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
// File: @openzeppelin/[email protected]/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^ 0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns(address) { return msg.sender; } function _msgData() internal view virtual returns(bytes calldata) { return msg.data; } } // File: @openzeppelin/[email protected]/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) 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); } // File: @openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^ 0.8.0; /** * @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); } // File: @openzeppelin/[email protected]/token/ERC20/ERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^ 0.8.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 Contracts guidelines: functions revert * instead 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, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * 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(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns(string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns(string memory) { return _symbol; } /** * @dev Returns the 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() public view virtual override returns(uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns(uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns(uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns(uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns(bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns(bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); 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) public virtual returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns(bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This 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); _afterTokenTransfer(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); _afterTokenTransfer(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); _afterTokenTransfer(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 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 { } /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual { } } // File: copy-planet-token.sol pragma solidity ^ 0.8.2; contract CopyPlanet is ERC20 { constructor() ERC20("Copy Planet", "COPY") { _mint(msg.sender, 100000000 * 10 ** decimals()); } }
* @dev Interface of the ERC20 standard as defined in the EIP./
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); }
10,416,189
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 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 ]
[ 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, 5831, 467, 654, 39, 3462, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 12, 11890, 5034, 1769, 203, 203, 915, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 12, 11890, 5034, 1769, 203, 203, 915, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 12, 6430, 1769, 203, 203, 915, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 12, 11890, 5034, 1769, 203, 203, 915, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 12, 6430, 1769, 203, 203, 915, 7412, 1265, 12, 203, 225, 1758, 5793, 16, 203, 225, 1758, 8027, 16, 203, 225, 2254, 5034, 3844, 203, 13, 3903, 1135, 12, 6430, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 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 ]
pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./SunflowerToken.sol"; interface ISunflowerMainV1 { function userInfo(uint256 pid, address account) external view returns (uint256); } // SunflowerMain is the master of Sunflower. He can make Sunflower and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SFR is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract SunflowerMainV2 is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SFRs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSunflowerPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSunflowerPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SFRs to distribute per block. uint256 lastRewardBlock; // Last block number that SFRs distribution occurs. uint256 accSunflowerPerShare; // Accumulated SFRs per share, times 1e12. See below. // Lock LP, until the end of mining. bool lock; uint256 totalAmount; } // The SFR TOKEN! SunflowerToken public sunflower; // Dev address. address public devaddr; // 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; // The block number when SFR mining starts. uint256 public startBlock; uint256 public halfPeriod; uint256 public maxSupply; ISunflowerMainV1 public sunflowerMainV1; IERC20 public pcc; 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); constructor( SunflowerToken _sunflower, address _devaddr, uint256 _startBlock, uint256 _halfPeriod, uint256 _maxSupply, ISunflowerMainV1 _sunflowerMainV1, IERC20 _pcc ) public { sunflower = _sunflower; devaddr = _devaddr; startBlock = _startBlock; halfPeriod = _halfPeriod; maxSupply = _maxSupply; sunflowerMainV1 = _sunflowerMainV1; pcc = _pcc; } function getPccBalanceV1() public view returns (uint256) { if(sunflower.totalSupply() >= halfPeriod && poolInfo[3].allocPoint == 0){ return 0; } return pcc.balanceOf(address(sunflowerMainV1)); } function getAmountV1(address _account) public view returns (uint256) { if(sunflower.totalSupply() >= halfPeriod && poolInfo[3].allocPoint == 0){ return 0; } return sunflowerMainV1.userInfo(3, _account); } function poolLength() external view returns (uint256) { return poolInfo.length; } function setStartBlock(uint256 _startBlock) public onlyOwner { require(block.number < startBlock); startBlock = _startBlock; } // 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. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, bool _lock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSunflowerPerShare: 0, lock: _lock, totalAmount: 0 })); } // Update the given pool's SFR allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function getBlockRewardNow() public view returns (uint256) { return getBlockReward(sunflower.totalSupply()); } // Reduce by 50% per halfPeriod. function getBlockReward(uint256 totalSupply) public view returns (uint256) { if(totalSupply >= maxSupply) return 0; uint256 nth = totalSupply / halfPeriod; if(0 == nth) { return 15625000000000000; } else if(1 == nth){ return 7813000000000000; } else if(2 == nth){ return 3906000000000000; } else if(3 == nth){ return 1953000000000000; } else if(4 == nth){ return 977000000000000; } else { return 488000000000000; } } function getBlockRewards(uint256 from, uint256 to) public view returns (uint256) { if(from < startBlock){ from = startBlock; } if(from >= to){ return 0; } uint256 totalSupply = sunflower.totalSupply(); if(totalSupply >= maxSupply) return 0; uint256 blockReward = getBlockReward(totalSupply); uint256 blockGap = to.sub(from); uint256 rewards = blockGap.mul(blockReward); if(rewards.add(totalSupply) > maxSupply){ if(totalSupply > maxSupply){ return 0; }else{ return maxSupply.sub(totalSupply); } } return rewards; } // View function to see pending SFRs on frontend. function pendingSunflower(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSunflowerPerShare = pool.accSunflowerPerShare; if(_pid == 3){ uint256 lpSupply = pool.totalAmount.add(getPccBalanceV1()); if (block.number > pool.lastRewardBlock && lpSupply != 0 && sunflower.totalSupply() < halfPeriod) { uint256 blockRewards = getBlockRewards(pool.lastRewardBlock, block.number); uint256 sunflowerReward = blockRewards.mul(9).div(10).mul(pool.allocPoint).div(totalAllocPoint); accSunflowerPerShare = accSunflowerPerShare.add(sunflowerReward.mul(1e12).div(lpSupply)); } return user.amount.add(getAmountV1(_user)).mul(accSunflowerPerShare).div(1e12).sub(user.rewardDebt); }else{ uint256 lpSupply = pool.totalAmount; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 blockRewards = getBlockRewards(pool.lastRewardBlock, block.number); uint256 sunflowerReward = blockRewards.mul(9).div(10).mul(pool.allocPoint).div(totalAllocPoint); accSunflowerPerShare = accSunflowerPerShare.add(sunflowerReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSunflowerPerShare).div(1e12).sub(user.rewardDebt); } } // 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); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.totalAmount; if(_pid == 3){ lpSupply = lpSupply.add(getPccBalanceV1()); } if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 blockRewards = getBlockRewards(pool.lastRewardBlock, block.number); uint256 sunflowerReward = blockRewards.mul(pool.allocPoint).div(totalAllocPoint); sunflower.mint(devaddr, sunflowerReward.div(10)); uint256 userRewards = sunflowerReward.mul(9).div(10); sunflower.mint(address(this), userRewards); pool.accSunflowerPerShare = pool.accSunflowerPerShare.add(userRewards.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to SunflowerMain for SFR allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 userAmount = user.amount; if(_pid == 3){ userAmount = userAmount.add(getAmountV1(msg.sender)); } if (userAmount > 0) { uint256 pending = userAmount.mul(pool.accSunflowerPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSunflowerTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); userAmount = userAmount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); } user.rewardDebt = userAmount.mul(pool.accSunflowerPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from SunflowerMain. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.lock == false || pool.lock && sunflower.totalSupply() >= halfPeriod); UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 userAmount = user.amount; if(_pid == 3){ userAmount = userAmount.add(getAmountV1(msg.sender)); } uint256 pending = userAmount.mul(pool.accSunflowerPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSunflowerTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); userAmount = userAmount.sub(_amount); pool.totalAmount = pool.totalAmount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = userAmount.mul(pool.accSunflowerPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.lock == false || pool.lock && sunflower.totalSupply() >= halfPeriod); UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sunflower transfer function, just in case if rounding error causes pool to not have enough SFRs. function safeSunflowerTransfer(address _to, uint256 _amount) internal { uint256 sunflowerBal = sunflower.balanceOf(address(this)); if (_amount > sunflowerBal) { sunflower.transfer(_to, sunflowerBal); } else { sunflower.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.lock == false || pool.lock && sunflower.totalSupply() >= halfPeriod); UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; }
12,807,777
[ 1, 1190, 9446, 2887, 5926, 310, 2973, 283, 6397, 18, 7141, 654, 16652, 16068, 20747, 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 ]
[ 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, 801, 24530, 1190, 9446, 12, 11890, 5034, 389, 6610, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 2583, 12, 6011, 18, 739, 422, 629, 747, 2845, 18, 739, 597, 13887, 2426, 264, 18, 4963, 3088, 1283, 1435, 1545, 8816, 5027, 1769, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 2845, 18, 9953, 1345, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 729, 18, 8949, 1769, 203, 3639, 3626, 512, 6592, 75, 2075, 1190, 9446, 12, 3576, 18, 15330, 16, 389, 6610, 16, 729, 18, 8949, 1769, 203, 3639, 729, 18, 8949, 273, 374, 31, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 374, 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 ]
./partial_match/1/0x43c6eE9D5B2369C5484f69E2Eb3361466855beDd/sources/FabricaToken.sol
* @dev Required interface of an ERC1155 compliant contract, as defined in the _Available since v3.1._/
interface IERC1155Upgradeable is IERC165Upgradeable { event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event ApprovalForAll(address indexed account, address indexed operator, bool approved); event URI(string value, uint256 indexed id); function balanceOf(address account, uint256 id) external view returns (uint256); function balanceOfBatch( address[] calldata accounts, uint256[] calldata ids ) external view returns (uint256[] memory); function setApprovalForAll(address operator, bool approved) external; function isApprovedForAll(address account, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } }
2,671,823
[ 1, 3705, 1560, 434, 392, 4232, 39, 2499, 2539, 24820, 6835, 16, 487, 2553, 316, 326, 389, 5268, 3241, 331, 23, 18, 21, 6315, 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 ]
[ 1, 1, 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, 5831, 467, 654, 39, 2499, 2539, 10784, 429, 353, 467, 654, 39, 28275, 10784, 429, 288, 203, 565, 871, 12279, 5281, 12, 2867, 8808, 3726, 16, 1758, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 612, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 12279, 4497, 12, 203, 3639, 1758, 8808, 3726, 16, 203, 3639, 1758, 8808, 628, 16, 203, 3639, 1758, 8808, 358, 16, 203, 3639, 2254, 5034, 8526, 3258, 16, 203, 3639, 2254, 5034, 8526, 924, 203, 565, 11272, 203, 203, 565, 871, 1716, 685, 1125, 1290, 1595, 12, 2867, 8808, 2236, 16, 1758, 8808, 3726, 16, 1426, 20412, 1769, 203, 203, 565, 871, 3699, 12, 1080, 460, 16, 2254, 5034, 8808, 612, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 16, 2254, 5034, 612, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 4497, 12, 203, 3639, 1758, 8526, 745, 892, 9484, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 3258, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 8526, 3778, 1769, 203, 203, 565, 445, 444, 23461, 1290, 1595, 12, 2867, 3726, 16, 1426, 20412, 13, 3903, 31, 203, 203, 565, 445, 353, 31639, 1290, 1595, 12, 2867, 2236, 16, 1758, 3726, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 565, 445, 4183, 5912, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 612, 16, 2254, 5034, 3844, 16, 1731, 745, 892, 501, 13, 3903, 31, 203, 203, 565, 445, 4183, 4497, 5912, 1265, 12, 203, 3639, 1758, 2 ]
pragma solidity ^0.6.6; pragma experimental ABIEncoderV2; import './Ownable.sol'; import './SafeMath.sol'; import './Address.sol'; import './ACONameFormatter.sol'; import './ACOAssetHelper.sol'; import './ERC20.sol'; import './IACOPool.sol'; import './IACOFactory.sol'; import './IACOStrategy.sol'; import './IACOToken.sol'; import './IACOFlashExercise.sol'; import './IUniswapV2Router02.sol'; import './IChiToken.sol'; /** * @title ACOPool * @dev A pool contract to trade ACO tokens. */ contract ACOPool is Ownable, ERC20, IACOPool { using Address for address; using SafeMath for uint256; uint256 internal constant POOL_PRECISION = 1000000000000000000; // 18 decimals uint256 internal constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /** * @dev Struct to store an ACO token trade data. */ struct ACOTokenData { /** * @dev Amount of tokens sold by the pool. */ uint256 amountSold; /** * @dev Amount of tokens purchased by the pool. */ uint256 amountPurchased; /** * @dev Index of the ACO token on the stored array. */ uint256 index; } /** * @dev Emitted when the strategy address has been changed. * @param oldStrategy Address of the previous strategy. * @param newStrategy Address of the new strategy. */ event SetStrategy(address indexed oldStrategy, address indexed newStrategy); /** * @dev Emitted when the base volatility has been changed. * @param oldBaseVolatility Value of the previous base volatility. * @param newBaseVolatility Value of the new base volatility. */ event SetBaseVolatility(uint256 indexed oldBaseVolatility, uint256 indexed newBaseVolatility); /** * @dev Emitted when a collateral has been deposited on the pool. * @param account Address of the account. * @param amount Amount deposited. */ event CollateralDeposited(address indexed account, uint256 amount); /** * @dev Emitted when the collateral and premium have been redeemed on the pool. * @param account Address of the account. * @param underlyingAmount Amount of underlying asset redeemed. * @param strikeAssetAmount Amount of strike asset redeemed. */ event Redeem(address indexed account, uint256 underlyingAmount, uint256 strikeAssetAmount); /** * @dev Emitted when the collateral has been restored on the pool. * @param amountOut Amount of the premium sold. * @param collateralIn Amount of collateral restored. */ event RestoreCollateral(uint256 amountOut, uint256 collateralIn); /** * @dev Emitted when an ACO token has been redeemed. * @param acoToken Address of the ACO token. * @param collateralIn Amount of collateral redeemed. * @param amountSold Total amount of ACO token sold by the pool. * @param amountPurchased Total amount of ACO token purchased by the pool. */ event ACORedeem(address indexed acoToken, uint256 collateralIn, uint256 amountSold, uint256 amountPurchased); /** * @dev Emitted when an ACO token has been exercised. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens exercised. * @param collateralIn Amount of collateral received. */ event ACOExercise(address indexed acoToken, uint256 tokenAmount, uint256 collateralIn); /** * @dev Emitted when an ACO token has been bought or sold by the pool. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param account Address of the account that is doing the swap. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens swapped. * @param price Value of the premium paid in strike asset. * @param protocolFee Value of the protocol fee paid in strike asset. * @param underlyingPrice The underlying price in strike asset. */ event Swap( bool indexed isPoolSelling, address indexed account, address indexed acoToken, uint256 tokenAmount, uint256 price, uint256 protocolFee, uint256 underlyingPrice ); /** * @dev UNIX timestamp that the pool can start to trade ACO tokens. */ uint256 public poolStart; /** * @dev The protocol fee percentage. (100000 = 100%) */ uint256 public fee; /** * @dev Address of the ACO flash exercise contract. */ IACOFlashExercise public acoFlashExercise; /** * @dev Address of the ACO factory contract. */ IACOFactory public acoFactory; /** * @dev Address of the Uniswap V2 router. */ IUniswapV2Router02 public uniswapRouter; /** * @dev Address of the Chi gas token. */ IChiToken public chiToken; /** * @dev Address of the protocol fee destination. */ address public feeDestination; /** * @dev Address of the underlying asset accepts by the pool. */ address public underlying; /** * @dev Address of the strike asset accepts by the pool. */ address public strikeAsset; /** * @dev Value of the minimum strike price on ACO token that the pool accept to trade. */ uint256 public minStrikePrice; /** * @dev Value of the maximum strike price on ACO token that the pool accept to trade. */ uint256 public maxStrikePrice; /** * @dev Value of the minimum UNIX expiration on ACO token that the pool accept to trade. */ uint256 public minExpiration; /** * @dev Value of the maximum UNIX expiration on ACO token that the pool accept to trade. */ uint256 public maxExpiration; /** * @dev True whether the pool accepts CALL options, otherwise the pool accepts only PUT options. */ bool public isCall; /** * @dev True whether the pool can also buy ACO tokens, otherwise the pool only sells ACO tokens. */ bool public canBuy; /** * @dev Address of the strategy. */ IACOStrategy public strategy; /** * @dev Percentage value for the base volatility. (100000 = 100%) */ uint256 public baseVolatility; /** * @dev Total amount of collateral deposited. */ uint256 public collateralDeposited; /** * @dev Total amount in strike asset spent buying ACO tokens. */ uint256 public strikeAssetSpentBuying; /** * @dev Total amount in strike asset earned selling ACO tokens. */ uint256 public strikeAssetEarnedSelling; /** * @dev Array of ACO tokens currently negotiated. */ address[] public acoTokens; /** * @dev Mapping for ACO tokens data currently negotiated. */ mapping(address => ACOTokenData) public acoTokensData; /** * @dev Underlying asset precision. (18 decimals = 1000000000000000000) */ uint256 internal underlyingPrecision; /** * @dev Strike asset precision. (6 decimals = 1000000) */ uint256 internal strikeAssetPrecision; /** * @dev Modifier to check if the pool is open to trade. */ modifier open() { require(isStarted() && notFinished(), "ACOPool:: Pool is not open"); _; } /** * @dev Modifier to apply the Chi gas token and save gas. */ modifier discountCHI { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; chiToken.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947); } /** * @dev Function to initialize the contract. * It should be called by the ACO pool factory when creating the pool. * It must be called only once. The first `require` is to guarantee that behavior. * @param initData The initialize data. */ function init(InitData calldata initData) external override { require(underlying == address(0) && strikeAsset == address(0) && minExpiration == 0, "ACOPool::init: Already initialized"); require(initData.acoFactory.isContract(), "ACOPool:: Invalid ACO Factory"); require(initData.acoFlashExercise.isContract(), "ACOPool:: Invalid ACO flash exercise"); require(initData.chiToken.isContract(), "ACOPool:: Invalid Chi Token"); require(initData.fee <= 12500, "ACOPool:: The maximum fee allowed is 12.5%"); require(initData.poolStart > block.timestamp, "ACOPool:: Invalid pool start"); require(initData.minExpiration > block.timestamp, "ACOPool:: Invalid expiration"); require(initData.minStrikePrice <= initData.maxStrikePrice, "ACOPool:: Invalid strike price range"); require(initData.minStrikePrice > 0, "ACOPool:: Invalid strike price"); require(initData.minExpiration <= initData.maxExpiration, "ACOPool:: Invalid expiration range"); require(initData.underlying != initData.strikeAsset, "ACOPool:: Same assets"); require(ACOAssetHelper._isEther(initData.underlying) || initData.underlying.isContract(), "ACOPool:: Invalid underlying"); require(ACOAssetHelper._isEther(initData.strikeAsset) || initData.strikeAsset.isContract(), "ACOPool:: Invalid strike asset"); super.init(); poolStart = initData.poolStart; acoFlashExercise = IACOFlashExercise(initData.acoFlashExercise); acoFactory = IACOFactory(initData.acoFactory); chiToken = IChiToken(initData.chiToken); fee = initData.fee; feeDestination = initData.feeDestination; underlying = initData.underlying; strikeAsset = initData.strikeAsset; minStrikePrice = initData.minStrikePrice; maxStrikePrice = initData.maxStrikePrice; minExpiration = initData.minExpiration; maxExpiration = initData.maxExpiration; isCall = initData.isCall; canBuy = initData.canBuy; address _uniswapRouter = IACOFlashExercise(initData.acoFlashExercise).uniswapRouter(); uniswapRouter = IUniswapV2Router02(_uniswapRouter); _setStrategy(initData.strategy); _setBaseVolatility(initData.baseVolatility); _setAssetsPrecision(initData.underlying, initData.strikeAsset); _approveAssetsOnRouter(initData.isCall, initData.canBuy, _uniswapRouter, initData.underlying, initData.strikeAsset); } receive() external payable { } /** * @dev Function to get the token name. */ function name() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token symbol, that it is equal to the name. */ function symbol() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token decimals. */ function decimals() public view override returns(uint8) { return 18; } /** * @dev Function to get whether the pool already started trade ACO tokens. */ function isStarted() public view returns(bool) { return block.timestamp >= poolStart; } /** * @dev Function to get whether the pool is not finished. */ function notFinished() public view returns(bool) { return block.timestamp < maxExpiration; } /** * @dev Function to get the number of ACO tokens currently negotiated. */ function numberOfACOTokensCurrentlyNegotiated() public override view returns(uint256) { return acoTokens.length; } /** * @dev Function to get the pool collateral asset. */ function collateral() public override view returns(address) { if (isCall) { return underlying; } else { return strikeAsset; } } /** * @dev Function to quote an ACO token swap. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The swap price, the protocol fee charged on the swap, and the underlying price in strike asset. */ function quote(bool isBuying, address acoToken, uint256 tokenAmount) open public override view returns(uint256, uint256, uint256) { (uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice,) = _internalQuote(isBuying, acoToken, tokenAmount); return (swapPrice, protocolFee, underlyingPrice); } /** * @dev Function to set the pool strategy address. * Only can be called by the ACO pool factory contract. * @param newStrategy Address of the new strategy. */ function setStrategy(address newStrategy) onlyOwner external override { _setStrategy(newStrategy); } /** * @dev Function to set the pool base volatility percentage. (100000 = 100%) * Only can be called by the ACO pool factory contract. * @param newBaseVolatility Value of the new base volatility. */ function setBaseVolatility(uint256 newBaseVolatility) onlyOwner external override { _setBaseVolatility(newBaseVolatility); } /** * @dev Function to deposit on the pool. * Only can be called when the pool is not started. * @param collateralAmount Amount of collateral to be deposited. * @param to Address of the destination of the pool token. * @return The amount of pool tokens minted. */ function deposit(uint256 collateralAmount, address to) public override payable returns(uint256) { require(!isStarted(), "ACOPool:: Pool already started"); require(collateralAmount > 0, "ACOPool:: Invalid collateral amount"); require(to != address(0) && to != address(this), "ACOPool:: Invalid to"); (uint256 normalizedAmount, uint256 amount) = _getNormalizedDepositAmount(collateralAmount); ACOAssetHelper._receiveAsset(collateral(), amount); collateralDeposited = collateralDeposited.add(amount); _mintAction(to, normalizedAmount); emit CollateralDeposited(msg.sender, amount); return normalizedAmount; } /** * @dev Function to swap an ACO token with the pool. * Only can be called when the pool is opened. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function swap( bool isBuying, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) open public override returns(uint256) { return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline); } /** * @dev Function to swap an ACO token with the pool and use Chi token to save gas. * Only can be called when the pool is opened. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function swapWithGasToken( bool isBuying, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) open discountCHI public override returns(uint256) { return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline); } /** * @dev Function to redeem the collateral and the premium from the pool. * Only can be called when the pool is finished. * @return The amount of underlying asset received and the amount of strike asset received. */ function redeem() public override returns(uint256, uint256) { return _redeem(msg.sender); } /** * @dev Function to redeem the collateral and the premium from the pool from an account. * Only can be called when the pool is finished. * The allowance must be respected. * The transaction sender will receive the redeemed assets. * @param account Address of the account. * @return The amount of underlying asset received and the amount of strike asset received. */ function redeemFrom(address account) public override returns(uint256, uint256) { return _redeem(account); } /** * @dev Function to redeem the collateral from the ACO tokens negotiated on the pool. * It redeems the collateral only if the respective ACO token is expired. */ function redeemACOTokens() public override { for (uint256 i = acoTokens.length; i > 0; --i) { address acoToken = acoTokens[i - 1]; uint256 expiryTime = IACOToken(acoToken).expiryTime(); _redeemACOToken(acoToken, expiryTime); } } /** * @dev Function to redeem the collateral from an ACO token. * It redeems the collateral only if the ACO token is expired. * @param acoToken Address of the ACO token. */ function redeemACOToken(address acoToken) public override { (,uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); _redeemACOToken(acoToken, expiryTime); } /** * @dev Function to exercise an ACO token negotiated on the pool. * Only ITM ACO tokens are exercisable. * @param acoToken Address of the ACO token. */ function exerciseACOToken(address acoToken) public override { (uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); uint256 exercisableAmount = _getExercisableAmount(acoToken); require(exercisableAmount > 0, "ACOPool:: Exercise is not available"); address _strikeAsset = strikeAsset; address _underlying = underlying; bool _isCall = isCall; uint256 collateralAmount; address _collateral; if (_isCall) { _collateral = _underlying; collateralAmount = exercisableAmount; } else { _collateral = _strikeAsset; collateralAmount = IACOToken(acoToken).getCollateralAmount(exercisableAmount); } uint256 collateralAvailable = _getPoolBalanceOf(_collateral); ACOTokenData storage data = acoTokensData[acoToken]; (bool canExercise, uint256 minIntrinsicValue) = strategy.checkExercise(IACOStrategy.CheckExercise( _underlying, _strikeAsset, _isCall, strikePrice, expiryTime, collateralAmount, collateralAvailable, data.amountPurchased, data.amountSold )); require(canExercise, "ACOPool:: Exercise is not possible"); if (IACOToken(acoToken).allowance(address(this), address(acoFlashExercise)) < exercisableAmount) { _setAuthorizedSpender(acoToken, address(acoFlashExercise)); } acoFlashExercise.flashExercise(acoToken, exercisableAmount, minIntrinsicValue, block.timestamp); uint256 collateralIn = _getPoolBalanceOf(_collateral).sub(collateralAvailable); emit ACOExercise(acoToken, exercisableAmount, collateralIn); } /** * @dev Function to restore the collateral on the pool by selling the other asset balance. */ function restoreCollateral() public override { address _strikeAsset = strikeAsset; address _underlying = underlying; bool _isCall = isCall; uint256 underlyingBalance = _getPoolBalanceOf(_underlying); uint256 strikeAssetBalance = _getPoolBalanceOf(_strikeAsset); uint256 balanceOut; address assetIn; address assetOut; if (_isCall) { balanceOut = strikeAssetBalance; assetIn = _underlying; assetOut = _strikeAsset; } else { balanceOut = underlyingBalance; assetIn = _strikeAsset; assetOut = _underlying; } require(balanceOut > 0, "ACOPool:: No balance"); uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, false); uint256 minToReceive; if (_isCall) { minToReceive = balanceOut.mul(underlyingPrecision).div(acceptablePrice); } else { minToReceive = balanceOut.mul(acceptablePrice).div(underlyingPrecision); } _swapAssetsExactAmountOut(assetOut, assetIn, minToReceive, balanceOut); uint256 collateralIn; if (_isCall) { collateralIn = _getPoolBalanceOf(_underlying).sub(underlyingBalance); } else { collateralIn = _getPoolBalanceOf(_strikeAsset).sub(strikeAssetBalance); } emit RestoreCollateral(balanceOut, collateralIn); } /** * @dev Internal function to swap an ACO token with the pool. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function _swap( bool isPoolSelling, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) internal returns(uint256) { require(block.timestamp <= deadline, "ACOPool:: Swap deadline"); require(to != address(0) && to != acoToken && to != address(this), "ACOPool:: Invalid destination"); (uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice, uint256 collateralAmount) = _internalQuote(isPoolSelling, acoToken, tokenAmount); uint256 amount; if (isPoolSelling) { amount = _internalSelling(to, acoToken, collateralAmount, tokenAmount, restriction, swapPrice, protocolFee); } else { amount = _internalBuying(to, acoToken, tokenAmount, restriction, swapPrice, protocolFee); } if (protocolFee > 0) { ACOAssetHelper._transferAsset(strikeAsset, feeDestination, protocolFee); } emit Swap(isPoolSelling, msg.sender, acoToken, tokenAmount, swapPrice, protocolFee, underlyingPrice); return amount; } /** * @dev Internal function to quote an ACO token price. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The quote price, the protocol fee charged, the underlying price, and the collateral amount. */ function _internalQuote(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256, uint256, uint256) { require(isPoolSelling || canBuy, "ACOPool:: The pool only sell"); require(tokenAmount > 0, "ACOPool:: Invalid token amount"); (uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); require(expiryTime > block.timestamp, "ACOPool:: ACO token expired"); (uint256 collateralAmount, uint256 collateralAvailable) = _getSizeData(isPoolSelling, acoToken, tokenAmount); (uint256 price, uint256 underlyingPrice,) = _strategyQuote(acoToken, isPoolSelling, strikePrice, expiryTime, collateralAmount, collateralAvailable); price = price.mul(tokenAmount).div(underlyingPrecision); uint256 protocolFee = 0; if (fee > 0) { protocolFee = price.mul(fee).div(100000); if (isPoolSelling) { price = price.add(protocolFee); } else { price = price.sub(protocolFee); } } require(price > 0, "ACOPool:: Invalid quote"); return (price, protocolFee, underlyingPrice, collateralAmount); } /** * @dev Internal function to the size data for a quote. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The collateral amount and the collateral available on the pool. */ function _getSizeData(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256) { uint256 collateralAmount; uint256 collateralAvailable; if (isCall) { collateralAvailable = _getPoolBalanceOf(underlying); collateralAmount = tokenAmount; } else { collateralAvailable = _getPoolBalanceOf(strikeAsset); collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount); require(collateralAmount > 0, "ACOPool:: Token amount is too small"); } require(!isPoolSelling || collateralAmount <= collateralAvailable, "ACOPool:: Insufficient liquidity"); return (collateralAmount, collateralAvailable); } /** * @dev Internal function to quote on the strategy contract. * @param acoToken Address of the ACO token. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param strikePrice ACO token strike price. * @param expiryTime ACO token expiry time on UNIX. * @param collateralAmount Amount of collateral for the order size. * @param collateralAvailable Amount of collateral available on the pool. * @return The quote price, the underlying price and the volatility. */ function _strategyQuote( address acoToken, bool isPoolSelling, uint256 strikePrice, uint256 expiryTime, uint256 collateralAmount, uint256 collateralAvailable ) internal view returns(uint256, uint256, uint256) { ACOTokenData storage data = acoTokensData[acoToken]; return strategy.quote(IACOStrategy.OptionQuote( isPoolSelling, underlying, strikeAsset, isCall, strikePrice, expiryTime, baseVolatility, collateralAmount, collateralAvailable, collateralDeposited, strikeAssetEarnedSelling, strikeAssetSpentBuying, data.amountPurchased, data.amountSold )); } /** * @dev Internal function to sell ACO tokens. * @param to Address of the destination of the ACO tokens. * @param acoToken Address of the ACO token. * @param collateralAmount Order collateral amount. * @param tokenAmount Order token amount. * @param maxPayment Maximum value to be paid for the ACO tokens. * @param swapPrice The swap price quoted. * @param protocolFee The protocol fee amount. * @return The ACO token amount sold. */ function _internalSelling( address to, address acoToken, uint256 collateralAmount, uint256 tokenAmount, uint256 maxPayment, uint256 swapPrice, uint256 protocolFee ) internal returns(uint256) { require(swapPrice <= maxPayment, "ACOPool:: Swap restriction"); ACOAssetHelper._callTransferFromERC20(strikeAsset, msg.sender, address(this), swapPrice); uint256 acoBalance = _getPoolBalanceOf(acoToken); ACOTokenData storage acoTokenData = acoTokensData[acoToken]; uint256 _amountSold = acoTokenData.amountSold; if (_amountSold == 0 && acoTokenData.amountPurchased == 0) { acoTokenData.index = acoTokens.length; acoTokens.push(acoToken); } if (tokenAmount > acoBalance) { tokenAmount = acoBalance; if (acoBalance > 0) { collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount.sub(acoBalance)); } if (collateralAmount > 0) { address _collateral = collateral(); if (ACOAssetHelper._isEther(_collateral)) { tokenAmount = tokenAmount.add(IACOToken(acoToken).mintPayable{value: collateralAmount}()); } else { if (_amountSold == 0) { _setAuthorizedSpender(_collateral, acoToken); } tokenAmount = tokenAmount.add(IACOToken(acoToken).mint(collateralAmount)); } } } acoTokenData.amountSold = tokenAmount.add(_amountSold); strikeAssetEarnedSelling = swapPrice.sub(protocolFee).add(strikeAssetEarnedSelling); ACOAssetHelper._callTransferERC20(acoToken, to, tokenAmount); return tokenAmount; } /** * @dev Internal function to buy ACO tokens. * @param to Address of the destination of the premium. * @param acoToken Address of the ACO token. * @param tokenAmount Order token amount. * @param minToReceive Minimum value to be received for the ACO tokens. * @param swapPrice The swap price quoted. * @param protocolFee The protocol fee amount. * @return The premium amount transferred. */ function _internalBuying( address to, address acoToken, uint256 tokenAmount, uint256 minToReceive, uint256 swapPrice, uint256 protocolFee ) internal returns(uint256) { require(swapPrice >= minToReceive, "ACOPool:: Swap restriction"); uint256 requiredStrikeAsset = swapPrice.add(protocolFee); if (isCall) { _getStrikeAssetAmount(requiredStrikeAsset); } ACOAssetHelper._callTransferFromERC20(acoToken, msg.sender, address(this), tokenAmount); ACOTokenData storage acoTokenData = acoTokensData[acoToken]; uint256 _amountPurchased = acoTokenData.amountPurchased; if (_amountPurchased == 0 && acoTokenData.amountSold == 0) { acoTokenData.index = acoTokens.length; acoTokens.push(acoToken); } acoTokenData.amountPurchased = tokenAmount.add(_amountPurchased); strikeAssetSpentBuying = requiredStrikeAsset.add(strikeAssetSpentBuying); ACOAssetHelper._transferAsset(strikeAsset, to, swapPrice); return swapPrice; } /** * @dev Internal function to get the normalized deposit amount. * The pool token has always with 18 decimals. * @param collateralAmount Amount of collateral to be deposited. * @return The normalized token amount and the collateral amount. */ function _getNormalizedDepositAmount(uint256 collateralAmount) internal view returns(uint256, uint256) { uint256 basePrecision = isCall ? underlyingPrecision : strikeAssetPrecision; uint256 normalizedAmount; if (basePrecision > POOL_PRECISION) { uint256 adjust = basePrecision.div(POOL_PRECISION); normalizedAmount = collateralAmount.div(adjust); collateralAmount = normalizedAmount.mul(adjust); } else if (basePrecision < POOL_PRECISION) { normalizedAmount = collateralAmount.mul(POOL_PRECISION.div(basePrecision)); } else { normalizedAmount = collateralAmount; } require(normalizedAmount > 0, "ACOPool:: Invalid collateral amount"); return (normalizedAmount, collateralAmount); } /** * @dev Internal function to get an amount of strike asset for the pool. * The pool swaps the collateral for it if necessary. * @param strikeAssetAmount Amount of strike asset required. */ function _getStrikeAssetAmount(uint256 strikeAssetAmount) internal { address _strikeAsset = strikeAsset; uint256 balance = _getPoolBalanceOf(_strikeAsset); if (balance < strikeAssetAmount) { uint256 amountToPurchase = strikeAssetAmount.sub(balance); address _underlying = underlying; uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, true); uint256 maxPayment = amountToPurchase.mul(underlyingPrecision).div(acceptablePrice); _swapAssetsExactAmountIn(_underlying, _strikeAsset, amountToPurchase, maxPayment); } } /** * @dev Internal function to redeem the collateral from an ACO token. * It redeems the collateral only if the ACO token is expired. * @param acoToken Address of the ACO token. * @param expiryTime ACO token expiry time in UNIX. */ function _redeemACOToken(address acoToken, uint256 expiryTime) internal { if (expiryTime <= block.timestamp) { uint256 collateralIn = 0; if (IACOToken(acoToken).currentCollateralizedTokens(address(this)) > 0) { collateralIn = IACOToken(acoToken).redeem(); } ACOTokenData storage data = acoTokensData[acoToken]; uint256 lastIndex = acoTokens.length - 1; if (lastIndex != data.index) { address last = acoTokens[lastIndex]; acoTokensData[last].index = data.index; acoTokens[data.index] = last; } emit ACORedeem(acoToken, collateralIn, data.amountSold, data.amountPurchased); acoTokens.pop(); delete acoTokensData[acoToken]; } } /** * @dev Internal function to redeem the collateral and the premium from the pool from an account. * @param account Address of the account. * @return The amount of underlying asset received and the amount of strike asset received. */ function _redeem(address account) internal returns(uint256, uint256) { uint256 share = balanceOf(account); require(share > 0, "ACOPool:: Account with no share"); require(!notFinished(), "ACOPool:: Pool is not finished"); redeemACOTokens(); uint256 _totalSupply = totalSupply(); uint256 underlyingBalance = share.mul(_getPoolBalanceOf(underlying)).div(_totalSupply); uint256 strikeAssetBalance = share.mul(_getPoolBalanceOf(strikeAsset)).div(_totalSupply); _callBurn(account, share); if (underlyingBalance > 0) { ACOAssetHelper._transferAsset(underlying, msg.sender, underlyingBalance); } if (strikeAssetBalance > 0) { ACOAssetHelper._transferAsset(strikeAsset, msg.sender, strikeAssetBalance); } emit Redeem(msg.sender, underlyingBalance, strikeAssetBalance); return (underlyingBalance, strikeAssetBalance); } /** * @dev Internal function to burn pool tokens. * @param account Address of the account. * @param tokenAmount Amount of pool tokens to be burned. */ function _callBurn(address account, uint256 tokenAmount) internal { if (account == msg.sender) { super._burnAction(account, tokenAmount); } else { super._burnFrom(account, tokenAmount); } } /** * @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be sold. * @param assetOut Address of the asset to be sold. * @param assetIn Address of the asset to be purchased. * @param minAmountIn Minimum amount to be received. * @param amountOut The exact amount to be sold. */ function _swapAssetsExactAmountOut(address assetOut, address assetIn, uint256 minAmountIn, uint256 amountOut) internal { address[] memory path = new address[](2); if (ACOAssetHelper._isEther(assetOut)) { path[0] = acoFlashExercise.weth(); path[1] = assetIn; uniswapRouter.swapExactETHForTokens{value: amountOut}(minAmountIn, path, address(this), block.timestamp); } else if (ACOAssetHelper._isEther(assetIn)) { path[0] = assetOut; path[1] = acoFlashExercise.weth(); uniswapRouter.swapExactTokensForETH(amountOut, minAmountIn, path, address(this), block.timestamp); } else { path[0] = assetOut; path[1] = assetIn; uniswapRouter.swapExactTokensForTokens(amountOut, minAmountIn, path, address(this), block.timestamp); } } /** * @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be purchased. * @param assetOut Address of the asset to be sold. * @param assetIn Address of the asset to be purchased. * @param amountIn The exact amount to be purchased. * @param maxAmountOut Maximum amount to be paid. */ function _swapAssetsExactAmountIn(address assetOut, address assetIn, uint256 amountIn, uint256 maxAmountOut) internal { address[] memory path = new address[](2); if (ACOAssetHelper._isEther(assetOut)) { path[0] = acoFlashExercise.weth(); path[1] = assetIn; uniswapRouter.swapETHForExactTokens{value: maxAmountOut}(amountIn, path, address(this), block.timestamp); } else if (ACOAssetHelper._isEther(assetIn)) { path[0] = assetOut; path[1] = acoFlashExercise.weth(); uniswapRouter.swapTokensForExactETH(amountIn, maxAmountOut, path, address(this), block.timestamp); } else { path[0] = assetOut; path[1] = assetIn; uniswapRouter.swapTokensForExactTokens(amountIn, maxAmountOut, path, address(this), block.timestamp); } } /** * @dev Internal function to set the strategy address. * @param newStrategy Address of the new strategy. */ function _setStrategy(address newStrategy) internal { require(newStrategy.isContract(), "ACOPool:: Invalid strategy"); emit SetStrategy(address(strategy), newStrategy); strategy = IACOStrategy(newStrategy); } /** * @dev Internal function to set the base volatility percentage. (100000 = 100%) * @param newBaseVolatility Value of the new base volatility. */ function _setBaseVolatility(uint256 newBaseVolatility) internal { require(newBaseVolatility > 0, "ACOPool:: Invalid base volatility"); emit SetBaseVolatility(baseVolatility, newBaseVolatility); baseVolatility = newBaseVolatility; } /** * @dev Internal function to set the pool assets precisions. * @param _underlying Address of the underlying asset. * @param _strikeAsset Address of the strike asset. */ function _setAssetsPrecision(address _underlying, address _strikeAsset) internal { underlyingPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_underlying)); strikeAssetPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_strikeAsset)); } /** * @dev Internal function to infinite authorize the pool assets on the Uniswap V2 router. * @param _isCall True whether it is a CALL option, otherwise it is PUT. * @param _canBuy True whether the pool can also buy ACO tokens, otherwise it only sells. * @param _uniswapRouter Address of the Uniswap V2 router. * @param _underlying Address of the underlying asset. * @param _strikeAsset Address of the strike asset. */ function _approveAssetsOnRouter( bool _isCall, bool _canBuy, address _uniswapRouter, address _underlying, address _strikeAsset ) internal { if (_isCall) { if (!ACOAssetHelper._isEther(_strikeAsset)) { _setAuthorizedSpender(_strikeAsset, _uniswapRouter); } if (_canBuy && !ACOAssetHelper._isEther(_underlying)) { _setAuthorizedSpender(_underlying, _uniswapRouter); } } else if (!ACOAssetHelper._isEther(_underlying)) { _setAuthorizedSpender(_underlying, _uniswapRouter); } } /** * @dev Internal function to infinite authorize a spender on an asset. * @param asset Address of the asset. * @param spender Address of the spender to be authorized. */ function _setAuthorizedSpender(address asset, address spender) internal { ACOAssetHelper._callApproveERC20(asset, spender, MAX_UINT); } /** * @dev Internal function to get the pool balance of an asset. * @param asset Address of the asset. * @return The pool balance. */ function _getPoolBalanceOf(address asset) internal view returns(uint256) { return ACOAssetHelper._getAssetBalanceOf(asset, address(this)); } /** * @dev Internal function to get the exercible amount of an ACO token. * @param acoToken Address of the ACO token. * @return The exercisable amount. */ function _getExercisableAmount(address acoToken) internal view returns(uint256) { uint256 balance = _getPoolBalanceOf(acoToken); if (balance > 0) { uint256 collaterized = IACOToken(acoToken).currentCollateralizedTokens(address(this)); if (balance > collaterized) { return balance.sub(collaterized); } } return 0; } /** * @dev Internal function to get an accepted ACO token by the pool. * @param acoToken Address of the ACO token. * @return The ACO token strike price, and the ACO token expiration. */ function _getValidACOTokenStrikePriceAndExpiration(address acoToken) internal view returns(uint256, uint256) { (address _underlying, address _strikeAsset, bool _isCall, uint256 _strikePrice, uint256 _expiryTime) = acoFactory.acoTokenData(acoToken); require( _underlying == underlying && _strikeAsset == strikeAsset && _isCall == isCall && _strikePrice >= minStrikePrice && _strikePrice <= maxStrikePrice && _expiryTime >= minExpiration && _expiryTime <= maxExpiration, "ACOPool:: Invalid ACO Token" ); return (_strikePrice, _expiryTime); } /** * @dev Internal function to get the token name. * The token name is assembled with the token data: * ACO POOL UNDERLYING_SYMBOL-STRIKE_ASSET_SYMBOL-TYPE-{ONLY_SELL}-MIN_STRIKE_PRICE-MAX_STRIKE_PRICE-MIN_EXPIRATION-MAX_EXPIRATION * @return The token name. */ function _name() internal view returns(string memory) { uint8 strikeDecimals = ACOAssetHelper._getAssetDecimals(strikeAsset); string memory strikePriceFormatted; if (minStrikePrice != maxStrikePrice) { strikePriceFormatted = string(abi.encodePacked(ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals), "-", ACONameFormatter.formatNumber(maxStrikePrice, strikeDecimals))); } else { strikePriceFormatted = ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals); } string memory dateFormatted; if (minExpiration != maxExpiration) { dateFormatted = string(abi.encodePacked(ACONameFormatter.formatTime(minExpiration), "-", ACONameFormatter.formatTime(maxExpiration))); } else { dateFormatted = ACONameFormatter.formatTime(minExpiration); } return string(abi.encodePacked( "ACO POOL ", ACOAssetHelper._getAssetSymbol(underlying), "-", ACOAssetHelper._getAssetSymbol(strikeAsset), "-", ACONameFormatter.formatType(isCall), (canBuy ? "" : "-SELL"), "-", strikePriceFormatted, "-", dateFormatted )); } }
* @dev Internal function to set the base volatility percentage. (100000 = 100%) @param newBaseVolatility Value of the new base volatility./
function _setBaseVolatility(uint256 newBaseVolatility) internal { require(newBaseVolatility > 0, "ACOPool:: Invalid base volatility"); emit SetBaseVolatility(baseVolatility, newBaseVolatility); baseVolatility = newBaseVolatility; }
48,908
[ 1, 3061, 445, 358, 444, 326, 1026, 6626, 30139, 11622, 18, 261, 21, 11706, 273, 2130, 9, 13, 225, 394, 2171, 17431, 30139, 1445, 434, 326, 394, 1026, 6626, 30139, 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, 565, 445, 389, 542, 2171, 17431, 30139, 12, 11890, 5034, 394, 2171, 17431, 30139, 13, 2713, 288, 203, 3639, 2583, 12, 2704, 2171, 17431, 30139, 405, 374, 16, 315, 2226, 51, 2864, 2866, 1962, 1026, 6626, 30139, 8863, 203, 3639, 3626, 1000, 2171, 17431, 30139, 12, 1969, 17431, 30139, 16, 394, 2171, 17431, 30139, 1769, 203, 3639, 1026, 17431, 30139, 273, 394, 2171, 17431, 30139, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x8815a120eE650A0b1bf94A94fc363f51aa3a5760/sources/KushoStaking.sol
Interfaces for ERC20 and ERC721 Constructor function to set the rewards token and the NFT collection addresses
contract KushoStaking is ReentrancyGuard { using SafeERC20 for IERC20; IERC20 public immutable rewardsToken; IERC721 public immutable nftCollection; pragma solidity ^0.8.4; constructor(IERC721 _nftCollection, IERC20 _rewardsToken) { nftCollection = _nftCollection; rewardsToken = _rewardsToken; } struct StakedToken { address staker; uint256 tokenId; } struct Staker { uint256 amountStaked; StakedToken[] stakedTokens; uint256 timeOfLastUpdate; uint256 unclaimedRewards; } uint256 private rewardsPerHour = 125000000000000000; mapping(address => Staker) public stakers; mapping(uint256 => address) public stakerAddress; function stake(uint256[] calldata tokenIds) external nonReentrant { if (stakers[msg.sender].amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require( nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); nftCollection.transferFrom(msg.sender, address(this), _tokenId); StakedToken memory stakedToken = StakedToken(msg.sender, _tokenId); stakers[msg.sender].stakedTokens.push(stakedToken); stakers[msg.sender].amountStaked++; stakerAddress[_tokenId] = msg.sender; stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function stake(uint256[] calldata tokenIds) external nonReentrant { if (stakers[msg.sender].amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require( nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); nftCollection.transferFrom(msg.sender, address(this), _tokenId); StakedToken memory stakedToken = StakedToken(msg.sender, _tokenId); stakers[msg.sender].stakedTokens.push(stakedToken); stakers[msg.sender].amountStaked++; stakerAddress[_tokenId] = msg.sender; stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function stake(uint256[] calldata tokenIds) external nonReentrant { if (stakers[msg.sender].amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require( nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); nftCollection.transferFrom(msg.sender, address(this), _tokenId); StakedToken memory stakedToken = StakedToken(msg.sender, _tokenId); stakers[msg.sender].stakedTokens.push(stakedToken); stakers[msg.sender].amountStaked++; stakerAddress[_tokenId] = msg.sender; stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function unstake(uint256[] calldata tokenIds) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 j = 0; j < stakers[msg.sender].stakedTokens.length; j++) { if (stakers[msg.sender].stakedTokens[j].tokenId == _tokenId) { index = j; break; } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].amountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function unstake(uint256[] calldata tokenIds) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 j = 0; j < stakers[msg.sender].stakedTokens.length; j++) { if (stakers[msg.sender].stakedTokens[j].tokenId == _tokenId) { index = j; break; } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].amountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function unstake(uint256[] calldata tokenIds) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 j = 0; j < stakers[msg.sender].stakedTokens.length; j++) { if (stakers[msg.sender].stakedTokens[j].tokenId == _tokenId) { index = j; break; } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].amountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function unstake(uint256[] calldata tokenIds) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 j = 0; j < stakers[msg.sender].stakedTokens.length; j++) { if (stakers[msg.sender].stakedTokens[j].tokenId == _tokenId) { index = j; break; } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].amountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function claimRewards() external { uint256 rewards = calculateRewards(msg.sender) + stakers[msg.sender].unclaimedRewards; require(rewards > 0, "You have no rewards to claim"); stakers[msg.sender].timeOfLastUpdate = block.timestamp; stakers[msg.sender].unclaimedRewards = 0; rewardsToken.safeTransfer(msg.sender, rewards); } function availableRewards(address _staker) public view returns (uint256) { uint256 rewards = calculateRewards(_staker) + stakers[_staker].unclaimedRewards; return rewards; } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function calculateRewards(address _staker) internal view returns (uint256 _rewards) { return ((( ((block.timestamp - stakers[_staker].timeOfLastUpdate) * stakers[_staker].amountStaked) ) * rewardsPerHour) / 3600); } }
5,681,485
[ 1, 10273, 364, 4232, 39, 3462, 471, 4232, 39, 27, 5340, 11417, 445, 358, 444, 326, 283, 6397, 1147, 471, 326, 423, 4464, 1849, 6138, 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, 16351, 1475, 1218, 83, 510, 6159, 353, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 11732, 283, 6397, 1345, 31, 203, 565, 467, 654, 39, 27, 5340, 1071, 11732, 290, 1222, 2532, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 3885, 12, 45, 654, 39, 27, 5340, 389, 82, 1222, 2532, 16, 467, 654, 39, 3462, 389, 266, 6397, 1345, 13, 288, 203, 3639, 290, 1222, 2532, 273, 389, 82, 1222, 2532, 31, 203, 3639, 283, 6397, 1345, 273, 389, 266, 6397, 1345, 31, 203, 565, 289, 203, 203, 565, 1958, 934, 9477, 1345, 288, 203, 3639, 1758, 384, 6388, 31, 203, 3639, 2254, 5034, 1147, 548, 31, 203, 565, 289, 203, 203, 565, 1958, 934, 6388, 288, 203, 3639, 2254, 5034, 3844, 510, 9477, 31, 203, 203, 3639, 934, 9477, 1345, 8526, 384, 9477, 5157, 31, 203, 203, 3639, 2254, 5034, 813, 951, 3024, 1891, 31, 203, 203, 3639, 2254, 5034, 6301, 80, 4581, 329, 17631, 14727, 31, 203, 565, 289, 203, 203, 203, 203, 203, 565, 2254, 5034, 3238, 283, 6397, 2173, 13433, 273, 30616, 12648, 17877, 31, 203, 565, 2874, 12, 2867, 516, 934, 6388, 13, 1071, 384, 581, 414, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 384, 6388, 1887, 31, 203, 565, 445, 384, 911, 12, 11890, 5034, 8526, 745, 892, 1147, 2673, 13, 3903, 1661, 426, 8230, 970, 288, 2 ]
/* SPDX-License-Identifier: MIT */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { console } from "@nomiclabs/buidler/console.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol"; //https://github.com/smartcontractkit/chainlink/issues/3153#issuecomment-655241638 import "@chainlink/contracts/src/v0.6/vendor/SafeMath.sol"; /// @title CommitPool single-player mode contract /// @notice Enables staking and validating performance. No social/pool functionality. contract SinglePlayerCommit is ChainlinkClient, Ownable { using SafeMath for uint256; /****************** GLOBAL CONSTANTS ******************/ IERC20 public token; uint256 BIGGEST_NUMBER = uint256(-1); uint256 constant private ORACLE_PAYMENT = 0.01 * 10 ** 18; //0.01 LINK /*************** DATA TYPES ***************/ /// @notice Activity as part of commitment with oracle address. E.g. "cycling" with ChainLink Strava node struct Activity { string name; address oracle; bool allowed; bool exists; } struct Commitment { address committer; // user bytes32 activityKey; uint256 goalValue; uint256 startTime; uint256 endTime; uint256 stake; // amount of token staked, scaled by token decimals uint256 reportedValue; // as reported by oracle uint256 lastActivityUpdate; // when updated by oracle bool met; // whether the commitment has been met string userId; bool exists; // flag to help check if commitment exists } /*************** EVENTS ***************/ event NewCommitment( address committer, string activityName, uint256 goalValue, uint256 startTime, uint256 endTime, uint256 stake ); event CommitmentEnded(address committer, bool met, uint256 amountPenalized); event Deposit(address committer, uint256 amount); event Withdrawal(address committer, uint256 amount); event RequestActivityDistanceFulfilled( bytes32 indexed requestId, uint256 indexed distance, address indexed committer ); event ActivityUpdated( string name, bytes32 activityKey, address oracle, bool allowed, bool exists); /****************** INTERNAL ACCOUNTING ******************/ mapping(bytes32 => Activity) public activities; // get Activity object based on activity key bytes32[] public activityKeyList; // List of activityKeys, used for indexing allowed activities mapping(address => Commitment) public commitments; // active commitments // address[] public userCommitments; // addresses with active commitments mapping(address => uint256) public committerBalances; // current token balances per user uint256 public totalCommitterBalance; // sum of current token balances uint256 public slashedBalance; //sum of all slashed balances mapping(bytes32 => address) public jobAddresses; // holds the address that ran the job /******** FUNCTIONS ********/ /// @notice Contract constructor used during deployment /// @param _activityList String list of activities reported by oracle /// @param _oracleAddress Address of oracle for activity data /// @param _daiToken Address of <dai token> contract /// @param _linkToken Address of <link token> contract /// @dev Configure token address, add activities to activities mapping by calling _addActivities method constructor( string[] memory _activityList, address _oracleAddress, address _daiToken, address _linkToken ) public { console.log("Constructor called for SinglePlayerCommit contract"); require(_activityList.length >= 1, "SPC::constructor - activityList empty"); token = IERC20(_daiToken); setChainlinkToken(_linkToken); _addActivities(_activityList, _oracleAddress); } // view functions /// @notice Get name string of activity based on key /// @param _activityKey Keccak256 hashed, encoded name of activity /// @dev Lookup in mapping and get name field function getActivityName(bytes32 _activityKey) public view returns (string memory activityName) { return activities[_activityKey].name; } // other public functions /// @notice Deposit amount of <token> into contract /// @param amount Size of deposit /// @dev Transfer amount to <token> contract, update balance, emit event function deposit(uint256 amount) public returns (bool success) { console.log("Received call for depositing amount %s from sender %s", amount, msg.sender); require( token.transferFrom(msg.sender, address(this), amount), "SPC::deposit - token transfer failed" ); _changeCommitterBalance(msg.sender, amount, true); emit Deposit(msg.sender, amount); return true; } /// @notice Public function to withdraw unstaked balance of user /// @param amount Amount of <token> to withdraw /// @dev Check balances and active stake, withdraw from balances, emit event function withdraw(uint256 amount) public returns (bool success) { console.log("Received call for withdrawing amount %s from sender %s", amount, msg.sender); uint256 available = committerBalances[msg.sender]; Commitment storage commitment = commitments[msg.sender]; if(commitment.exists == true){ available = available.sub(commitment.stake); } require(amount <= available, "SPC::withdraw - not enough (unstaked) balance available"); _changeCommitterBalance(msg.sender, amount, false); require(token.transfer(msg.sender, amount), "SPC::withdraw - token transfer failed"); emit Withdrawal(msg.sender, amount); return true; } /// @notice Create commitment, store on-chain and emit event /// @param _activityKey Keccak256 hashed, encoded name of activity /// @param _goalValue Distance of activity as goal /// @param _startTime Unix timestamp in seconds to set commitment starting time /// @param _endTime Unix timestamp in seconds to set commitment deadline /// @param _stake Amount of <token> to stake againt achieving goal /// @param _userId ??? /// @dev Check parameters, create commitment, store on-chain and emit event function makeCommitment( bytes32 _activityKey, uint256 _goalValue, uint256 _startTime, uint256 _endTime, uint256 _stake, string memory _userId ) public returns (bool success) { console.log("makeCommitment called by %s", msg.sender); require(!commitments[msg.sender].exists, "SPC::makeCommitment - msg.sender already has a commitment"); require(activities[_activityKey].allowed, "SPC::makeCommitment - activity doesn't exist or isn't allowed"); require(_endTime > _startTime, "SPC::makeCommitment - endTime before startTime"); require(_goalValue > 1, "SPC::makeCommitment - goal is too low"); require(committerBalances[msg.sender] >= _stake, "SPC::makeCommitment - insufficient token balance"); Commitment memory commitment = Commitment({ committer: msg.sender, activityKey: _activityKey, goalValue: _goalValue, startTime: _startTime, endTime: _endTime, stake: _stake, reportedValue: 0, lastActivityUpdate: 0, met: false, userId: _userId, exists: true }); commitments[msg.sender] = commitment; emit NewCommitment(msg.sender, activities[_activityKey].name, _goalValue, _startTime, _endTime, _stake); return true; } /// @notice Wrapper function to deposit <token> and create commitment in one call /// @param _activityKey Keccak256 hashed, encoded name of activity /// @param _goalValue Distance of activity as goal /// @param _startTime Unix timestamp in seconds to set commitment starting time /// @param _endTime Unix timestamp in seconds to set commitment deadline /// @param _stake Amount of <token> to stake againt achieving goale /// @param _depositAmount Size of deposit /// @param _userId ??? /// @dev Call deposit and makeCommitment method function depositAndCommit( bytes32 _activityKey, uint256 _goalValue, uint256 _startTime, uint256 _endTime, uint256 _stake, uint256 _depositAmount, string memory _userId ) public returns (bool success) { require(deposit(_depositAmount), "SPC::depositAndCommit - deposit failed"); require( makeCommitment(_activityKey, _goalValue, _startTime, _endTime, _stake, _userId), "SPC::depositAndCommit - commitment creation failed" ); return true; } // /// @notice Enables processing of open commitments after endDate that have not been processed by creator // /// @param committer address of the creator of the committer to process // /// @dev Process commitment by lookup based on address, checking metrics, state and updating balances // function processCommitment(address committer) public { // console.log("Processing commitment"); // require(commitments[committer].exists, "SPC::processCommitment - commitment does not exist"); // Commitment storage commitment = commitments[committer]; // require(commitment.endTime < block.timestamp, "SPC::processCommitment - commitment is still active"); // require(commitment.endTime < commitment.lastActivityUpdate, "SPC::processCommitment - update activity"); // require(_settleCommitment(commitment), "SPC::processCommitmentUser - settlement failed"); // emit CommitmentEnded(committer, commitment.met, commitment.stake); // } /// @notice Enables control of processing own commitment. For instance when completed. /// @dev Process commitment by lookup msg.sender, checking metrics, state and updating balances function processCommitmentUser() public { console.log("Processing commitment"); require(commitments[msg.sender].exists, "SPC::processCommitmentUser - commitment does not exist"); Commitment storage commitment = commitments[msg.sender]; require(_settleCommitment(commitment), "SPC::processCommitmentUser - settlement failed"); emit CommitmentEnded(msg.sender, commitment.met, commitment.stake); } /// @notice Internal function for evaluating commitment and slashing funds if needed /// @dev Receive call with commitment object from storage function _settleCommitment(Commitment storage commitment) internal returns (bool success) { console.log("Settling commitment"); commitment.met = commitment.reportedValue >= commitment.goalValue; commitment.exists = false; commitment.met ? withdraw(commitment.stake) : _slashFunds(commitment.stake, msg.sender); return true; } /// @notice Contract owner can withdraw funds not owned by committers. E.g. slashed from failed commitments /// @param amount Amount of <token> to withdraw /// @dev Check amount against slashedBalance, transfer amount and update slashedBalance function ownerWithdraw(uint256 amount) public onlyOwner returns (bool success) { console.log("Received call for owner withdrawal for amount %s", amount); require(amount <= slashedBalance, "SPC::ownerWithdraw - not enough available balance"); slashedBalance = slashedBalance.sub(amount); require(token.transfer(msg.sender, amount), "SPC::ownerWithdraw - token transfer failed"); return true; } /// @notice Internal function to update balance of caller and total balance /// @param amount Amount of <token> to deposit/withdraw /// @param add Boolean toggle to deposit or withdraw /// @dev Based on add param add or substract amount from msg.sender balance and total committerBalance function _changeCommitterBalance(address committer, uint256 amount, bool add) internal returns (bool success) { console.log("Changing committer balance"); if (add) { committerBalances[committer] = committerBalances[committer].add(amount); totalCommitterBalance = totalCommitterBalance.add(amount); } else { committerBalances[committer] = committerBalances[committer].sub(amount); totalCommitterBalance = totalCommitterBalance.sub(amount); } return true; } /// @notice Internal function to slash funds from user /// @param amount Amount of <token> to slash /// @param committer Address of committer /// @dev Substract amount from committer balance and add to slashedBalance function _slashFunds(uint256 amount, address committer) internal returns (bool success) { console.log("Slashing funds commitment"); require(committerBalances[committer] >= amount, "SPC::_slashFunds - funds not available"); _changeCommitterBalance(committer, amount, false); slashedBalance = slashedBalance.add(amount); return true; } // internal functions /// @notice Adds list of activities with oracle (i.e. datasource) to contract /// @param _activityList String list of activities reported by oracle /// @param oracleAddress Address of oracle for activity data /// @dev Basically just loops over _addActivity for list function _addActivities(string[] memory _activityList, address oracleAddress) internal { require(_activityList.length > 0, "SPC::_addActivities - list appears to be empty"); for (uint256 i = 0; i < _activityList.length; i++) { _addActivity(_activityList[i], oracleAddress); } console.log("All provided activities added"); } /// @notice Add activity to contract's activityKeyList /// @param _activityName String name of activity /// @param _oracleAddress Contract address of oracle /// @dev Create key from name, create activity, push to activityKeyList, return key function _addActivity(string memory _activityName, address _oracleAddress) internal returns (bytes32 activityKey) { bytes memory activityNameBytes = bytes(_activityName); require(activityNameBytes.length > 0, "SPC::_addActivity - _activityName empty"); bytes32 _activityKey = keccak256(abi.encode(_activityName)); Activity memory activity = Activity({ name: _activityName, oracle: _oracleAddress, allowed: true, exists: true }); console.log( "Registered activity %s", _activityName ); activities[_activityKey] = activity; activityKeyList.push(_activityKey); emit ActivityUpdated( activity.name, _activityKey, activity.oracle, activity.allowed, activity.exists); return _activityKey; } /// @notice Function to update oracle address of existing activity /// @param _activityKey Keccak256 hashed, encoded name of activity /// @param _oracleAddress Address of oracle for activity data /// @dev Check activity exists, update state, emit event function updateActivityOracle(bytes32 _activityKey, address _oracleAddress) public onlyOwner returns (bool success) { require(activities[_activityKey].exists, "SPC::_updateActivityOracle - activity does not exist"); Activity storage activity = activities[_activityKey]; activity.oracle = _oracleAddress; emit ActivityUpdated( activity.name, _activityKey, activity.oracle, activity.allowed, activity.exists ); return true; } /// @notice Function to update availability of activity of existing activity /// @param _activityKey Keccak256 hashed, encoded name of activity /// @param _allowed Toggle for allowing new commitments with activity /// @dev Check activity exists, update state, emit event function updateActivityAllowed(bytes32 _activityKey, bool _allowed) public onlyOwner returns (bool success) { require(activities[_activityKey].exists, "SPC::_updateActivityOracle - activity does not exist"); Activity storage activity = activities[_activityKey]; activity.allowed = _allowed; emit ActivityUpdated( activity.name, _activityKey, activity.oracle, activity.allowed, activity.exists ); return true; } /// @notice Function to 'delete' an existing activity. One way function, cannot be reversed. /// @param _activityKey Keccak256 hashed, encoded name of activity /// @dev Check activity exists, update state, emit event function disableActivity(bytes32 _activityKey) public onlyOwner returns (bool success) { require(activities[_activityKey].exists, "SPC::_updateActivityOracle - activity does not exist"); Activity storage activity = activities[_activityKey]; activity.exists = false; emit ActivityUpdated( activity.name, _activityKey, activity.oracle, activity.allowed, activity.exists ); return true; } //Chainlink functions /// @notice Call ChainLink node to report distance measured based on Strava data /// @param _committer Address of creator of commitment /// @param _oracle ChainLink oracle address /// @param _jobId ??? /// @dev Async function sending request to ChainLink node function requestActivityDistance(address _committer, address _oracle, string memory _jobId) public { Commitment memory commitment = commitments[_committer]; Chainlink.Request memory req = buildChainlinkRequest( stringToBytes32(_jobId), address(this), this.fulfillActivityDistance.selector ); req.add("type", activities[commitment.activityKey].name); req.add("startTime", uint2str(commitment.startTime)); req.add("endTime", uint2str(commitment.endTime)); req.add("userId", commitment.userId); bytes32 requestId = sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT); jobAddresses[requestId] = _committer; } /// @notice Register distance reported by ChainLink node /// @param _requestId ID or request triggering the method call /// @param _distance Distance to register /// @dev Follow-up function to requestActivityDistance function fulfillActivityDistance(bytes32 _requestId, uint256 _distance) public recordChainlinkFulfillment(_requestId) { address userAddress = jobAddresses[_requestId]; emit RequestActivityDistanceFulfilled(_requestId, _distance, userAddress); commitments[userAddress].reportedValue = _distance; commitments[userAddress].lastActivityUpdate = block.timestamp; } /// @notice Get address for ChainLink token contract /// @dev ChainLink contract method function getChainlinkToken() public view returns (address tokenAddress) { return chainlinkTokenAddress(); } /// @notice Withdraw ChainLink token from contract to contract owner function withdrawLink() public onlyOwner { LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer"); } function cancelRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunctionId, uint256 _expiration ) public onlyOwner { cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration); } function stringToBytes32(string memory source) private pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { // solhint-disable-line no-inline-assembly result := mload(add(source, 32)) } } function uint2str(uint i) internal pure returns (string memory str){ if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function addDays(uint256 amountOfDays, uint256 startDate) internal pure returns (uint256 updatedDate) { return (startDate + amountOfDays * 1 days); } }
@notice Function to update availability of activity of existing activity @param _activityKey Keccak256 hashed, encoded name of activity @param _allowed Toggle for allowing new commitments with activity @dev Check activity exists, update state, emit event
function updateActivityAllowed(bytes32 _activityKey, bool _allowed) public onlyOwner returns (bool success) { require(activities[_activityKey].exists, "SPC::_updateActivityOracle - activity does not exist"); Activity storage activity = activities[_activityKey]; activity.allowed = _allowed; emit ActivityUpdated( activity.name, _activityKey, activity.oracle, activity.allowed, activity.exists ); return true; }
1,060,825
[ 1, 2083, 358, 1089, 13395, 434, 5728, 434, 2062, 5728, 225, 389, 9653, 653, 1475, 24410, 581, 5034, 14242, 16, 3749, 508, 434, 5728, 225, 389, 8151, 399, 9891, 364, 15632, 394, 3294, 1346, 598, 5728, 225, 2073, 5728, 1704, 16, 1089, 919, 16, 3626, 871, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1089, 6193, 5042, 12, 3890, 1578, 389, 9653, 653, 16, 1426, 389, 8151, 13, 7010, 3639, 1071, 203, 3639, 1338, 5541, 7010, 3639, 1135, 261, 6430, 2216, 13, 203, 565, 288, 203, 3639, 2583, 12, 24745, 63, 67, 9653, 653, 8009, 1808, 16, 315, 3118, 39, 2866, 67, 2725, 6193, 23601, 300, 5728, 1552, 486, 1005, 8863, 203, 3639, 9621, 2502, 5728, 273, 17259, 63, 67, 9653, 653, 15533, 203, 3639, 5728, 18, 8151, 273, 389, 8151, 31, 203, 3639, 3626, 9621, 7381, 12, 203, 7734, 5728, 18, 529, 16, 7010, 7734, 389, 9653, 653, 16, 7010, 7734, 5728, 18, 280, 16066, 16, 7010, 7734, 5728, 18, 8151, 16, 7010, 7734, 5728, 18, 1808, 203, 5411, 11272, 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 ]
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
@dev Reads the int128 at `cdPtr` in calldata.
function readInt128( CalldataPointer cdPtr ) internal pure returns (int128 value) { assembly { value := calldataload(cdPtr) } }
3,218,348
[ 1, 7483, 326, 509, 10392, 622, 1375, 4315, 5263, 68, 316, 745, 892, 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, 225, 445, 13731, 10392, 12, 203, 565, 3049, 892, 4926, 7976, 5263, 203, 225, 262, 2713, 16618, 1135, 261, 474, 10392, 460, 13, 288, 203, 565, 19931, 288, 203, 1377, 460, 519, 745, 72, 3145, 6189, 12, 4315, 5263, 13, 203, 565, 289, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /// @title The main contract of Loketh Event Ticketing System. /// @author Roni Yusuf (https://rymanalu.github.io/) contract Loketh is Context, Ownable { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using SafeMath for uint; /// @dev The main Event struct. Every event in Loketh is /// represented by a copy of this structure. struct Event { // Event name. string name; // Address of event owner. address organizer; // Timestamp as seconds since unix epoch. uint startTime; // Timestamp as seconds since unix epoch. // Should be bigger than `startTime`. uint endTime; // Event price in wei. uint price; // Number of maximum participants. uint quota; // Type of currency for payment. string currency; } /// @dev An array containing all events in Loketh. /// The ID of each event is actually the index of the event in this array. /// ID 0 (zero) is reserved for Genesis event, and should not be /// accessible to end-user. Event[] private _events; /// @dev A mapping of organizer to a set of event IDs that they owned. mapping(address => EnumerableSet.UintSet) private _organizerToEventIdsOwned; /// @dev A mapping of event ID to its participants. mapping(uint => EnumerableSet.AddressSet) private _eventParticipants; /// @dev A mapping of event ticket holders to a set of event IDs /// that they owned the ticket. mapping(address => EnumerableSet.UintSet) private _participantToEventIdsOwned; /// @dev The name of native currency in Loketh: Ether. string constant public nativeCurrency = "ETH"; /// @dev An array of supported token names. /// This is related with `supportedTokens`. string[] public supportedTokenNames; /// @dev A mapping of token name and the address, /// that supported for payment. mapping(string => address) public supportedTokens; /// @dev A mapping of event ID to total money collected from buyer. /// Loketh changes the event balance when someone buy a ticket or /// organizer withdraws the money. mapping(uint => uint) private _moneyJar; /// @dev Validate given event ID. Used when getting an event. /// @param _eventId The event id. modifier validEventId(uint _eventId) { require(_eventId > 0, "Loketh: event ID must be at least one."); require( _eventId < _events.length, "Loketh: event ID must be lower than `_events` length." ); _; } /// @dev Emitted when new event created. event EventCreated(uint indexed newEventId, address indexed organizer); /// @dev Emitted when someone buy a ticket. event TicketIssued(uint indexed eventId, address indexed participant); /// @dev Emitted when organizer withdrawn money from the money jar. event MoneyWithdrawn( uint indexed eventId, address indexed recipient, uint amount ); /// @dev Emitted when new token added. event TokenAdded( string indexed tokenName, address indexed tokenAddress, address indexed addedBy ); /// @dev Initializes contract and create the event zero to its address. constructor() { _createEvent( "Genesis", address(this), block.timestamp, block.timestamp, 1 wei, 0, nativeCurrency ); } /// @notice Add a new supported token for payment. /// @param _tokenName The token name. /// @param _tokenAddress The token address where it is deployed. function addNewToken(string memory _tokenName, address _tokenAddress) external onlyOwner { require( _usingToken(_tokenName), "Loketh: Can not register native currency name." ); require( _tokenAddress != address(0), "Loketh: Given address is not a valid address." ); require( supportedTokens[_tokenName] == address(0), "Loketh: Token is already registered." ); supportedTokens[_tokenName] = _tokenAddress; supportedTokenNames.push(_tokenName); emit TokenAdded(_tokenName, _tokenAddress, _msgSender()); } /// @notice Let's buy a ticket! /// @param _eventId The event ID. function buyTicket(uint _eventId) external payable validEventId(_eventId) { Event memory e = _events[_eventId]; address participant = _msgSender(); bool payWithToken = _usingToken(e.currency); IERC20 token; if (payWithToken) { token = IERC20(supportedTokens[e.currency]); } require( participant != e.organizer, "Loketh: Organizer can not buy their own event." ); require( block.timestamp < e.endTime, "Loketh: Can not buy ticket from an event that already ended." ); if (payWithToken) { uint allowance = token.allowance(participant, address(this)); require( allowance >= e.price, "Loketh: Allowance is insufficient." ); uint balance = token.balanceOf(participant); require( balance >= e.price, "Loketh: Balance is insufficient." ); } else { require( msg.value == e.price, "Loketh: Must pay exactly same with the price." ); } require( _eventParticipants[_eventId].length() < e.quota, "Loketh: No quota left." ); require( _eventParticipants[_eventId].contains(participant) == false, "Loketh: Participant already bought the ticket." ); if (payWithToken) { bool transferSucceed = token.transferFrom( participant, address(this), e.price ); require(transferSucceed, "Loketh: Transfer token failed."); } _moneyJar[_eventId] = _moneyJar[_eventId].add(e.price); _buyTicket(_eventId, participant); } /// @notice Let's create a new event! /// @param _name The event name. /// @param _startTime The time when the event started. /// @param _endTime The time when the event ended. /// @param _price The ticket price in wei. /// @param _quota The maximum number of event participants. /// @return The new event ID. function createEvent( string calldata _name, uint _startTime, uint _endTime, uint _price, uint _quota, string calldata _currency ) external returns (uint) { require(_quota > 0, "Loketh: `_quota` must be at least one."); require( _startTime > block.timestamp, "Loketh: `_startTime` must be greater than `block.timestamp`." ); require( _endTime > _startTime, "Loketh: `_endTime` must be greater than `_startTime`." ); require( ( _usingEther(_currency) || supportedTokens[_currency] != address(0) ), "Loketh: `_currency` is invalid." ); uint newEventId = _createEvent( _name, _msgSender(), _startTime, _endTime, _price, _quota, _currency ); return newEventId; } /// @notice Returns a list of all event IDs assigned to an address. /// @param _address The event owner address. /// @return The event IDs. function eventsOfOwner(address _address) external view returns (uint[] memory) { uint eventsCount = eventsOf(_address); uint[] memory eventIds = new uint[](eventsCount); for (uint i = 0; i < eventsCount; i++) { eventIds[i] = _organizerToEventIdsOwned[_address].at(i); } return eventIds; } /// @notice Returns all relevant information about a spesific event. /// @dev Prevent users to access event ID 0 (zero). /// @param _id The event ID we are interested in. /// @return Members of `Event` struct. function getEvent(uint _id) external view validEventId(_id) returns ( string memory, address, uint, uint, uint, uint, uint, uint, string memory ) { Event memory e = _events[_id]; uint soldCounter = _eventParticipants[_id].length(); uint moneyCollected = _moneyJar[_id]; return ( e.name, e.organizer, e.startTime, e.endTime, e.price, e.quota, soldCounter, moneyCollected, e.currency ); } /// @dev Checking if given organizer owns the given ticket. /// @param _organizer The address to check. /// @param _eventId The event ID to check. function organizerOwnsEvent(address _organizer, uint _eventId) external view validEventId(_eventId) returns (bool) { return _organizerToEventIdsOwned[_organizer].contains(_eventId); } /// @dev Checking if given participant is already has given ticket. /// @param _participant The address to check. /// @param _eventId The ticket ID to check. function participantHasTicket(address _participant, uint _eventId) external view validEventId(_eventId) returns (bool) { return _participantToEventIdsOwned[_participant].contains(_eventId); } /// @notice Returns a list of all ticket (event) IDs assigned to an address. /// @param _address The ticket owner address. /// @return The ticket (event) IDs. function ticketsOfOwner(address _address) external view returns (uint[] memory) { uint ticketsCount = ticketsOf(_address); uint[] memory eventIds = new uint[](ticketsCount); for (uint i = 0; i < ticketsCount; i++) { eventIds[i] = _participantToEventIdsOwned[_address].at(i); } return eventIds; } /// @notice Returns the total number of events. /// @return Returns the total number of events, without the Genesis. function totalEvents() external view returns (uint) { return _events.length - 1; } /// @notice Let's withdraw the money from event ticket sale! /// @param _eventId The event ID we are going to withdraw from. function withdrawMoney(uint _eventId) external validEventId(_eventId) { address payable sender = _msgSender(); Event memory e = _events[_eventId]; require( sender == e.organizer, "Loketh: Sender is not the event owner." ); require( block.timestamp > e.endTime, "Loketh: Money only can be withdrawn after the event ends." ); uint amount = _moneyJar[_eventId]; _moneyJar[_eventId] = 0; if (_usingEther(e.currency)) { sender.transfer(amount); } else { IERC20 token = IERC20(supportedTokens[e.currency]); token.transfer(sender, amount); } emit MoneyWithdrawn(_eventId, sender, amount); } /// @notice Returns total number of events owned by given address. /// @param _address The address to check. /// @return The total number of events. function eventsOf(address _address) public view returns (uint) { return _organizerToEventIdsOwned[_address].length(); } /// @notice Returns total number of tickets owned by given address. /// @param _address The address to check. /// @return The total number of tickets. function ticketsOf(address _address) public view returns (uint) { return _participantToEventIdsOwned[_address].length(); } /// @return The total number of supported tokens in Loketh. function totalSupportedTokens() public view returns (uint) { return supportedTokenNames.length; } /// @dev A private method that increments the counter, adds participants, /// add the event ID to the participant, and emit the TicketIssued event. /// This method doesn't do any checking and should only be called /// when the input data is known to be valid. /// @param _eventId The event ID. /// @param _participant The event participant. function _buyTicket(uint _eventId, address _participant) private { _eventParticipants[_eventId].add(_participant); _participantToEventIdsOwned[_participant].add(_eventId); emit TicketIssued(_eventId, _participant); } /// @dev A private method that creates a new event and stores it. /// This method doesn't do any checking and should only be called /// when the input data is known to be valid. /// @param _name The event name. /// @param _organizer The event owner. /// @param _startTime The time when the event started. /// @param _endTime The time when the event ended. /// @param _price The ticket price in wei. /// @param _quota The maximum number of event participants. /// @return The new event ID. function _createEvent( string memory _name, address _organizer, uint _startTime, uint _endTime, uint _price, uint _quota, string memory _currency ) private returns (uint) { Event memory _event = Event({ name: _name, organizer: _organizer, startTime: _startTime, endTime: _endTime, price: _price, quota: _quota, currency: _currency }); _events.push(_event); uint newEventId = _events.length - 1; _organizerToEventIdsOwned[_organizer].add(newEventId); emit EventCreated(newEventId, _organizer); return newEventId; } /// @dev Determine whether given currency is Ether. /// @param _currency The currency name. /// @return Returns if currency is Ether. function _usingEther(string memory _currency) private pure returns (bool) { return ( keccak256(abi.encodePacked((nativeCurrency))) == keccak256(abi.encodePacked((_currency))) ); } /// @dev Determine whether given currency is ERC-20 token. /// @param _currency The currency name. /// @return Returns if currency is an ERC-20 token. function _usingToken(string memory _currency) private pure returns (bool) { return !_usingEther(_currency); } }
@dev A mapping of token name and the address, that supported for payment.
mapping(string => address) public supportedTokens;
5,393,256
[ 1, 37, 2874, 434, 1147, 508, 471, 326, 1758, 16, 225, 716, 3260, 364, 5184, 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 ]
[ 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, 2874, 12, 1080, 516, 1758, 13, 1071, 3260, 5157, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; import "./AcuityItemStoreInterface.sol"; import "./AcuityItemStoreConstants.sol"; import "./AcuityItemStoreRegistry.sol"; /** * @title AcuityItemStoreIpfsSha256 * @author Jonathan Brown <[email protected]> * @dev AcuityItemStoreInterface implementation where each item revision is a SHA256 IPFS hash. */ contract AcuityItemStoreIpfsSha256 is AcuityItemStoreInterface, AcuityItemStoreConstants { /** * @dev Single slot structure of item state. */ struct ItemState { bool inUse; // Has this itemId ever been used. byte flags; // Packed item settings. uint32 revisionCount; // Number of revisions including revision 0. uint32 timestamp; // Timestamp of revision 0. address owner; // Who owns this item. } /** * @dev Mapping of itemId to item state. */ mapping (bytes32 => ItemState) itemState; /** * @dev Mapping of itemId to mapping of packed slots of eight 32-bit timestamps. */ mapping (bytes32 => mapping (uint => bytes32)) itemPackedTimestamps; /** * @dev Mapping of itemId to mapping of revision number to IPFS hash. */ mapping (bytes32 => mapping (uint => bytes32)) itemRevisionIpfsHashes; /** * @dev Mapping of itemId to mapping of transfer recipient addresses to enabled. */ mapping (bytes32 => mapping (address => bool)) itemTransferEnabled; /** * @dev AcuityItemStoreRegistry contract. */ AcuityItemStoreRegistry public itemStoreRegistry; /** * @dev Id of this instance of AcuityItemStoreInterface. Stored as bytes32 instead of bytes8 to reduce gas usage. */ bytes32 contractId; /** * @dev Revert if the itemId is not in use. * @param itemId itemId of the item. */ modifier inUse(bytes32 itemId) { require (itemState[itemId].inUse, "Item not in use."); _; } /** * @dev Revert if the owner of the item is not the message sender. * @param itemId itemId of the item. */ modifier isOwner(bytes32 itemId) { require (itemState[itemId].owner == msg.sender, "Sender is not owner of item."); _; } /** * @dev Revert if the item is not updatable. * @param itemId itemId of the item. */ modifier isUpdatable(bytes32 itemId) { require (itemState[itemId].flags & UPDATABLE != 0, "Item is not updatable."); _; } /** * @dev Revert if the item is not enforcing revisions. * @param itemId itemId of the item. */ modifier isNotEnforceRevisions(bytes32 itemId) { require (itemState[itemId].flags & ENFORCE_REVISIONS == 0, "Item is enforcing revisions."); _; } /** * @dev Revert if the item is not retractable. * @param itemId itemId of the item. */ modifier isRetractable(bytes32 itemId) { require (itemState[itemId].flags & RETRACTABLE != 0, "Item is not retractable."); _; } /** * @dev Revert if the item is not transferable. * @param itemId itemId of the item. */ modifier isTransferable(bytes32 itemId) { require (itemState[itemId].flags & TRANSFERABLE != 0, "Item is not transferable."); _; } /** * @dev Revert if the item is not transferable to a specific user. * @param itemId itemId of the item. * @param recipient Address of the user. */ modifier isTransferEnabled(bytes32 itemId, address recipient) { require (itemTransferEnabled[itemId][recipient], "Item transfer to recipient not enabled."); _; } /** * @dev Revert if the item only has one revision. * @param itemId itemId of the item. */ modifier hasAdditionalRevisions(bytes32 itemId) { require (itemState[itemId].revisionCount > 1, "Item only has 1 revision."); _; } /** * @dev Revert if a specific item revision does not exist. * @param itemId itemId of the item. * @param revisionId Id of the revision. */ modifier revisionExists(bytes32 itemId, uint revisionId) { require (revisionId < itemState[itemId].revisionCount, "Revision does not exist."); _; } /** * @param _itemStoreRegistry Address of the AcuityItemStoreRegistry contract. */ constructor(AcuityItemStoreRegistry _itemStoreRegistry) { // Store the address of the AcuityItemStoreRegistry contract. itemStoreRegistry = _itemStoreRegistry; // Register this contract. contractId = itemStoreRegistry.register(); } /** * @dev Generates an itemId from owner and nonce and checks that it is unused. * @param owner Address that will own the item. * @param nonce Nonce that this owner has never used before. * @return itemId itemId of the item with this owner and nonce. */ function getNewItemId(address owner, bytes32 nonce) override public view returns (bytes32 itemId) { // Combine contractId with hash of sender and nonce. itemId = (keccak256(abi.encodePacked(address(this), owner, nonce)) & ITEM_ID_MASK) | contractId; // Make sure this itemId has not been used before. require (!itemState[itemId].inUse, "itemId already in use."); } /** * @dev Creates an item with no parents. It is guaranteed that different users will never receive the same itemId, even before consensus has been reached. This prevents itemId sniping. * @param flagsNonce Nonce that this address has never passed before; first byte is creation flags. * @param ipfsHash Hash of the IPFS object where revision 0 is stored. * @return itemId itemId of the new item. */ function create(bytes32 flagsNonce, bytes32 ipfsHash) external returns (bytes32 itemId) { // Determine the itemId. itemId = getNewItemId(msg.sender, flagsNonce); // Extract the flags. byte flags = byte(flagsNonce); // Determine the owner. address owner = (flags & DISOWN == 0) ? msg.sender : address(0); // Store item state. ItemState storage state = itemState[itemId]; state.inUse = true; state.flags = flags; state.revisionCount = 1; state.timestamp = uint32(block.timestamp); state.owner = owner; // Store the IPFS hash. itemRevisionIpfsHashes[itemId][0] = ipfsHash; // Log item creation. emit Create(itemId, owner, flags); // Log the first revision. emit PublishRevision(itemId, owner, 0); } /** * @dev Store an item revision timestamp in a packed slot. * @param itemId itemId of the item. * @param offset The offset of the timestamp that should be stored. */ function _setPackedTimestamp(bytes32 itemId, uint offset) internal { // Get the slot. bytes32 slot = itemPackedTimestamps[itemId][offset / 8]; // Calculate the shift. uint shift = (offset % 8) * 32; // Wipe the previous timestamp. slot &= ~(bytes32(uint256(uint32(-1))) << shift); // Insert the current timestamp. slot |= bytes32(uint256(uint32(block.timestamp))) << shift; // Store the slot. itemPackedTimestamps[itemId][offset / 8] = slot; } /** * @dev Create a new item revision. * @param itemId itemId of the item. * @param ipfsHash Hash of the IPFS object where the item revision is stored. * @return revisionId The revisionId of the new revision. */ function createNewRevision(bytes32 itemId, bytes32 ipfsHash) external isOwner(itemId) isUpdatable(itemId) returns (uint revisionId) { // Get item state. ItemState storage state = itemState[itemId]; // Increment the number of revisions. revisionId = state.revisionCount++; // Store the IPFS hash. itemRevisionIpfsHashes[itemId][revisionId] = ipfsHash; // Store the timestamp. _setPackedTimestamp(itemId, revisionId - 1); // Log the revision. emit PublishRevision(itemId, state.owner, revisionId); } /** * @dev Update an item's latest revision. * @param itemId itemId of the item. * @param ipfsHash Hash of the IPFS object where the item revision is stored. */ function updateLatestRevision(bytes32 itemId, bytes32 ipfsHash) external isOwner(itemId) isUpdatable(itemId) isNotEnforceRevisions(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Determine the revisionId. uint revisionId = state.revisionCount - 1; // Update the IPFS hash. itemRevisionIpfsHashes[itemId][revisionId] = ipfsHash; // Update the timestamp. if (revisionId == 0) { state.timestamp = uint32(block.timestamp); } else { _setPackedTimestamp(itemId, revisionId - 1); } // Log the revision. emit PublishRevision(itemId, state.owner, revisionId); } /** * @dev Retract an item's latest revision. Revision 0 cannot be retracted. * @param itemId itemId of the item. */ function retractLatestRevision(bytes32 itemId) override external isOwner(itemId) isUpdatable(itemId) isNotEnforceRevisions(itemId) hasAdditionalRevisions(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Decrement the number of revisions. uint revisionId = --state.revisionCount; // Delete the IPFS hash. delete itemRevisionIpfsHashes[itemId][revisionId]; // Delete the packed timestamp slot if it is no longer required. if (revisionId % 8 == 1) { delete itemPackedTimestamps[itemId][revisionId / 8]; } // Log the revision retraction. emit RetractRevision(itemId, state.owner, revisionId); } /** * @dev Delete all of an item's packed revision timestamps. * @param itemId itemId of the item. */ function _deleteAllPackedRevisionTimestamps(bytes32 itemId) internal { // Determine how many slots should be deleted. // Timestamp of the first revision is stored in the item state, so the first slot only needs to be deleted if there are at least 2 revisions. uint slotCount = (itemState[itemId].revisionCount + 6) / 8; // Delete the slots. for (uint i = 0; i < slotCount; i++) { delete itemPackedTimestamps[itemId][i]; } } /** * @dev Delete all an item's revisions and replace it with a new item. * @param itemId itemId of the item. * @param ipfsHash Hash of the IPFS object where the item revision is stored. */ function restart(bytes32 itemId, bytes32 ipfsHash) external isOwner(itemId) isUpdatable(itemId) isNotEnforceRevisions(itemId) { // Get item state and IPFS hashes. ItemState storage state = itemState[itemId]; mapping (uint => bytes32) storage ipfsHashes = itemRevisionIpfsHashes[itemId]; // Log and delete all the IPFS hashes except the first one. for (uint revisionId = state.revisionCount - 1; revisionId > 0; revisionId--) { delete ipfsHashes[revisionId]; emit RetractRevision(itemId, state.owner, revisionId); } // Delete all the packed revision timestamps. _deleteAllPackedRevisionTimestamps(itemId); // Update the item state. state.revisionCount = 1; state.timestamp = uint32(block.timestamp); // Update the first IPFS hash. ipfsHashes[0] = ipfsHash; // Log the revision. emit PublishRevision(itemId, state.owner, 0); } /** * @dev Retract an item. * @param itemId itemId of the item. This itemId can never be used again. */ function retract(bytes32 itemId) override external isOwner(itemId) isRetractable(itemId) { // Get item state and IPFS hashes. ItemState storage state = itemState[itemId]; mapping (uint => bytes32) storage ipfsHashes = itemRevisionIpfsHashes[itemId]; // Log and delete all the IPFS hashes. for (uint revisionId = state.revisionCount - 1; revisionId < state.revisionCount; revisionId--) { delete ipfsHashes[revisionId]; emit RetractRevision(itemId, state.owner, revisionId); } // Delete all the packed revision timestamps. _deleteAllPackedRevisionTimestamps(itemId); // Mark this item as retracted. state.inUse = true; state.flags = 0; state.revisionCount = 0; state.timestamp = 0; state.owner = address(0); // Log the item retraction. emit Retract(itemId, state.owner); } /** * @dev Enable transfer of an item to the current user. * @param itemId itemId of the item. */ function transferEnable(bytes32 itemId) override external isTransferable(itemId) { // Record in state that the current user will accept this item. itemTransferEnabled[itemId][msg.sender] = true; // Log that transfer to this user is enabled. emit EnableTransfer(itemId, itemState[itemId].owner, msg.sender); } /** * @dev Disable transfer of an item to the current user. * @param itemId itemId of the item. */ function transferDisable(bytes32 itemId) override external isTransferEnabled(itemId, msg.sender) { // Record in state that the current user will not accept this item. itemTransferEnabled[itemId][msg.sender] = false; // Log that transfer to this user is disabled. emit DisableTransfer(itemId, itemState[itemId].owner, msg.sender); } /** * @dev Transfer an item to a new user. * @param itemId itemId of the item. * @param recipient Address of the user to transfer to item to. */ function transfer(bytes32 itemId, address recipient) override external isOwner(itemId) isTransferable(itemId) isTransferEnabled(itemId, recipient) { // Get item state. ItemState storage state = itemState[itemId]; // Log the transfer. emit Transfer(itemId, state.owner, recipient); // Update ownership of the item. state.owner = recipient; // Disable this transfer in future and free up the slot. itemTransferEnabled[itemId][recipient] = false; } /** * @dev Disown an item. * @param itemId itemId of the item. */ function disown(bytes32 itemId) override external isOwner(itemId) isTransferable(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Log that the item has been disowned. emit Disown(itemId, state.owner); // Remove the owner from the item's state. delete state.owner; } /** * @dev Set an item as not updatable. * @param itemId itemId of the item. */ function setNotUpdatable(bytes32 itemId) override external isOwner(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Record in state that the item is not updatable. state.flags &= ~UPDATABLE; // Log that the item is not updatable. emit SetNotUpdatable(itemId, state.owner); } /** * @dev Set an item to enforce revisions. * @param itemId itemId of the item. */ function setEnforceRevisions(bytes32 itemId) override external isOwner(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Record in state that all changes to this item must be new revisions. state.flags |= ENFORCE_REVISIONS; // Log that the item now enforces new revisions. emit SetEnforceRevisions(itemId, state.owner); } /** * @dev Set an item to not be retractable. * @param itemId itemId of the item. */ function setNotRetractable(bytes32 itemId) override external isOwner(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Record in state that the item is not retractable. state.flags &= ~RETRACTABLE; // Log that the item is not retractable. emit SetNotRetractable(itemId, state.owner); } /** * @dev Set an item to not be transferable. * @param itemId itemId of the item. */ function setNotTransferable(bytes32 itemId) override external isOwner(itemId) { // Get item state. ItemState storage state = itemState[itemId]; // Record in state that the item is not transferable. state.flags &= ~TRANSFERABLE; // Log that the item is not transferable. emit SetNotTransferable(itemId, state.owner); } /** * @dev Get the ABI version for this contract. * @return ABI version. */ function getAbiVersion() override external pure returns (uint) { return ABI_VERSION; } /** * @dev Get the id for this contract. * @return Id of the contract. */ function getContractId() override external view returns (bytes8) { return bytes8(contractId << 192); } /** * @dev Check if an itemId is in use. * @param itemId itemId of the item. * @return True if the itemId is in use. */ function getInUse(bytes32 itemId) override external view returns (bool) { return itemState[itemId].inUse; } /** * @dev Get the IPFS hashes for all of an item's revisions. * @param itemId itemId of the item. * @return ipfsHashes Revision IPFS hashes. */ function _getAllRevisionIpfsHashes(bytes32 itemId) internal view returns (bytes32[] memory ipfsHashes) { uint revisionCount = itemState[itemId].revisionCount; ipfsHashes = new bytes32[](revisionCount); for (uint revisionId = 0; revisionId < revisionCount; revisionId++) { ipfsHashes[revisionId] = itemRevisionIpfsHashes[itemId][revisionId]; } } /** * @dev Get the timestamp for a specific item revision. * @param itemId itemId of the item. * @param revisionId Id of the revision. * @return timestamp Timestamp of the specified revision or 0 for unconfirmed. */ function _getRevisionTimestamp(bytes32 itemId, uint revisionId) internal view returns (uint timestamp) { if (revisionId == 0) { timestamp = itemState[itemId].timestamp; } else { uint offset = revisionId - 1; timestamp = uint32(uint256(itemPackedTimestamps[itemId][offset / 8] >> ((offset % 8) * 32))); } // Check if the revision has been confirmed yet. if (timestamp == block.timestamp) { timestamp = 0; } } /** * @dev Get the timestamps for all of an item's revisions. * @param itemId itemId of the item. * @return timestamps Revision timestamps. */ function _getAllRevisionTimestamps(bytes32 itemId) internal view returns (uint[] memory timestamps) { uint count = itemState[itemId].revisionCount; timestamps = new uint[](count); for (uint revisionId = 0; revisionId < count; revisionId++) { timestamps[revisionId] = _getRevisionTimestamp(itemId, revisionId); } } /** * @dev Get an item. * @param itemId itemId of the item. * @return flags Packed item settings. * @return owner Owner of the item. * @return timestamps Timestamp of each revision. * @return ipfsHashes IPFS hash of each revision. */ function getItem(bytes32 itemId) external view inUse(itemId) returns (byte flags, address owner, uint[] memory timestamps, bytes32[] memory ipfsHashes) { ItemState storage state = itemState[itemId]; flags = state.flags; owner = state.owner; ipfsHashes = _getAllRevisionIpfsHashes(itemId); timestamps = _getAllRevisionTimestamps(itemId); } /** * @dev Get an item's flags. * @param itemId itemId of the item. * @return Packed item settings. */ function getFlags(bytes32 itemId) override external view inUse(itemId) returns (byte) { return itemState[itemId].flags; } /** * @dev Determine if an item is updatable. * @param itemId itemId of the item. * @return True if the item is updatable. */ function getUpdatable(bytes32 itemId) override external view inUse(itemId) returns (bool) { return itemState[itemId].flags & UPDATABLE != 0; } /** * @dev Determine if an item enforces revisions. * @param itemId itemId of the item. * @return True if the item enforces revisions. */ function getEnforceRevisions(bytes32 itemId) override external view inUse(itemId) returns (bool) { return itemState[itemId].flags & ENFORCE_REVISIONS != 0; } /** * @dev Determine if an item is retractable. * @param itemId itemId of the item. * @return True if the item is item retractable. */ function getRetractable(bytes32 itemId) override external view inUse(itemId) returns (bool) { return itemState[itemId].flags & RETRACTABLE != 0; } /** * @dev Determine if an item is transferable. * @param itemId itemId of the item. * @return True if the item is transferable. */ function getTransferable(bytes32 itemId) override external view inUse(itemId) returns (bool) { return itemState[itemId].flags & TRANSFERABLE != 0; } /** * @dev Get the owner of an item. * @param itemId itemId of the item. * @return Owner of the item. */ function getOwner(bytes32 itemId) override external view inUse(itemId) returns (address) { return itemState[itemId].owner; } /** * @dev Get the number of revisions an item has. * @param itemId itemId of the item. * @return How many revisions the item has. */ function getRevisionCount(bytes32 itemId) override external view inUse(itemId) returns (uint) { return itemState[itemId].revisionCount; } /** * @dev Get the timestamp for a specific item revision. * @param itemId itemId of the item. * @param revisionId Id of the revision. * @return Timestamp of the specified revision. */ function getRevisionTimestamp(bytes32 itemId, uint revisionId) override external view revisionExists(itemId, revisionId) returns (uint) { return _getRevisionTimestamp(itemId, revisionId); } /** * @dev Get the timestamps for all of an item's revisions. * @param itemId itemId of the item. * @return Timestamps of all revisions of the item. */ function getAllRevisionTimestamps(bytes32 itemId) override external view inUse(itemId) returns (uint[] memory) { return _getAllRevisionTimestamps(itemId); } /** * @dev Get the IPFS hash for a specific item revision. * @param itemId itemId of the item. * @param revisionId Id of the revision. * @return IPFS hash of the specified revision. */ function getRevisionIpfsHash(bytes32 itemId, uint revisionId) external view revisionExists(itemId, revisionId) returns (bytes32) { return itemRevisionIpfsHashes[itemId][revisionId]; } /** * @dev Get the IPFS hashes for all of an item's revisions. * @param itemId itemId of the item. * @return IPFS hashes of all revisions of the item. */ function getAllRevisionIpfsHashes(bytes32 itemId) external view inUse(itemId) returns (bytes32[] memory) { return _getAllRevisionIpfsHashes(itemId); } }
* @dev Id of this instance of AcuityItemStoreInterface. Stored as bytes32 instead of bytes8 to reduce gas usage./
bytes32 contractId;
12,839,047
[ 1, 548, 434, 333, 791, 434, 432, 6319, 560, 1180, 2257, 1358, 18, 26548, 487, 1731, 1578, 3560, 434, 1731, 28, 358, 5459, 16189, 4084, 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 ]
[ 1, 1, 1, 1, 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, 1731, 1578, 6835, 548, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-06-18 */ /** *Submitted for verification at FtmScan.com on 2021-05-31 */ /** *Submitted for verification at BscScan.com on 2021-04-15 */ /** *Submitted for verification at BscScan.com on 2021-04-08 */ /** *Submitted for verification at hecoinfo.com on 2021-04-08 */ // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0; interface ISushiswapV2Pair { 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 swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathSushiswap { 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'); } } library SushiswapV2Library { using SafeMathSushiswap 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, 'SushiswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'SushiswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(uint256(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash ))))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = ISushiswapV2Pair(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, 'SushiswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'SushiswapV2Library: 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, 'SushiswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SushiswapV2Library: 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, 'SushiswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SushiswapV2Library: 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, 'SushiswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'SushiswapV2Library: 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); } } } // helper methods for interacting with ERC20 tokens and sending NATIVE 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 safeTransferNative(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: NATIVE_TRANSFER_FAILED'); } } interface IwNATIVE { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } interface AnyswapV1ERC20 { function mint(address to, uint256 amount) external returns (bool); function burn(address from, uint256 amount) external returns (bool); function changeVault(address newVault) external returns (bool); function depositVault(uint amount, address to) external returns (uint); function withdrawVault(address from, uint amount, address to) external returns (uint); function underlying() external view returns (address); } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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 permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract AnyswapV4Router { using SafeMathSushiswap for uint; address public immutable factory; address public immutable wNATIVE; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'AnyswapV3Router: EXPIRED'); _; } constructor(address _factory, address _wNATIVE, address _mpc) { _newMPC = _mpc; _newMPCEffectiveTime = block.timestamp; factory = _factory; wNATIVE = _wNATIVE; } receive() external payable { assert(msg.sender == wNATIVE); // only accept Native via fallback from the wNative contract } address private _oldMPC; address private _newMPC; uint256 private _newMPCEffectiveTime; event LogChangeMPC(address indexed oldMPC, address indexed newMPC, uint indexed effectiveTime, uint chainID); event LogChangeRouter(address indexed oldRouter, address indexed newRouter, uint chainID); event LogAnySwapIn(bytes32 indexed txhash, address indexed token, address indexed to, uint amount, uint fromChainID, uint toChainID); event LogAnySwapOut(address indexed token, address indexed from, address indexed to, uint amount, uint fromChainID, uint toChainID); event LogAnySwapTradeTokensForTokens(address[] path, address indexed from, address indexed to, uint amountIn, uint amountOutMin, uint fromChainID, uint toChainID); event LogAnySwapTradeTokensForNative(address[] path, address indexed from, address indexed to, uint amountIn, uint amountOutMin, uint fromChainID, uint toChainID); modifier onlyMPC() { require(msg.sender == mpc(), "AnyswapV3Router: FORBIDDEN"); _; } function mpc() public view returns (address) { if (block.timestamp >= _newMPCEffectiveTime) { return _newMPC; } return _oldMPC; } function cID() public view returns (uint id) { assembly {id := chainid()} } function changeMPC(address newMPC) public onlyMPC returns (bool) { require(newMPC != address(0), "AnyswapV3Router: address(0x0)"); _oldMPC = mpc(); _newMPC = newMPC; _newMPCEffectiveTime = block.timestamp + 2*24*3600; emit LogChangeMPC(_oldMPC, _newMPC, _newMPCEffectiveTime, cID()); return true; } function changeVault(address token, address newVault) public onlyMPC returns (bool) { require(newVault != address(0), "AnyswapV3Router: address(0x0)"); return AnyswapV1ERC20(token).changeVault(newVault); } function _anySwapOut(address from, address token, address to, uint amount, uint toChainID) internal { AnyswapV1ERC20(token).burn(from, amount); emit LogAnySwapOut(token, from, to, amount, cID(), toChainID); } // Swaps `amount` `token` from this chain to `toChainID` chain with recipient `to` function anySwapOut(address token, address to, uint amount, uint toChainID) external { _anySwapOut(msg.sender, token, to, amount, toChainID); } // Swaps `amount` `token` from this chain to `toChainID` chain with recipient `to` by minting with `underlying` function anySwapOutUnderlying(address token, address to, uint amount, uint toChainID) external { TransferHelper.safeTransferFrom(AnyswapV1ERC20(token).underlying(), msg.sender, token, amount); AnyswapV1ERC20(token).depositVault(amount, msg.sender); _anySwapOut(msg.sender, token, to, amount, toChainID); } function anySwapOutUnderlyingWithPermit( address from, address token, address to, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external { address _underlying = AnyswapV1ERC20(token).underlying(); IERC20(_underlying).permit(from, address(this), amount, deadline, v, r, s); TransferHelper.safeTransferFrom(_underlying, from, token, amount); AnyswapV1ERC20(token).depositVault(amount, from); _anySwapOut(from, token, to, amount, toChainID); } function anySwapOutUnderlyingWithTransferPermit( address from, address token, address to, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external { IERC20(AnyswapV1ERC20(token).underlying()).transferWithPermit(from, token, amount, deadline, v, r, s); AnyswapV1ERC20(token).depositVault(amount, from); _anySwapOut(from, token, to, amount, toChainID); } function anySwapOut(address[] calldata tokens, address[] calldata to, uint[] calldata amounts, uint[] calldata toChainIDs) external { for (uint i = 0; i < tokens.length; i++) { _anySwapOut(msg.sender, tokens[i], to[i], amounts[i], toChainIDs[i]); } } // swaps `amount` `token` in `fromChainID` to `to` on this chainID function _anySwapIn(bytes32 txs, address token, address to, uint amount, uint fromChainID) internal { AnyswapV1ERC20(token).mint(to, amount); emit LogAnySwapIn(txs, token, to, amount, fromChainID, cID()); } // swaps `amount` `token` in `fromChainID` to `to` on this chainID // triggered by `anySwapOut` function anySwapIn(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC { _anySwapIn(txs, token, to, amount, fromChainID); } // swaps `amount` `token` in `fromChainID` to `to` on this chainID with `to` receiving `underlying` function anySwapInUnderlying(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC { _anySwapIn(txs, token, to, amount, fromChainID); AnyswapV1ERC20(token).withdrawVault(to, amount, to); } // swaps `amount` `token` in `fromChainID` to `to` on this chainID with `to` receiving `underlying` if possible function anySwapInAuto(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC { _anySwapIn(txs, token, to, amount, fromChainID); AnyswapV1ERC20 _anyToken = AnyswapV1ERC20(token); address _underlying = _anyToken.underlying(); if (_underlying != address(0) && IERC20(_underlying).balanceOf(token) >= amount) { _anyToken.withdrawVault(to, amount, to); } } // extracts mpc fee from bridge fees function anySwapFeeTo(address token, uint amount) external onlyMPC { address _mpc = mpc(); AnyswapV1ERC20(token).mint(_mpc, amount); AnyswapV1ERC20(token).withdrawVault(_mpc, amount, _mpc); } function anySwapIn(bytes32[] calldata txs, address[] calldata tokens, address[] calldata to, uint256[] calldata amounts, uint[] calldata fromChainIDs) external onlyMPC { for (uint i = 0; i < tokens.length; i++) { _anySwapIn(txs[i], tokens[i], to[i], amounts[i], fromChainIDs[i]); } } // **** 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; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = SushiswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? SushiswapV2Library.pairFor(factory, output, path[i + 2]) : _to; ISushiswapV2Pair(SushiswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint toChainID ) external virtual ensure(deadline) { AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn); emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID); } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForTokensUnderlying( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint toChainID ) external virtual ensure(deadline) { TransferHelper.safeTransferFrom(AnyswapV1ERC20(path[0]).underlying(), msg.sender, path[0], amountIn); AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender); AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn); emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID); } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForTokensUnderlyingWithPermit( address from, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external virtual ensure(deadline) { address _underlying = AnyswapV1ERC20(path[0]).underlying(); IERC20(_underlying).permit(from, address(this), amountIn, deadline, v, r, s); TransferHelper.safeTransferFrom(_underlying, from, path[0], amountIn); AnyswapV1ERC20(path[0]).depositVault(amountIn, from); AnyswapV1ERC20(path[0]).burn(from, amountIn); { address[] memory _path = path; address _from = from; address _to = to; uint _amountIn = amountIn; uint _amountOutMin = amountOutMin; uint _cID = cID(); uint _toChainID = toChainID; emit LogAnySwapTradeTokensForTokens(_path, _from, _to, _amountIn, _amountOutMin, _cID, _toChainID); } } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForTokensUnderlyingWithTransferPermit( address from, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external virtual ensure(deadline) { IERC20(AnyswapV1ERC20(path[0]).underlying()).transferWithPermit(from, path[0], amountIn, deadline, v, r, s); AnyswapV1ERC20(path[0]).depositVault(amountIn, from); AnyswapV1ERC20(path[0]).burn(from, amountIn); emit LogAnySwapTradeTokensForTokens(path, from, to, amountIn, amountOutMin, cID(), toChainID); } // Swaps `amounts[path.length-1]` `path[path.length-1]` to `to` on this chain // Triggered by `anySwapOutExactTokensForTokens` function anySwapInExactTokensForTokens( bytes32 txs, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint fromChainID ) external onlyMPC virtual ensure(deadline) returns (uint[] memory amounts) { amounts = SushiswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'SushiswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); _anySwapIn(txs, path[0], SushiswapV2Library.pairFor(factory, path[0], path[1]), amounts[0], fromChainID); _swap(amounts, path, to); } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForNative( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint toChainID ) external virtual ensure(deadline) { AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn); emit LogAnySwapTradeTokensForNative(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID); } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForNativeUnderlying( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint toChainID ) external virtual ensure(deadline) { TransferHelper.safeTransferFrom(AnyswapV1ERC20(path[0]).underlying(), msg.sender, path[0], amountIn); AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender); AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn); emit LogAnySwapTradeTokensForNative(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID); } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForNativeUnderlyingWithPermit( address from, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external virtual ensure(deadline) { address _underlying = AnyswapV1ERC20(path[0]).underlying(); IERC20(_underlying).permit(from, address(this), amountIn, deadline, v, r, s); TransferHelper.safeTransferFrom(_underlying, from, path[0], amountIn); AnyswapV1ERC20(path[0]).depositVault(amountIn, from); AnyswapV1ERC20(path[0]).burn(from, amountIn); { address[] memory _path = path; address _from = from; address _to = to; uint _amountIn = amountIn; uint _amountOutMin = amountOutMin; uint _cID = cID(); uint _toChainID = toChainID; emit LogAnySwapTradeTokensForNative(_path, _from, _to, _amountIn, _amountOutMin, _cID, _toChainID); } } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForNativeUnderlyingWithTransferPermit( address from, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external virtual ensure(deadline) { IERC20(AnyswapV1ERC20(path[0]).underlying()).transferWithPermit(from, path[0], amountIn, deadline, v, r, s); AnyswapV1ERC20(path[0]).depositVault(amountIn, from); AnyswapV1ERC20(path[0]).burn(from, amountIn); emit LogAnySwapTradeTokensForNative(path, from, to, amountIn, amountOutMin, cID(), toChainID); } // Swaps `amounts[path.length-1]` `path[path.length-1]` to `to` on this chain // Triggered by `anySwapOutExactTokensForNative` function anySwapInExactTokensForNative( bytes32 txs, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint fromChainID ) external onlyMPC virtual ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == wNATIVE, 'AnyswapV3Router: INVALID_PATH'); amounts = SushiswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'AnyswapV3Router: INSUFFICIENT_OUTPUT_AMOUNT'); _anySwapIn(txs, path[0], SushiswapV2Library.pairFor(factory, path[0], path[1]), amounts[0], fromChainID); _swap(amounts, path, address(this)); IwNATIVE(wNATIVE).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferNative(to, amounts[amounts.length - 1]); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual returns (uint amountB) { return SushiswapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual returns (uint amountOut) { return SushiswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual returns (uint amountIn) { return SushiswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual returns (uint[] memory amounts) { return SushiswapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual returns (uint[] memory amounts) { return SushiswapV2Library.getAmountsIn(factory, amountOut, path); } }
sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokensUnderlying( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint toChainID ) external virtual ensure(deadline) { TransferHelper.safeTransferFrom(AnyswapV1ERC20(path[0]).underlying(), msg.sender, path[0], amountIn); AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender); AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn); emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID); }
2,413,584
[ 1, 4424, 731, 279, 6828, 17, 5639, 18542, 628, 333, 2687, 358, 1375, 869, 3893, 734, 68, 364, 1375, 803, 68, 1284, 5489, 358, 1375, 869, 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, 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, 1281, 12521, 1182, 14332, 5157, 1290, 5157, 14655, 6291, 12, 203, 3639, 2254, 3844, 382, 16, 203, 3639, 2254, 3844, 1182, 2930, 16, 203, 3639, 1758, 8526, 745, 892, 589, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 14096, 16, 203, 3639, 2254, 358, 3893, 734, 203, 565, 262, 3903, 5024, 3387, 12, 22097, 1369, 13, 288, 203, 3639, 12279, 2276, 18, 4626, 5912, 1265, 12, 979, 1900, 91, 438, 58, 21, 654, 39, 3462, 12, 803, 63, 20, 65, 2934, 9341, 6291, 9334, 1234, 18, 15330, 16, 589, 63, 20, 6487, 3844, 382, 1769, 203, 3639, 1922, 1900, 91, 438, 58, 21, 654, 39, 3462, 12, 803, 63, 20, 65, 2934, 323, 1724, 12003, 12, 8949, 382, 16, 1234, 18, 15330, 1769, 203, 3639, 1922, 1900, 91, 438, 58, 21, 654, 39, 3462, 12, 803, 63, 20, 65, 2934, 70, 321, 12, 3576, 18, 15330, 16, 3844, 382, 1769, 203, 3639, 3626, 1827, 2961, 12521, 22583, 5157, 1290, 5157, 12, 803, 16, 1234, 18, 15330, 16, 358, 16, 3844, 382, 16, 3844, 1182, 2930, 16, 26222, 9334, 358, 3893, 734, 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 ]
./full_match/3/0x08064DDdcC488EE1ACF405eBb8167dBBF84631d5/sources/browser/MyToken2.sol
* @dev Returns total tokens held by an address (locked + transferable) @param _of The address to query the total balance of/
{ amount = balanceOf(_of); function lock(address _to, bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool) return true; } function transferWithLock(address _to, bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool) } function tokensLocked(address _of, bytes32 _reason) public view override returns (uint256 amount) } function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view override returns (uint256 amount) } function totalBalanceOf(address _of) public view override returns (uint256 amount) for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(tokensLocked(_of, lockReason[_of][i])); } }
8,084,783
[ 1, 1356, 2078, 2430, 15770, 635, 392, 1758, 261, 15091, 397, 7412, 429, 13, 225, 389, 792, 1021, 1758, 358, 843, 326, 2078, 11013, 434, 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, 288, 203, 3639, 3844, 273, 11013, 951, 24899, 792, 1769, 203, 203, 565, 445, 2176, 12, 2867, 389, 869, 16, 1731, 1578, 389, 10579, 16, 2254, 5034, 389, 8949, 16, 2254, 5034, 389, 957, 13, 203, 3639, 1071, 203, 540, 1135, 261, 6430, 13, 203, 3639, 327, 638, 31, 565, 289, 203, 377, 203, 540, 203, 565, 445, 7412, 1190, 2531, 12, 2867, 389, 869, 16, 1731, 1578, 389, 10579, 16, 2254, 5034, 389, 8949, 16, 2254, 5034, 389, 957, 13, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 13, 203, 565, 289, 203, 203, 565, 445, 2430, 8966, 12, 2867, 389, 792, 16, 1731, 1578, 389, 10579, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 1135, 261, 11890, 5034, 3844, 13, 203, 565, 289, 203, 377, 203, 565, 445, 2430, 8966, 861, 950, 12, 2867, 389, 792, 16, 1731, 1578, 389, 10579, 16, 2254, 5034, 389, 957, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 4202, 3849, 1135, 261, 11890, 5034, 3844, 13, 203, 565, 289, 203, 203, 565, 445, 2078, 13937, 951, 12, 2867, 389, 792, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 1135, 261, 11890, 5034, 3844, 13, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2176, 8385, 63, 67, 792, 8009, 2469, 31, 277, 27245, 288, 203, 5411, 3844, 273, 3844, 18, 1289, 12, 7860, 8966, 24899, 792, 16, 2176, 8385, 63, 67, 792, 6362, 77, 5717, 1769, 203, 3639, 289, 27699, 565, 289, 377, 203, 2, -100, -100, -100, -100 ]
pragma solidity 0.4.25; pragma experimental ABIEncoderV2; contract dexBlue{ // Events /** @notice The event, emitted when a trade is settled * @param index Implying the index of the settled trade in the trade array passed to matchTrades() */ event TradeSettled(uint8 index); /** @notice The event, emitted when a trade settlement failed * @param index Implying the index of the failed trade in the trade array passed to matchTrades() */ event TradeFailed(uint8 index); /** @notice The event, emitted after a successful deposit of ETH or token * @param account The address, which initiated the deposit * @param token The address of the deposited token (ETH is address(0)) * @param amount The amount deposited in this transaction */ event Deposit(address account, address token, uint256 amount); /** @notice The event, emitted after a successful (multi-sig) withdrawal of deposited ETH or token * @param account The address, which initiated the withdrawal * @param token The address of the token which is withdrawn (ETH is address(0)) * @param amount The amount withdrawn in this transaction */ event Withdrawal(address account, address token, uint256 amount); /** @notice The event, emitted after a user successfully blocked tokens or ETH for a single signature withdrawal * @param account The address controlling the tokens * @param token The address of the token which is blocked (ETH is address(0)) * @param amount The amount blocked in this transaction */ event BlockedForSingleSigWithdrawal(address account, address token, uint256 amount); /** @notice The event, emitted after a successful single-sig withdrawal of deposited ETH or token * @param account The address, which initiated the withdrawal * @param token The address of the token which is withdrawn (ETH is address(0)) * @param amount The amount withdrawn in this transaction */ event SingleSigWithdrawal(address account, address token, uint256 amount); /** @notice The event, emitted once the feeCollector address initiated a withdrawal of collected tokens or ETH via feeWithdrawal() * @param token The address of the token which is withdrawn (ETH is address(0)) * @param amount The amount withdrawn in this transaction */ event FeeWithdrawal(address token, uint256 amount); /** @notice The event, emitted once an on-chain cancellation of an order was performed * @param hash The invalidated orders hash */ event OrderCanceled(bytes32 hash); /** @notice The event, emitted once a address delegation or dedelegation was performed * @param delegator The delegating address, * @param delegate The delegated address, * @param status Whether the transaction delegated an address (true) or inactivated an active delegation (false) */ event DelegateStatus(address delegator, address delegate, bool status); // Mappings mapping(address => mapping(address => uint256)) balances; // Users balances (token address > user address > balance amount) (ETH is address(0)) mapping(address => mapping(address => uint256)) blocked_for_single_sig_withdrawal; // Users balances they blocked to withdraw without arbiters multi-sig (token address > user address > balance amount) (ETH is address(0)) mapping(address => uint256) last_blocked_timestamp; // The last timestamp a user blocked tokens to withdraw without arbiters multi-sig mapping(bytes32 => bool) processed_withdrawals; // Processed withdrawal hashes mapping(bytes32 => uint256) matched; // Orders matched sell_amounts to prevent multiple-/over- matches of the same orders mapping(address => address) delegates; // Delegated order signing addresses // EIP712 (signTypedData) // EIP712 Domain struct EIP712_Domain { string name; string version; uint256 chainId; address verifyingContract; } bytes32 constant EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 EIP712_DOMAIN_SEPARATOR; // Order typehash bytes32 constant EIP712_ORDER_TYPEHASH = keccak256("Order(address buyTokenAddress,address sellTokenAddress,uint256 buyTokenAmount,uint256 sellTokenAmount,uint64 nonce)"); // Withdrawal typehash bytes32 constant EIP712_WITHDRAWAL_TYPEHASH = keccak256("Withdrawal(address token,uint256 amount,uint64 nonce)"); // Utility functions: /** @notice Get the balance of a user for a specific token * @param token The token address (ETH is token address(0)) * @param holder The address holding the token * @return The amount of the specified token held by the user */ function getBalance(address token, address holder) constant public returns(uint256){ return balances[token][holder]; } /** @notice Get the balance a user blocked for a single-signature withdrawal (ETH is token address(0)) * @param token The token address (ETH is token address(0)) * @param holder The address holding the token * @return The amount of the specified token blocked by the user */ function getBlocked(address token, address holder) constant public returns(uint256){ return blocked_for_single_sig_withdrawal[token][holder]; } /** @notice Returns the timestamp of the last blocked balance * @param user Address of the user which blocked funds * @return The last unix timestamp the user blocked funds at, which starts the waiting period for single-sig withdrawals */ function getLastBlockedTimestamp(address user) constant public returns(uint256){ return last_blocked_timestamp[user]; } // Deposit functions: /** @notice Deposit Ether into the smart contract */ function depositEther() public payable{ balances[address(0)][msg.sender] += msg.value; // Add the received ETH to the users balance emit Deposit(msg.sender, address(0), msg.value); // Emit a deposit event } /** @notice Fallback function to credit ETH sent to the contract without data */ function() public payable{ depositEther(); // Call the deposit function to credit ETH sent in this transaction } /** @notice Deposit ERC20 tokens into the smart contract (remember to set allowance in the token contract first) * @param token The address of the token to deposit * @param amount The amount of tokens to deposit */ function depositToken(address token, uint256 amount) public { Token(token).transferFrom(msg.sender, address(this), amount); // Deposit ERC20 require( checkERC20TransferSuccess(), // Check whether the ERC20 token transfer was successful "ERC20 token transfer failed." ); balances[token][msg.sender] += amount; // Credit the deposited token to users balance emit Deposit(msg.sender, token, amount); // Emit a deposit event } // Multi-sig withdrawal functions: /** @notice User-submitted withdrawal with arbiters signature, which withdraws to the users address * @param token The token to withdraw (ETH is address(address(0))) * @param amount The amount of tokens to withdraw * @param nonce The nonce (to salt the hash) * @param v Multi-signature v * @param r Multi-signature r * @param s Multi-signature s */ function multiSigWithdrawal(address token, uint256 amount, uint64 nonce, uint8 v, bytes32 r, bytes32 s) public { bytes32 hash = keccak256(abi.encodePacked( // Calculate the withdrawal hash from the parameters "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked( msg.sender, token, amount, nonce, address(this) )) )); if( !processed_withdrawals[hash] // Check if the withdrawal was initiated before && arbiters[ecrecover(hash, v,r,s)] // Check if the multi-sig is valid && balances[token][msg.sender] >= amount // Check if the user holds the required balance ){ processed_withdrawals[hash] = true; // Mark this withdrawal as processed balances[token][msg.sender] -= amount; // Substract withdrawn token from users balance if(token == address(0)){ // Withdraw ETH require( msg.sender.send(amount), "Sending of ETH failed." ); }else{ // Withdraw an ERC20 token Token(token).transfer(msg.sender, amount); // Transfer the ERC20 token require( checkERC20TransferSuccess(), // Check whether the ERC20 token transfer was successful "ERC20 token transfer failed." ); } blocked_for_single_sig_withdrawal[token][msg.sender] = 0; // Set possible previous manual blocking of these funds to 0 emit Withdrawal(msg.sender,token,amount); // Emit a Withdrawal event }else{ revert(); // Revert the transaction if checks fail } } /** @notice User-submitted withdrawal with arbiters signature, which sends tokens to specified address * @param token The token to withdraw (ETH is address(address(0))) * @param amount The amount of tokens to withdraw * @param nonce The nonce (to salt the hash) * @param v Multi-signature v * @param r Multi-signature r * @param s Multi-signature s * @param receiving_address The address to send the withdrawn token/ETH to */ function multiSigSend(address token, uint256 amount, uint64 nonce, uint8 v, bytes32 r, bytes32 s, address receiving_address) public { bytes32 hash = keccak256(abi.encodePacked( // Calculate the withdrawal hash from the parameters "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked( msg.sender, token, amount, nonce, address(this) )) )); if( !processed_withdrawals[hash] // Check if the withdrawal was initiated before && arbiters[ecrecover(hash, v,r,s)] // Check if the multi-sig is valid && balances[token][msg.sender] >= amount // Check if the user holds the required balance ){ processed_withdrawals[hash] = true; // Mark this withdrawal as processed balances[token][msg.sender] -= amount; // Substract the withdrawn balance from the users balance if(token == address(0)){ // Process an ETH withdrawal require( receiving_address.send(amount), "Sending of ETH failed." ); }else{ // Withdraw an ERC20 token Token(token).transfer(receiving_address, amount); // Transfer the ERC20 token require( checkERC20TransferSuccess(), // Check whether the ERC20 token transfer was successful "ERC20 token transfer failed." ); } blocked_for_single_sig_withdrawal[token][msg.sender] = 0; // Set possible previous manual blocking of these funds to 0 emit Withdrawal(msg.sender,token,amount); // Emit a Withdrawal event }else{ revert(); // Revert the transaction if checks fail } } /** @notice User-submitted transfer with arbiters signature, which sends tokens to another addresses account in the smart contract * @param token The token to transfer (ETH is address(address(0))) * @param amount The amount of tokens to transfer * @param nonce The nonce (to salt the hash) * @param v Multi-signature v * @param r Multi-signature r * @param s Multi-signature s * @param receiving_address The address to transfer the token/ETH to */ function multiSigTransfer(address token, uint256 amount, uint64 nonce, uint8 v, bytes32 r, bytes32 s, address receiving_address) public { bytes32 hash = keccak256(abi.encodePacked( // Calculate the withdrawal/transfer hash from the parameters "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked( msg.sender, token, amount, nonce, address(this) )) )); if( !processed_withdrawals[hash] // Check if the withdrawal was initiated before && arbiters[ecrecover(hash, v,r,s)] // Check if the multi-sig is valid && balances[token][msg.sender] >= amount // Check if the user holds the required balance ){ processed_withdrawals[hash] = true; // Mark this withdrawal as processed balances[token][msg.sender] -= amount; // Substract the balance from the withdrawing account balances[token][receiving_address] += amount; // Add the balance to the receiving account blocked_for_single_sig_withdrawal[token][msg.sender] = 0; // Set possible previous manual blocking of these funds to 0 emit Withdrawal(msg.sender,token,amount); // Emit a Withdrawal event emit Deposit(receiving_address,token,amount); // Emit a Deposit event }else{ revert(); // Revert the transaction if checks fail } } /** @notice Arbiter submitted withdrawal with users multi-sig to users address * @param token The token to withdraw (ETH is address(address(0))) * @param amount The amount of tokens to withdraw * @param fee The fee, covering the gas cost of the arbiter * @param nonce The nonce (to salt the hash) * @param v Multi-signature v (either 27 or 28. To identify the different signing schemes an offset of 10 is applied for EIP712) * @param r Multi-signature r * @param s Multi-signature s */ function userSigWithdrawal(address token, uint256 amount, uint256 fee, uint64 nonce, uint8 v, bytes32 r, bytes32 s) public { bytes32 hash; if(v < 30){ // Standard signing scheme (personal.sign()) hash = keccak256(abi.encodePacked( // Restore multi-sig hash "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked( token, amount, nonce, address(this) )) )); }else{ // EIP712 signing scheme v -= 10; // Remove offset hash = keccak256(abi.encodePacked( // Restore multi-sig hash "\x19\x01", EIP712_DOMAIN_SEPARATOR, keccak256(abi.encode( EIP712_WITHDRAWAL_TYPEHASH, token, amount, nonce )) )); } address account = ecrecover(hash, v, r, s); // Restore signing address if( !processed_withdrawals[hash] // Check if the withdrawal was initiated before && arbiters[msg.sender] // Check if transaction comes from arbiter && fee <= amount / 50 // Check if fee is not too big && balances[token][account] >= amount // Check if the user holds the required tokens ){ processed_withdrawals[hash] = true; balances[token][account] -= amount; balances[token][feeCollector] += fee; // Fee to cover gas costs for the withdrawal if(token == address(0)){ // Send ETH require( account.send(amount - fee), "Sending of ETH failed." ); }else{ Token(token).transfer(account, amount - fee); // Withdraw ERC20 require( checkERC20TransferSuccess(), // Check if the transfer was successful "ERC20 token transfer failed." ); } blocked_for_single_sig_withdrawal[token][account] = 0; // Set possible previous manual blocking of these funds to 0 emit Withdrawal(account,token,amount); // Emit a Withdrawal event }else{ revert(); // Revert the transaction is checks fail } } // Single-sig withdrawal functions: /** @notice Allows user to block funds for single-sig withdrawal after 24h waiting period * (This period is necessary to ensure all trades backed by these funds will be settled.) * @param token The address of the token to block (ETH is address(address(0))) * @param amount The amount of the token to block */ function blockFundsForSingleSigWithdrawal(address token, uint256 amount) public { if (balances[token][msg.sender] - blocked_for_single_sig_withdrawal[token][msg.sender] >= amount){ // Check if the user holds the required funds blocked_for_single_sig_withdrawal[token][msg.sender] += amount; // Block funds for manual withdrawal last_blocked_timestamp[msg.sender] = block.timestamp; // Start 24h waiting period emit BlockedForSingleSigWithdrawal(msg.sender,token,amount); // Emit BlockedForSingleSigWithdrawal event }else{ revert(); // Revert the transaction if the user does not hold the required balance } } /** @notice Allows user to withdraw funds previously blocked after 24h */ function initiateSingleSigWithdrawal(address token, uint256 amount) public { if ( balances[token][msg.sender] >= amount // Check if the user holds the funds && blocked_for_single_sig_withdrawal[token][msg.sender] >= amount // Check if these funds are blocked && last_blocked_timestamp[msg.sender] + 86400 <= block.timestamp // Check if the one day waiting period has passed ){ balances[token][msg.sender] -= amount; // Substract the tokens from users balance blocked_for_single_sig_withdrawal[token][msg.sender] -= amount; // Substract the tokens from users blocked balance if(token == address(0)){ // Withdraw ETH require( msg.sender.send(amount), "Sending of ETH failed." ); }else{ // Withdraw ERC20 tokens Token(token).transfer(msg.sender, amount); // Transfer the ERC20 tokens require( checkERC20TransferSuccess(), // Check if the transfer was successful "ERC20 token transfer failed." ); } emit SingleSigWithdrawal(msg.sender,token,amount); // Emit a SingleSigWithdrawal event }else{ revert(); // Revert the transaction if the required checks fail } } //Trade settlement structs and function struct OrderInput{ uint8 buy_token; // The token, the order signee wants to buy uint8 sell_token; // The token, the order signee wants to sell uint256 buy_amount; // The total amount the signee wants to buy uint256 sell_amount; // The total amount the signee wants to give for the amount he wants to buy (the orders "rate" is implied by the ratio between the two amounts) uint64 nonce; // Random number to give each order an individual hash and signature int8 v; // Signature v (either 27 or 28) // To identify the different signing schemes an offset of 10 is applied for EIP712. // To identify whether the order was signed by a delegated signing address, the number is either positive or negative. bytes32 r; // Signature r bytes32 s; // Signature s } struct TradeInput{ uint8 maker_order; // The index of the maker order uint8 taker_order; // The index of the taker order uint256 maker_amount; // The amount the maker gives in return for the taker's tokens uint256 taker_amount; // The amount the taker gives in return for the maker's tokens uint256 maker_fee; // The trading fee of the maker + a share in the settlement (gas) cost uint256 taker_fee; // The trading fee of the taker + a share in the settlement (gas) cost uint256 maker_rebate; // A optional rebate for the maker (portion of takers fee) as an incentive } /** @notice Allows an arbiter to settle trades between two user-signed orders * @param addresses Array of all addresses involved in the transactions * @param orders Array of all orders involved in the transactions * @param trades Array of the trades to be settled */ function matchTrades(address[] addresses, OrderInput[] orders, TradeInput[] trades) public { require(arbiters[msg.sender] && marketActive); // Check if msg.sender is an arbiter and the market is active //Restore signing addresses uint len = orders.length; // Length of orders array to loop through bytes32[] memory hashes = new bytes32[](len); // Array of the restored order hashes address[] memory signee = new address[](len); // Array of the restored order signees OrderInput memory order; // Memory slot to cache orders while looping (otherwise the Stack would be too deep) address addressCache1; // Memory slot 1 to cache addresses while looping (otherwise the Stack would be too deep) address addressCache2; // Memory slot 2 to cache addresses while looping (otherwise the Stack would be too deep) bool delegated; for(uint8 i = 0; i < len; i++){ // Loop through the orders array to restore all signees order = orders[i]; // Cache order addressCache1 = addresses[order.buy_token]; // Cache orders buy token addressCache2 = addresses[order.sell_token]; // Cache orders sell token if(order.v < 0){ // Check if the order is signed by a delegate delegated = true; order.v *= -1; // Restore the negated v }else{ delegated = false; } if(order.v < 30){ // Order is hashed after signature scheme personal.sign() hashes[i] = keccak256(abi.encodePacked( // Restore the hash of this order "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked( addressCache1, addressCache2, order.buy_amount, order.sell_amount, order.nonce, address(this) // This contract's address )) )); }else{ // Order is hashed after EIP712 order.v -= 10; // Remove signature format identifying offset hashes[i] = keccak256(abi.encodePacked( "\x19\x01", EIP712_DOMAIN_SEPARATOR, keccak256(abi.encode( EIP712_ORDER_TYPEHASH, addressCache1, addressCache2, order.buy_amount, order.sell_amount, order.nonce )) )); } signee[i] = ecrecover( // Restore the signee of this order hashes[i], // Order hash uint8(order.v), // Signature v order.r, // Signature r order.s // Signature s ); // When the signature was delegated restore delegating address if(delegated){ signee[i] = delegates[signee[i]]; } } // Settle Trades after check len = trades.length; // Length of the trades array to loop through TradeInput memory trade; // Memory slot to cache trades while looping uint maker_index; // Memory slot to cache the trade's maker order index uint taker_index; // Memory slot to cache the trade's taker order index for(i = 0; i < len; i++){ // Loop through trades to settle after checks trade = trades[i]; // Cache trade maker_index = trade.maker_order; // Cache maker order index taker_index = trade.taker_order; // Cache taker order index addressCache1 = addresses[orders[maker_index].buy_token]; // Cache first of the two swapped token addresses addressCache2 = addresses[orders[taker_index].buy_token]; // Cache second of the two swapped token addresses if( // Check if the arbiter has matched following the conditions of the two order signees // Do maker and taker want to trade the same tokens with each other orders[maker_index].buy_token == orders[taker_index].sell_token && orders[taker_index].buy_token == orders[maker_index].sell_token // Do maker and taker hold the required balances && balances[addressCache2][signee[maker_index]] >= trade.maker_amount - trade.maker_rebate && balances[addressCache1][signee[taker_index]] >= trade.taker_amount // Are they both matched at a rate better or equal to the one they signed && trade.maker_amount - trade.maker_rebate <= orders[maker_index].sell_amount * trade.taker_amount / orders[maker_index].buy_amount + 1 // Check maker doesn't overpay (+ 1 to deal with rouding errors for very smal amounts) && trade.taker_amount <= orders[taker_index].sell_amount * trade.maker_amount / orders[taker_index].buy_amount + 1 // Check taker doesn't overpay (+ 1 to deal with rouding errors for very smal amounts) // Check if the matched amount + previously matched trades doesn't exceed the amount specified by the order signee && trade.taker_amount + matched[hashes[taker_index]] <= orders[taker_index].sell_amount && trade.maker_amount - trade.maker_rebate + matched[hashes[maker_index]] <= orders[maker_index].sell_amount // Check if the charged fee is not too high && trade.maker_fee <= trade.taker_amount / 100 && trade.taker_fee <= trade.maker_amount / 50 // Check if maker_rebate is smaller than or equal to the taker's fee which compensates it && trade.maker_rebate <= trade.taker_fee ){ // Settle the trade: // Substract sold amounts balances[addressCache2][signee[maker_index]] -= trade.maker_amount - trade.maker_rebate; // Substract maker's sold amount minus the makers rebate balances[addressCache1][signee[taker_index]] -= trade.taker_amount; // Substract taker's sold amount // Add bought amounts balances[addressCache1][signee[maker_index]] += trade.taker_amount - trade.maker_fee; // Give the maker his bought amount minus the fee balances[addressCache2][signee[taker_index]] += trade.maker_amount - trade.taker_fee; // Give the taker his bought amount minus the fee // Save bought amounts to prevent double matching matched[hashes[maker_index]] += trade.maker_amount; // Prevent maker order from being reused matched[hashes[taker_index]] += trade.taker_amount; // Prevent taker order from being reused // Give fee to feeCollector balances[addressCache2][feeCollector] += trade.taker_fee - trade.maker_rebate; // Give the feeColletor the taker fee minus the maker rebate balances[addressCache1][feeCollector] += trade.maker_fee; // Give the feeColletor the maker fee // Set possible previous manual blocking of these funds to 0 blocked_for_single_sig_withdrawal[addressCache2][signee[maker_index]] = 0; // If the maker tried to block funds which he/she used in this order we have to unblock them blocked_for_single_sig_withdrawal[addressCache1][signee[taker_index]] = 0; // If the taker tried to block funds which he/she used in this order we have to unblock them emit TradeSettled(i); // Emit tradeSettled Event to confirm the trade was settled }else{ emit TradeFailed(i); // Emit tradeFailed Event because the trade checks failed } } } // Order cancellation functions /** @notice Give the user the option to perform multiple on-chain cancellations of orders at once with arbiters multi-sig * @param orderHashes Array of orderHashes of the orders to be canceled * @param v Multi-sig v * @param r Multi-sig r * @param s Multi-sig s */ function multiSigOrderBatchCancel(bytes32[] orderHashes, uint8 v, bytes32 r, bytes32 s) public { if( arbiters[ // Check if the signee is an arbiter ecrecover( // Restore the signing address keccak256(abi.encodePacked( // Restore the signed hash (hash of all orderHashes) "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(orderHashes)) )), v, r, s ) ] ){ uint len = orderHashes.length; for(uint8 i = 0; i < len; i++){ matched[orderHashes[i]] = 2**256 - 1; // Set the matched amount of all orders to the maximum emit OrderCanceled(orderHashes[i]); // emit OrderCanceled event } }else{ revert(); } } /** @notice Give arbiters the option to perform on-chain multiple cancellations of orders at once * @param orderHashes Array of hashes of the orders to be canceled */ function orderBatchCancel(bytes32[] orderHashes) public { if( arbiters[msg.sender] // Check if the sender is an arbiter ){ uint len = orderHashes.length; for(uint8 i = 0; i < len; i++){ matched[orderHashes[i]] = 2**256 - 1; // Set the matched amount of all orders to the maximum emit OrderCanceled(orderHashes[i]); // emit OrderCanceled event } }else{ revert(); } } // Signature delegation /** @notice delegate an address to allow it to sign orders on your behalf * @param delegate The address to delegate */ function delegateAddress(address delegate) public { // set as delegate require(delegates[delegate] == address(0), "Address is already a delegate"); delegates[delegate] = msg.sender; emit DelegateStatus(msg.sender, delegate, true); } /** @notice revoke the delegation of an address * @param delegate The delegated address * @param v Multi-sig v * @param r Multi-sig r * @param s Multi-sig s */ function revokeDelegation(address delegate, uint8 v, bytes32 r, bytes32 s) public { bytes32 hash = keccak256(abi.encodePacked( // Restore the signed hash "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked( delegate, msg.sender, address(this) )) )); require(arbiters[ecrecover(hash, v, r, s)], "MultiSig is not from known arbiter"); // Check if signee is an arbiter delegates[delegate] = address(1); // set to 1 not 0 to prevent double delegation, which would make old signed order valid for the new delegator emit DelegateStatus(msg.sender, delegate, false); } // Management functions: address owner; // Contract owner address (has the right to nominate arbiters and the feeCollectors addresses) address feeCollector; // feeCollector address bool marketActive = true; // Make it possible to pause the market bool feeCollectorLocked = false; // Make it possible to lock the feeCollector address (to allow to change the feeCollector to a fee distribution contract) mapping(address => bool) arbiters; // Mapping of arbiters /** @notice Constructor function */ constructor() public { owner = msg.sender; // Nominate sender to be the contract owner feeCollector = msg.sender; // Nominate sender to be the standart feeCollector arbiters[msg.sender] = true; // Nominate sender to be an arbiter // create EIP712 domain seperator EIP712_Domain memory eip712Domain = EIP712_Domain({ name : "dex.blue", version : "1", chainId : 1, verifyingContract : this }); EIP712_DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract )); } /** @notice Allows the owner to nominate or denominate trade arbitting addresses * @param arbiter The arbiter whose status to change * @param status Whether the address should be an arbiter (true) or not (false) */ function nominateArbiter(address arbiter, bool status) public { require(msg.sender == owner); // Check if sender is owner arbiters[arbiter] = status; // Update address status } /** @notice Allows the owner to pause / unpause the market * @param state Whether the the market should be active (true) or paused (false) */ function setMarketActiveState(bool state) public { require(msg.sender == owner); // Check if sender is owner marketActive = state; // pause / unpause market } /** @notice Allows the owner to nominate the feeCollector address * @param collector The address to nominate as feeCollector */ function nominateFeeCollector(address collector) public { require(msg.sender == owner && !feeCollectorLocked); // Check if sender is owner and feeCollector address is not locked feeCollector = collector; // Update feeCollector address } /** @notice Allows the owner to lock the feeCollector address */ function lockFeeCollector() public { require(msg.sender == owner); // Check if sender is owner feeCollectorLocked = true; // Lock feeCollector address } /** @notice Get the feeCollectors address * @return The feeCollectors address */ function getFeeCollector() public constant returns (address){ return feeCollector; } /** @notice Allows the feeCollector to directly withdraw his funds (would allow a fee distribution contract to withdraw collected fees) * @param token The token to withdraw * @param amount The amount of tokens to withdraw */ function feeWithdrawal(address token, uint256 amount) public { if ( msg.sender == feeCollector // Check if the sender is the feeCollector && balances[token][feeCollector] >= amount // Check if feeCollector has the sufficient balance ){ balances[token][feeCollector] -= amount; // Substract the feeCollectors balance if(token == address(0)){ // Is the withdrawal token ETH require( feeCollector.send(amount), // Withdraw ETH "Sending of ETH failed." ); }else{ Token(token).transfer(feeCollector, amount); // Withdraw ERC20 require( // Revert if the withdrawal failed checkERC20TransferSuccess(), "ERC20 token transfer failed." ); } emit FeeWithdrawal(token,amount); // Emit FeeWithdrawal event }else{ revert(); // Revert the transaction if the checks fail } } // We have to check returndatasize after ERC20 tokens transfers, as some tokens are implemented badly (dont return a boolean) function checkERC20TransferSuccess() pure private returns(bool){ uint256 success = 0; assembly { switch returndatasize // Check the number of bytes the token contract returned case 0 { // Nothing returned, but contract did not throw > assume our transfer succeeded success := 1 } case 32 { // 32 bytes returned, result is the returned bool returndatacopy(0, 0, 32) success := mload(0) } } return success != 0; } } // Standart ERC20 token interface to interact with ERC20 token contracts // To support badly implemented tokens (which dont return a boolean on the transfer functions) // we have to expect a badly implemented token and then check with checkERC20TransferSuccess() whether the transfer succeeded contract Token { /** @return total amount of tokens */ function totalSupply() constant public returns (uint256 supply) {} /** @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) constant public returns (uint256 balance) {} /** @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of tokens to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public {} /** @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 tokens to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint256 _value) public {} /** @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) public 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 spend */ function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); uint public decimals; string public name; }
Is the withdrawal token ETH
if(token == address(0)){
12,878,822
[ 1, 2520, 326, 598, 9446, 287, 1147, 512, 2455, 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, 5411, 309, 12, 2316, 422, 1758, 12, 20, 3719, 95, 4766, 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 ]
pragma solidity ^0.4.0; interface 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); } // GOO - Crypto Idle Game // https://ethergoo.io contract Goo is ERC20 { string public constant name = "IdleEth"; string public constant symbol = "Goo"; uint8 public constant decimals = 0; uint256 private roughSupply; uint256 public totalGooProduction; address public owner; // Minor management of game bool public gameStarted; uint256 public totalEtherGooResearchPool; // Eth dividends to be split between players' goo production uint256[] public totalGooProductionSnapshots; // The total goo production for each prior day past uint256[] public allocatedGooResearchSnapshots; // The research eth allocated to each prior day past uint256 public nextSnapshotTime; uint256 private MAX_PRODUCTION_UNITS = 999; // Per type (makes balancing slightly easier) uint256 private constant RAFFLE_TICKET_BASE_GOO_PRICE = 1000; // Balances for each player mapping(address => uint256) private ethBalance; mapping(address => uint256) private gooBalance; mapping(address => mapping(uint256 => uint256)) private gooProductionSnapshots; // Store player's goo production for given day (snapshot) mapping(address => mapping(uint256 => bool)) private gooProductionZeroedSnapshots; // This isn't great but we need know difference between 0 production and an unused/inactive day. mapping(address => uint256) private lastGooSaveTime; // Seconds (last time player claimed their produced goo) mapping(address => uint256) public lastGooProductionUpdate; // Days (last snapshot player updated their production) mapping(address => uint256) private lastGooResearchFundClaim; // Days (snapshot number) mapping(address => uint256) private battleCooldown; // If user attacks they cannot attack again for short time // Stuff owned by each player mapping(address => mapping(uint256 => uint256)) private unitsOwned; mapping(address => mapping(uint256 => bool)) private upgradesOwned; mapping(uint256 => address) private rareItemOwner; mapping(uint256 => uint256) private rareItemPrice; // Rares & Upgrades (Increase unit's production / attack etc.) mapping(address => mapping(uint256 => uint256)) private unitGooProductionIncreases; // Adds to the goo per second mapping(address => mapping(uint256 => uint256)) private unitGooProductionMultiplier; // Multiplies the goo per second mapping(address => mapping(uint256 => uint256)) private unitAttackIncreases; mapping(address => mapping(uint256 => uint256)) private unitAttackMultiplier; mapping(address => mapping(uint256 => uint256)) private unitDefenseIncreases; mapping(address => mapping(uint256 => uint256)) private unitDefenseMultiplier; mapping(address => mapping(uint256 => uint256)) private unitGooStealingIncreases; mapping(address => mapping(uint256 => uint256)) private unitGooStealingMultiplier; // Mapping of approved ERC20 transfers (by player) mapping(address => mapping(address => uint256)) private allowed; mapping(address => bool) private protectedAddresses; // For npc exchanges (requires 0 goo production) // Raffle structures struct TicketPurchases { TicketPurchase[] ticketsBought; uint256 numPurchases; // Allows us to reset without clearing TicketPurchase[] (avoids potential for gas limit) uint256 raffleRareId; } // Allows us to query winner without looping (avoiding potential for gas limit) struct TicketPurchase { uint256 startId; uint256 endId; } // Raffle tickets mapping(address => TicketPurchases) private ticketsBoughtByPlayer; mapping(uint256 => address[]) private rafflePlayers; // Keeping a seperate list for each raffle has it's benefits. // Current raffle info uint256 private raffleEndTime; uint256 private raffleRareId; uint256 private raffleTicketsBought; address private raffleWinner; // Address of winner bool private raffleWinningTicketSelected; uint256 private raffleTicketThatWon; // Minor game events event UnitBought(address player, uint256 unitId, uint256 amount); event UnitSold(address player, uint256 unitId, uint256 amount); event PlayerAttacked(address attacker, address target, bool success, uint256 gooStolen); GooGameConfig schema; // Constructor function Goo() public payable { owner = msg.sender; schema = GooGameConfig(0x21912e81d7eff8bff895302b45da76f7f070e3b9); } function() payable { } function beginGame(uint256 firstDivsTime) external payable { require(msg.sender == owner); require(!gameStarted); gameStarted = true; // GO-OOOO! nextSnapshotTime = firstDivsTime; totalEtherGooResearchPool = msg.value; // Seed pot } function totalSupply() public constant returns(uint256) { return roughSupply; // Stored goo (rough supply as it ignores earned/unclaimed goo) } function balanceOf(address player) public constant returns(uint256) { return gooBalance[player] + balanceOfUnclaimedGoo(player); } function balanceOfUnclaimedGoo(address player) internal constant returns (uint256) { if (lastGooSaveTime[player] > 0 && lastGooSaveTime[player] < block.timestamp) { return (getGooProduction(player) * (block.timestamp - lastGooSaveTime[player])); } return 0; } function etherBalanceOf(address player) public constant returns(uint256) { return ethBalance[player]; } function transfer(address recipient, uint256 amount) public returns (bool) { updatePlayersGoo(msg.sender); require(amount <= gooBalance[msg.sender]); gooBalance[msg.sender] -= amount; gooBalance[recipient] += amount; emit Transfer(msg.sender, recipient, amount); return true; } function transferFrom(address player, address recipient, uint256 amount) public returns (bool) { updatePlayersGoo(player); require(amount <= allowed[player][msg.sender] && amount <= gooBalance[msg.sender]); gooBalance[player] -= amount; gooBalance[recipient] += amount; allowed[player][msg.sender] -= amount; emit Transfer(player, recipient, amount); return true; } function approve(address approvee, uint256 amount) public returns (bool){ allowed[msg.sender][approvee] = amount; emit Approval(msg.sender, approvee, amount); return true; } function allowance(address player, address approvee) public constant returns(uint256){ return allowed[player][approvee]; } function getGooProduction(address player) public constant returns (uint256){ return gooProductionSnapshots[player][lastGooProductionUpdate[player]]; } function updatePlayersGoo(address player) internal { uint256 gooGain = balanceOfUnclaimedGoo(player); lastGooSaveTime[player] = block.timestamp; roughSupply += gooGain; gooBalance[player] += gooGain; } function updatePlayersGooFromPurchase(address player, uint256 purchaseCost) internal { uint256 unclaimedGoo = balanceOfUnclaimedGoo(player); if (purchaseCost > unclaimedGoo) { uint256 gooDecrease = purchaseCost - unclaimedGoo; roughSupply -= gooDecrease; gooBalance[player] -= gooDecrease; } else { uint256 gooGain = unclaimedGoo - purchaseCost; roughSupply += gooGain; gooBalance[player] += gooGain; } lastGooSaveTime[player] = block.timestamp; } function increasePlayersGooProduction(uint256 increase) internal { gooProductionSnapshots[msg.sender][allocatedGooResearchSnapshots.length] = getGooProduction(msg.sender) + increase; lastGooProductionUpdate[msg.sender] = allocatedGooResearchSnapshots.length; totalGooProduction += increase; } function reducePlayersGooProduction(address player, uint256 decrease) internal { uint256 previousProduction = getGooProduction(player); uint256 newProduction = SafeMath.sub(previousProduction, decrease); if (newProduction == 0) { // Special case which tangles with "inactive day" snapshots (claiming divs) gooProductionZeroedSnapshots[player][allocatedGooResearchSnapshots.length] = true; delete gooProductionSnapshots[player][allocatedGooResearchSnapshots.length]; // 0 } else { gooProductionSnapshots[player][allocatedGooResearchSnapshots.length] = newProduction; } lastGooProductionUpdate[player] = allocatedGooResearchSnapshots.length; totalGooProduction -= decrease; } function buyBasicUnit(uint256 unitId, uint256 amount) external { require(gameStarted); require(schema.validUnitId(unitId)); require(unitsOwned[msg.sender][unitId] + amount <= MAX_PRODUCTION_UNITS); uint256 unitCost = schema.getGooCostForUnit(unitId, unitsOwned[msg.sender][unitId], amount); require(balanceOf(msg.sender) >= unitCost); require(schema.unitEthCost(unitId) == 0); // Free unit // Update players goo updatePlayersGooFromPurchase(msg.sender, unitCost); if (schema.unitGooProduction(unitId) > 0) { increasePlayersGooProduction(getUnitsProduction(msg.sender, unitId, amount)); } unitsOwned[msg.sender][unitId] += amount; emit UnitBought(msg.sender, unitId, amount); } function buyEthUnit(uint256 unitId, uint256 amount) external payable { require(gameStarted); require(schema.validUnitId(unitId)); require(unitsOwned[msg.sender][unitId] + amount <= MAX_PRODUCTION_UNITS); uint256 unitCost = schema.getGooCostForUnit(unitId, unitsOwned[msg.sender][unitId], amount); uint256 ethCost = SafeMath.mul(schema.unitEthCost(unitId), amount); require(balanceOf(msg.sender) >= unitCost); require(ethBalance[msg.sender] + msg.value >= ethCost); // Update players goo updatePlayersGooFromPurchase(msg.sender, unitCost); if (ethCost > msg.value) { ethBalance[msg.sender] -= (ethCost - msg.value); } uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance) uint256 dividends = (ethCost - devFund) / 4; // 25% goes to pool (75% retained for sale value) totalEtherGooResearchPool += dividends; ethBalance[owner] += devFund; if (schema.unitGooProduction(unitId) > 0) { increasePlayersGooProduction(getUnitsProduction(msg.sender, unitId, amount)); } unitsOwned[msg.sender][unitId] += amount; emit UnitBought(msg.sender, unitId, amount); } function sellUnit(uint256 unitId, uint256 amount) external { require(unitsOwned[msg.sender][unitId] >= amount); unitsOwned[msg.sender][unitId] -= amount; uint256 unitSalePrice = (schema.getGooCostForUnit(unitId, unitsOwned[msg.sender][unitId], amount) * 3) / 4; // 75% uint256 gooChange = balanceOfUnclaimedGoo(msg.sender) + unitSalePrice; // Claim unsaved goo whilst here lastGooSaveTime[msg.sender] = block.timestamp; roughSupply += gooChange; gooBalance[msg.sender] += gooChange; if (schema.unitGooProduction(unitId) > 0) { reducePlayersGooProduction(msg.sender, getUnitsProduction(msg.sender, unitId, amount)); } if (schema.unitEthCost(unitId) > 0) { // Premium units sell for 75% of buy cost ethBalance[msg.sender] += ((schema.unitEthCost(unitId) * amount) * 3) / 4; } emit UnitSold(msg.sender, unitId, amount); } function buyUpgrade(uint256 upgradeId) external payable { require(gameStarted); require(schema.validUpgradeId(upgradeId)); // Valid upgrade require(!upgradesOwned[msg.sender][upgradeId]); // Haven't already purchased uint256 gooCost; uint256 ethCost; uint256 upgradeClass; uint256 unitId; uint256 upgradeValue; (gooCost, ethCost, upgradeClass, unitId, upgradeValue) = schema.getUpgradeInfo(upgradeId); require(balanceOf(msg.sender) >= gooCost); if (ethCost > 0) { require(ethBalance[msg.sender] + msg.value >= ethCost); if (ethCost > msg.value) { // They can use their balance instead ethBalance[msg.sender] -= (ethCost - msg.value); } uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance) totalEtherGooResearchPool += (ethCost - devFund); // Rest goes to div pool (Can't sell upgrades) ethBalance[owner] += devFund; } // Update players goo updatePlayersGooFromPurchase(msg.sender, gooCost); upgradeUnitMultipliers(msg.sender, upgradeClass, unitId, upgradeValue); upgradesOwned[msg.sender][upgradeId] = true; } function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal { uint256 productionGain; if (upgradeClass == 0) { unitGooProductionIncreases[player][unitId] += upgradeValue; productionGain = (unitsOwned[player][unitId] * upgradeValue * (10 + unitGooProductionMultiplier[player][unitId])) / 10; increasePlayersGooProduction(productionGain); } else if (upgradeClass == 1) { unitGooProductionMultiplier[player][unitId] += upgradeValue; productionGain = (unitsOwned[player][unitId] * upgradeValue * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId])) / 10; increasePlayersGooProduction(productionGain); } else if (upgradeClass == 2) { unitAttackIncreases[player][unitId] += upgradeValue; } else if (upgradeClass == 3) { unitAttackMultiplier[player][unitId] += upgradeValue; } else if (upgradeClass == 4) { unitDefenseIncreases[player][unitId] += upgradeValue; } else if (upgradeClass == 5) { unitDefenseMultiplier[player][unitId] += upgradeValue; } else if (upgradeClass == 6) { unitGooStealingIncreases[player][unitId] += upgradeValue; } else if (upgradeClass == 7) { unitGooStealingMultiplier[player][unitId] += upgradeValue; } } function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal { uint256 productionLoss; if (upgradeClass == 0) { unitGooProductionIncreases[player][unitId] -= upgradeValue; productionLoss = (unitsOwned[player][unitId] * upgradeValue * (10 + unitGooProductionMultiplier[player][unitId])) / 10; reducePlayersGooProduction(player, productionLoss); } else if (upgradeClass == 1) { unitGooProductionMultiplier[player][unitId] -= upgradeValue; productionLoss = (unitsOwned[player][unitId] * upgradeValue * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId])) / 10; reducePlayersGooProduction(player, productionLoss); } else if (upgradeClass == 2) { unitAttackIncreases[player][unitId] -= upgradeValue; } else if (upgradeClass == 3) { unitAttackMultiplier[player][unitId] -= upgradeValue; } else if (upgradeClass == 4) { unitDefenseIncreases[player][unitId] -= upgradeValue; } else if (upgradeClass == 5) { unitDefenseMultiplier[player][unitId] -= upgradeValue; } else if (upgradeClass == 6) { unitGooStealingIncreases[player][unitId] -= upgradeValue; } else if (upgradeClass == 7) { unitGooStealingMultiplier[player][unitId] -= upgradeValue; } } function buyRareItem(uint256 rareId) external payable { require(schema.validRareId(rareId)); address previousOwner = rareItemOwner[rareId]; require(previousOwner != 0); uint256 ethCost = rareItemPrice[rareId]; require(ethBalance[msg.sender] + msg.value >= ethCost); // We have to claim buyer's goo before updating their production values updatePlayersGoo(msg.sender); uint256 upgradeClass; uint256 unitId; uint256 upgradeValue; (upgradeClass, unitId, upgradeValue) = schema.getRareInfo(rareId); upgradeUnitMultipliers(msg.sender, upgradeClass, unitId, upgradeValue); // We have to claim seller's goo before reducing their production values updatePlayersGoo(previousOwner); removeUnitMultipliers(previousOwner, upgradeClass, unitId, upgradeValue); // Splitbid/Overbid if (ethCost > msg.value) { // Earlier require() said they can still afford it (so use their ingame balance) ethBalance[msg.sender] -= (ethCost - msg.value); } else if (msg.value > ethCost) { // Store overbid in their balance ethBalance[msg.sender] += msg.value - ethCost; } // Distribute ethCost uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance) uint256 dividends = ethCost / 20; // 5% goes to pool (~93% goes to player) totalEtherGooResearchPool += dividends; ethBalance[owner] += devFund; // Transfer / update rare item rareItemOwner[rareId] = msg.sender; rareItemPrice[rareId] = (ethCost * 5) / 4; // 25% price flip increase ethBalance[previousOwner] += ethCost - (dividends + devFund); } function withdrawEther(uint256 amount) external { require(amount <= ethBalance[msg.sender]); ethBalance[msg.sender] -= amount; msg.sender.transfer(amount); } function claimResearchDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external { require(startSnapshot <= endSnapShot); require(startSnapshot >= lastGooResearchFundClaim[msg.sender]); require(endSnapShot < allocatedGooResearchSnapshots.length); uint256 researchShare; uint256 previousProduction = gooProductionSnapshots[msg.sender][lastGooResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xffffffffff] = 0; for (uint256 i = startSnapshot; i <= endSnapShot; i++) { // Slightly complex things by accounting for days/snapshots when user made no tx's uint256 productionDuringSnapshot = gooProductionSnapshots[msg.sender][i]; bool soldAllProduction = gooProductionZeroedSnapshots[msg.sender][i]; if (productionDuringSnapshot == 0 && !soldAllProduction) { productionDuringSnapshot = previousProduction; } else { previousProduction = productionDuringSnapshot; } researchShare += (allocatedGooResearchSnapshots[i] * productionDuringSnapshot) / totalGooProductionSnapshots[i]; } if (gooProductionSnapshots[msg.sender][endSnapShot] == 0 && !gooProductionZeroedSnapshots[msg.sender][i] && previousProduction > 0) { gooProductionSnapshots[msg.sender][endSnapShot] = previousProduction; // Checkpoint for next claim } lastGooResearchFundClaim[msg.sender] = endSnapShot + 1; uint256 referalDivs; if (referer != address(0) && referer != msg.sender) { referalDivs = researchShare / 100; // 1% ethBalance[referer] += referalDivs; } ethBalance[msg.sender] += researchShare - referalDivs; } // Allocate divs for the day (cron job) function snapshotDailyGooResearchFunding() external { require(msg.sender == owner); //require(block.timestamp >= (nextSnapshotTime - 30 minutes)); // Small bit of leeway for cron / network uint256 todaysEtherResearchFund = (totalEtherGooResearchPool / 10); // 10% of pool daily totalEtherGooResearchPool -= todaysEtherResearchFund; totalGooProductionSnapshots.push(totalGooProduction); allocatedGooResearchSnapshots.push(todaysEtherResearchFund); nextSnapshotTime = block.timestamp + 24 hours; } // Raffle for rare items function buyRaffleTicket(uint256 amount) external { require(raffleEndTime >= block.timestamp); require(amount > 0); uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_GOO_PRICE, amount); require(balanceOf(msg.sender) >= ticketsCost); // Update players goo updatePlayersGooFromPurchase(msg.sender, ticketsCost); // Handle new tickets TicketPurchases storage purchases = ticketsBoughtByPlayer[msg.sender]; // If we need to reset tickets from a previous raffle if (purchases.raffleRareId != raffleRareId) { purchases.numPurchases = 0; purchases.raffleRareId = raffleRareId; rafflePlayers[raffleRareId].push(msg.sender); // Add user to raffle } // Store new ticket purchase if (purchases.numPurchases == purchases.ticketsBought.length) { purchases.ticketsBought.length += 1; } purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(raffleTicketsBought, raffleTicketsBought + (amount - 1)); // (eg: buy 10, get id's 0-9) // Finally update ticket total raffleTicketsBought += amount; } function startRareRaffle(uint256 endTime, uint256 rareId) external { require(msg.sender == owner); require(schema.validRareId(rareId)); require(rareItemOwner[rareId] == 0); // Reset previous raffle info raffleWinningTicketSelected = false; raffleTicketThatWon = 0; raffleWinner = 0; raffleTicketsBought = 0; // Set current raffle info raffleEndTime = endTime; raffleRareId = rareId; } function awardRafflePrize(address checkWinner, uint256 checkIndex) external { require(raffleEndTime < block.timestamp); require(raffleWinner == 0); require(rareItemOwner[raffleRareId] == 0); if (!raffleWinningTicketSelected) { drawRandomWinner(); // Ideally do it in one call (gas limit cautious) } // Reduce gas by (optionally) offering an address to _check_ for winner if (checkWinner != 0) { TicketPurchases storage tickets = ticketsBoughtByPlayer[checkWinner]; if (tickets.numPurchases > 0 && checkIndex < tickets.numPurchases && tickets.raffleRareId == raffleRareId) { TicketPurchase storage checkTicket = tickets.ticketsBought[checkIndex]; if (raffleTicketThatWon >= checkTicket.startId && raffleTicketThatWon <= checkTicket.endId) { assignRafflePrize(checkWinner); // WINNER! return; } } } // Otherwise just naively try to find the winner (will work until mass amounts of players) for (uint256 i = 0; i < rafflePlayers[raffleRareId].length; i++) { address player = rafflePlayers[raffleRareId][i]; TicketPurchases storage playersTickets = ticketsBoughtByPlayer[player]; uint256 endIndex = playersTickets.numPurchases - 1; // Minor optimization to avoid checking every single player if (raffleTicketThatWon >= playersTickets.ticketsBought[0].startId && raffleTicketThatWon <= playersTickets.ticketsBought[endIndex].endId) { for (uint256 j = 0; j < playersTickets.numPurchases; j++) { TicketPurchase storage playerTicket = playersTickets.ticketsBought[j]; if (raffleTicketThatWon >= playerTicket.startId && raffleTicketThatWon <= playerTicket.endId) { assignRafflePrize(player); // WINNER! return; } } } } } function assignRafflePrize(address winner) internal { raffleWinner = winner; rareItemOwner[raffleRareId] = winner; rareItemPrice[raffleRareId] = (schema.rareStartPrice(raffleRareId) * 21) / 20; // Buy price slightly higher (Div pool cut) updatePlayersGoo(winner); uint256 upgradeClass; uint256 unitId; uint256 upgradeValue; (upgradeClass, unitId, upgradeValue) = schema.getRareInfo(raffleRareId); upgradeUnitMultipliers(winner, upgradeClass, unitId, upgradeValue); } // Random enough for small contests (Owner only to prevent trial & error execution) function drawRandomWinner() public { require(msg.sender == owner); require(raffleEndTime < block.timestamp); require(!raffleWinningTicketSelected); uint256 seed = raffleTicketsBought + block.timestamp; raffleTicketThatWon = addmod(uint256(block.blockhash(block.number-1)), seed, raffleTicketsBought); raffleWinningTicketSelected = true; } function protectAddress(address exchange, bool isProtected) external { require(msg.sender == owner); require(getGooProduction(exchange) == 0); // Can't protect actual players protectedAddresses[exchange] = isProtected; } function attackPlayer(address target) external { require(battleCooldown[msg.sender] < block.timestamp); require(target != msg.sender); require(!protectedAddresses[target]); //target not whitelisted (i.e. exchange wallets) uint256 attackingPower; uint256 defendingPower; uint256 stealingPower; (attackingPower, defendingPower, stealingPower) = getPlayersBattlePower(msg.sender, target); if (battleCooldown[target] > block.timestamp) { // When on battle cooldown you're vulnerable (starting value is 50% normal power) defendingPower = schema.getWeakenedDefensePower(defendingPower); } if (attackingPower > defendingPower) { battleCooldown[msg.sender] = block.timestamp + 30 minutes; if (balanceOf(target) > stealingPower) { // Save all their unclaimed goo, then steal attacker's max capacity (at same time) uint256 unclaimedGoo = balanceOfUnclaimedGoo(target); if (stealingPower > unclaimedGoo) { uint256 gooDecrease = stealingPower - unclaimedGoo; gooBalance[target] -= gooDecrease; } else { uint256 gooGain = unclaimedGoo - stealingPower; gooBalance[target] += gooGain; } gooBalance[msg.sender] += stealingPower; emit PlayerAttacked(msg.sender, target, true, stealingPower); } else { emit PlayerAttacked(msg.sender, target, true, balanceOf(target)); gooBalance[msg.sender] += balanceOf(target); gooBalance[target] = 0; } lastGooSaveTime[target] = block.timestamp; // We don't need to claim/save msg.sender's goo (as production delta is unchanged) } else { battleCooldown[msg.sender] = block.timestamp + 10 minutes; emit PlayerAttacked(msg.sender, target, false, 0); } } function getPlayersBattlePower(address attacker, address defender) internal constant returns (uint256, uint256, uint256) { uint256 startId; uint256 endId; (startId, endId) = schema.battleUnitIdRange(); uint256 attackingPower; uint256 defendingPower; uint256 stealingPower; // Not ideal but will only be a small number of units (and saves gas when buying units) while (startId <= endId) { attackingPower += getUnitsAttack(attacker, startId, unitsOwned[attacker][startId]); stealingPower += getUnitsStealingCapacity(attacker, startId, unitsOwned[attacker][startId]); defendingPower += getUnitsDefense(defender, startId, unitsOwned[defender][startId]); startId++; } return (attackingPower, defendingPower, stealingPower); } function getPlayersBattleStats(address player) external constant returns (uint256, uint256, uint256) { uint256 startId; uint256 endId; (startId, endId) = schema.battleUnitIdRange(); uint256 attackingPower; uint256 defendingPower; uint256 stealingPower; // Not ideal but will only be a small number of units (and saves gas when buying units) while (startId <= endId) { attackingPower += getUnitsAttack(player, startId, unitsOwned[player][startId]); stealingPower += getUnitsStealingCapacity(player, startId, unitsOwned[player][startId]); defendingPower += getUnitsDefense(player, startId, unitsOwned[player][startId]); startId++; } return (attackingPower, defendingPower, stealingPower); } function getUnitsProduction(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) { return (amount * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId]) * (10 + unitGooProductionMultiplier[player][unitId])) / 10; } function getUnitsAttack(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) { return (amount * (schema.unitAttack(unitId) + unitAttackIncreases[player][unitId]) * (10 + unitAttackMultiplier[player][unitId])) / 10; } function getUnitsDefense(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) { return (amount * (schema.unitDefense(unitId) + unitDefenseIncreases[player][unitId]) * (10 + unitDefenseMultiplier[player][unitId])) / 10; } function getUnitsStealingCapacity(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) { return (amount * (schema.unitStealingCapacity(unitId) + unitGooStealingIncreases[player][unitId]) * (10 + unitGooStealingMultiplier[player][unitId])) / 10; } // To display on website function getGameInfo() external constant returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256[], bool[]){ uint256[] memory units = new uint256[](schema.currentNumberOfUnits()); bool[] memory upgrades = new bool[](schema.currentNumberOfUpgrades()); uint256 startId; uint256 endId; (startId, endId) = schema.productionUnitIdRange(); uint256 i; while (startId <= endId) { units[i] = unitsOwned[msg.sender][startId]; i++; startId++; } (startId, endId) = schema.battleUnitIdRange(); while (startId <= endId) { units[i] = unitsOwned[msg.sender][startId]; i++; startId++; } // Reset for upgrades i = 0; (startId, endId) = schema.upgradeIdRange(); while (startId <= endId) { upgrades[i] = upgradesOwned[msg.sender][startId]; i++; startId++; } return (block.timestamp, totalEtherGooResearchPool, totalGooProduction, nextSnapshotTime, balanceOf(msg.sender), ethBalance[msg.sender], getGooProduction(msg.sender), units, upgrades); } // To display on website function getRareItemInfo() external constant returns (address[], uint256[]) { address[] memory itemOwners = new address[](schema.currentNumberOfRares()); uint256[] memory itemPrices = new uint256[](schema.currentNumberOfRares()); uint256 startId; uint256 endId; (startId, endId) = schema.rareIdRange(); uint256 i; while (startId <= endId) { itemOwners[i] = rareItemOwner[startId]; itemPrices[i] = rareItemPrice[startId]; i++; startId++; } return (itemOwners, itemPrices); } // To display on website function viewUnclaimedResearchDividends() external constant returns (uint256, uint256, uint256) { uint256 startSnapshot = lastGooResearchFundClaim[msg.sender]; uint256 latestSnapshot = allocatedGooResearchSnapshots.length - 1; // No snapshots to begin with uint256 researchShare; uint256 previousProduction = gooProductionSnapshots[msg.sender][lastGooResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xfffffffffffff] = 0; for (uint256 i = startSnapshot; i <= latestSnapshot; i++) { // Slightly complex things by accounting for days/snapshots when user made no tx's uint256 productionDuringSnapshot = gooProductionSnapshots[msg.sender][i]; bool soldAllProduction = gooProductionZeroedSnapshots[msg.sender][i]; if (productionDuringSnapshot == 0 && !soldAllProduction) { productionDuringSnapshot = previousProduction; } else { previousProduction = productionDuringSnapshot; } researchShare += (allocatedGooResearchSnapshots[i] * productionDuringSnapshot) / totalGooProductionSnapshots[i]; } return (researchShare, startSnapshot, latestSnapshot); } // To allow clients to verify contestants function getRafflePlayers(uint256 raffleId) external constant returns (address[]) { return (rafflePlayers[raffleId]); } // To allow clients to verify contestants function getPlayersTickets(address player) external constant returns (uint256[], uint256[]) { TicketPurchases storage playersTickets = ticketsBoughtByPlayer[player]; if (playersTickets.raffleRareId == raffleRareId) { uint256[] memory startIds = new uint256[](playersTickets.numPurchases); uint256[] memory endIds = new uint256[](playersTickets.numPurchases); for (uint256 i = 0; i < playersTickets.numPurchases; i++) { startIds[i] = playersTickets.ticketsBought[i].startId; endIds[i] = playersTickets.ticketsBought[i].endId; } } return (startIds, endIds); } // To display on website function getLatestRaffleInfo() external constant returns (uint256, uint256, uint256, address, uint256) { return (raffleEndTime, raffleRareId, raffleTicketsBought, raffleWinner, raffleTicketThatWon); } // New units may be added in future, but check it matches existing schema so no-one can abuse selling. function updateGooConfig(address newSchemaAddress) external { require(msg.sender == owner); GooGameConfig newSchema = GooGameConfig(newSchemaAddress); requireExistingUnitsSame(newSchema); requireExistingUpgradesSame(newSchema); // Finally update config schema = GooGameConfig(newSchema); } function requireExistingUnitsSame(GooGameConfig newSchema) internal constant { // Requires units eth costs match up or fail execution uint256 startId; uint256 endId; (startId, endId) = schema.productionUnitIdRange(); while (startId <= endId) { require(schema.unitEthCost(startId) == newSchema.unitEthCost(startId)); require(schema.unitGooProduction(startId) == newSchema.unitGooProduction(startId)); startId++; } (startId, endId) = schema.battleUnitIdRange(); while (startId <= endId) { require(schema.unitEthCost(startId) == newSchema.unitEthCost(startId)); require(schema.unitAttack(startId) == newSchema.unitAttack(startId)); require(schema.unitDefense(startId) == newSchema.unitDefense(startId)); require(schema.unitStealingCapacity(startId) == newSchema.unitStealingCapacity(startId)); startId++; } } function requireExistingUpgradesSame(GooGameConfig newSchema) internal constant { uint256 startId; uint256 endId; uint256 oldClass; uint256 oldUnitId; uint256 oldValue; uint256 newClass; uint256 newUnitId; uint256 newValue; // Requires ALL upgrade stats match up or fail execution (startId, endId) = schema.rareIdRange(); while (startId <= endId) { uint256 oldGooCost; uint256 oldEthCost; (oldGooCost, oldEthCost, oldClass, oldUnitId, oldValue) = schema.getUpgradeInfo(startId); uint256 newGooCost; uint256 newEthCost; (newGooCost, newEthCost, newClass, newUnitId, newValue) = newSchema.getUpgradeInfo(startId); require(oldGooCost == newGooCost); require(oldEthCost == oldEthCost); require(oldClass == oldClass); require(oldUnitId == newUnitId); require(oldValue == newValue); startId++; } // Requires ALL rare stats match up or fail execution (startId, endId) = schema.rareIdRange(); while (startId <= endId) { (oldClass, oldUnitId, oldValue) = schema.getRareInfo(startId); (newClass, newUnitId, newValue) = newSchema.getRareInfo(startId); require(oldClass == newClass); require(oldUnitId == newUnitId); require(oldValue == newValue); startId++; } } } contract GooGameConfig { mapping(uint256 => Unit) private unitInfo; mapping(uint256 => Upgrade) private upgradeInfo; mapping(uint256 => Rare) private rareInfo; uint256 public constant currentNumberOfUnits = 14; uint256 public constant currentNumberOfUpgrades = 42; uint256 public constant currentNumberOfRares = 2; struct Unit { uint256 unitId; uint256 baseGooCost; uint256 gooCostIncreaseHalf; // Halfed to make maths slightly less (cancels a 2 out) uint256 ethCost; uint256 baseGooProduction; uint256 attackValue; uint256 defenseValue; uint256 gooStealingCapacity; } struct Upgrade { uint256 upgradeId; uint256 gooCost; uint256 ethCost; uint256 upgradeClass; uint256 unitId; uint256 upgradeValue; } struct Rare { uint256 rareId; uint256 ethCost; uint256 rareClass; uint256 unitId; uint256 rareValue; } // Constructor function GooGameConfig() public { unitInfo[1] = Unit(1, 0, 10, 0, 1, 0, 0, 0); unitInfo[2] = Unit(2, 100, 50, 0, 2, 0, 0, 0); unitInfo[3] = Unit(3, 0, 0, 0.01 ether, 12, 0, 0, 0); unitInfo[4] = Unit(4, 500, 250, 0, 4, 0, 0, 0); unitInfo[5] = Unit(5, 2500, 1250, 0, 6, 0, 0, 0); unitInfo[6] = Unit(6, 10000, 5000, 0, 8, 0, 0, 0); unitInfo[7] = Unit(7, 0, 1000, 0.05 ether, 60, 0, 0, 0); unitInfo[8] = Unit(8, 25000, 12500, 0, 10, 0, 0, 0); unitInfo[40] = Unit(40, 100, 50, 0, 0, 10, 10, 20); unitInfo[41] = Unit(41, 250, 125, 0, 0, 1, 25, 1); unitInfo[42] = Unit(42, 0, 50, 0.01 ether, 0, 100, 10, 5); unitInfo[43] = Unit(43, 1000, 500, 0, 0, 25, 1, 50); unitInfo[44] = Unit(44, 2500, 1250, 0, 0, 20, 40, 100); unitInfo[45] = Unit(45, 0, 500, 0.02 ether, 0, 0, 0, 1000); upgradeInfo[1] = Upgrade(1, 500, 0, 0, 1, 1); // +1 upgradeInfo[2] = Upgrade(2, 0, 0.1 ether, 1, 1, 10); // 10 = +100% upgradeInfo[3] = Upgrade(3, 10000, 0, 1, 1, 5); // 5 = +50% upgradeInfo[4] = Upgrade(4, 0, 0.1 ether, 0, 2, 2); // +1 upgradeInfo[5] = Upgrade(5, 2000, 0, 1, 2, 5); // 10 = +50% upgradeInfo[6] = Upgrade(6, 0, 0.2 ether, 0, 2, 2); // +2 upgradeInfo[7] = Upgrade(7, 2500, 0, 0, 3, 2); // +2 upgradeInfo[8] = Upgrade(8, 0, 0.5 ether, 1, 3, 10); // 10 = +100% upgradeInfo[9] = Upgrade(9, 25000, 0, 1, 3, 5); // 5 = +50% upgradeInfo[10] = Upgrade(10, 0, 0.1 ether, 0, 4, 1); // +1 upgradeInfo[11] = Upgrade(11, 5000, 0, 1, 4, 5); // 10 = +50% upgradeInfo[12] = Upgrade(12, 0, 0.2 ether, 0, 4, 2); // +2 upgradeInfo[13] = Upgrade(13, 10000, 0, 0, 5, 2); // +2 upgradeInfo[14] = Upgrade(14, 0, 0.5 ether, 1, 5, 10); // 10 = +100% upgradeInfo[15] = Upgrade(15, 25000, 0, 1, 5, 5); // 5 = +50% upgradeInfo[16] = Upgrade(16, 0, 0.1 ether, 0, 6, 1); // +1 upgradeInfo[17] = Upgrade(17, 25000, 0, 1, 6, 5); // 10 = +50% upgradeInfo[18] = Upgrade(18, 0, 0.2 ether, 0, 6, 2); // +2 upgradeInfo[19] = Upgrade(13, 50000, 0, 0, 7, 2); // +2 upgradeInfo[20] = Upgrade(20, 0, 0.2 ether, 1, 7, 5); // 5 = +50% upgradeInfo[21] = Upgrade(21, 100000, 0, 1, 7, 5); // 5 = +50% upgradeInfo[22] = Upgrade(22, 0, 0.1 ether, 0, 8, 2); // +1 upgradeInfo[23] = Upgrade(23, 25000, 0, 1, 8, 5); // 10 = +50% upgradeInfo[24] = Upgrade(24, 0, 0.2 ether, 0, 8, 4); // +2 upgradeInfo[25] = Upgrade(25, 500, 0, 2, 40, 10); // +10 upgradeInfo[26] = Upgrade(26, 0, 0.1 ether, 4, 40, 10); // +10 upgradeInfo[27] = Upgrade(27, 10000, 0, 6, 40, 10); // +10 upgradeInfo[28] = Upgrade(28, 0, 0.2 ether, 3, 41, 5); // +50 % upgradeInfo[29] = Upgrade(29, 5000, 0, 4, 41, 10); // +10 upgradeInfo[30] = Upgrade(30, 0, 0.5 ether, 6, 41, 4); // +4 upgradeInfo[31] = Upgrade(31, 2500, 0, 5, 42, 5); // +50 % upgradeInfo[32] = Upgrade(32, 0, 0.2 ether, 6, 42, 10); // +10 upgradeInfo[33] = Upgrade(33, 20000, 0, 7, 42, 5); // +50 % upgradeInfo[34] = Upgrade(34, 0, 0.1 ether, 2, 43, 5); // +5 upgradeInfo[35] = Upgrade(35, 10000, 0, 4, 43, 5); // +5 upgradeInfo[36] = Upgrade(36, 0, 0.2 ether, 5, 43, 5); // +50% upgradeInfo[37] = Upgrade(37, 0, 0.1 ether, 2, 44, 15); // +15 upgradeInfo[38] = Upgrade(38, 25000, 0, 3, 44, 5); // +50% upgradeInfo[39] = Upgrade(39, 0, 0.2 ether, 4, 44, 15); // +15 upgradeInfo[40] = Upgrade(40, 50000, 0, 6, 45, 500); // +500 upgradeInfo[41] = Upgrade(41, 0, 0.5 ether, 7, 45, 10); // +100 % upgradeInfo[42] = Upgrade(42, 250000, 0, 7, 45, 5); // +50 % rareInfo[1] = Rare(1, 0.5 ether, 1, 1, 30); // 30 = +300% rareInfo[2] = Rare(2, 0.5 ether, 0, 2, 4); // +4 } function getGooCostForUnit(uint256 unitId, uint256 existing, uint256 amount) public constant returns (uint256) { if (amount == 1) { // 1 if (existing == 0) { return unitInfo[unitId].baseGooCost; } else { return unitInfo[unitId].baseGooCost + (existing * unitInfo[unitId].gooCostIncreaseHalf * 2); } } else if (amount > 1) { uint256 existingCost; if (existing > 0) { existingCost = (unitInfo[unitId].baseGooCost * existing) + (existing * (existing - 1) * unitInfo[unitId].gooCostIncreaseHalf); } existing += amount; uint256 newCost = SafeMath.add(SafeMath.mul(unitInfo[unitId].baseGooCost, existing), SafeMath.mul(SafeMath.mul(existing, (existing - 1)), unitInfo[unitId].gooCostIncreaseHalf)); return newCost - existingCost; } } function getWeakenedDefensePower(uint256 defendingPower) external constant returns (uint256) { return defendingPower / 2; } function validUnitId(uint256 unitId) external constant returns (bool) { return ((unitId > 0 && unitId < 9) || (unitId > 39 && unitId < 46)); } function validUpgradeId(uint256 upgradeId) external constant returns (bool) { return (upgradeId > 0 && upgradeId < 43); } function validRareId(uint256 rareId) external constant returns (bool) { return (rareId > 0 && rareId < 3); } function unitEthCost(uint256 unitId) external constant returns (uint256) { return unitInfo[unitId].ethCost; } function unitGooProduction(uint256 unitId) external constant returns (uint256) { return unitInfo[unitId].baseGooProduction; } function unitAttack(uint256 unitId) external constant returns (uint256) { return unitInfo[unitId].attackValue; } function unitDefense(uint256 unitId) external constant returns (uint256) { return unitInfo[unitId].defenseValue; } function unitStealingCapacity(uint256 unitId) external constant returns (uint256) { return unitInfo[unitId].gooStealingCapacity; } function rareStartPrice(uint256 rareId) external constant returns (uint256) { return rareInfo[rareId].ethCost; } function productionUnitIdRange() external constant returns (uint256, uint256) { return (1, 8); } function battleUnitIdRange() external constant returns (uint256, uint256) { return (40, 45); } function upgradeIdRange() external constant returns (uint256, uint256) { return (1, 42); } function rareIdRange() external constant returns (uint256, uint256) { return (1, 2); } function getUpgradeInfo(uint256 upgradeId) external constant returns (uint256, uint256, uint256, uint256, uint256) { return (upgradeInfo[upgradeId].gooCost, upgradeInfo[upgradeId].ethCost, upgradeInfo[upgradeId].upgradeClass, upgradeInfo[upgradeId].unitId, upgradeInfo[upgradeId].upgradeValue); } function getRareInfo(uint256 rareId) external constant returns (uint256, uint256, uint256) { return (rareInfo[rareId].rareClass, rareInfo[rareId].unitId, rareInfo[rareId].rareValue); } } 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, 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) { uint256 c = a + b; assert(c >= a); return c; } }
Raffle for rare items Update players goo Handle new tickets If we need to reset tickets from a previous raffle
function buyRaffleTicket(uint256 amount) external { require(raffleEndTime >= block.timestamp); require(amount > 0); uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_GOO_PRICE, amount); require(balanceOf(msg.sender) >= ticketsCost); updatePlayersGooFromPurchase(msg.sender, ticketsCost); TicketPurchases storage purchases = ticketsBoughtByPlayer[msg.sender]; if (purchases.raffleRareId != raffleRareId) { purchases.numPurchases = 0; purchases.raffleRareId = raffleRareId; } if (purchases.numPurchases == purchases.ticketsBought.length) { purchases.ticketsBought.length += 1; } raffleTicketsBought += amount; }
9,845,528
[ 1, 54, 7329, 298, 364, 25671, 1516, 2315, 18115, 1960, 83, 5004, 394, 24475, 971, 732, 1608, 358, 2715, 24475, 628, 279, 2416, 767, 1403, 298, 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, 30143, 54, 7329, 298, 13614, 12, 11890, 5034, 3844, 13, 3903, 288, 203, 3639, 2583, 12, 354, 1403, 298, 25255, 1545, 1203, 18, 5508, 1769, 203, 3639, 2583, 12, 8949, 405, 374, 1769, 203, 540, 203, 3639, 2254, 5034, 24475, 8018, 273, 14060, 10477, 18, 16411, 12, 2849, 2246, 900, 67, 56, 16656, 1584, 67, 8369, 67, 16387, 51, 67, 7698, 1441, 16, 3844, 1769, 203, 3639, 2583, 12, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 24475, 8018, 1769, 203, 540, 203, 3639, 1089, 1749, 3907, 43, 5161, 1265, 23164, 12, 3576, 18, 15330, 16, 24475, 8018, 1769, 203, 540, 203, 3639, 22023, 10262, 343, 3304, 2502, 5405, 343, 3304, 273, 24475, 13809, 9540, 858, 12148, 63, 3576, 18, 15330, 15533, 203, 540, 203, 3639, 309, 261, 12688, 343, 3304, 18, 354, 1403, 298, 54, 834, 548, 480, 767, 1403, 298, 54, 834, 548, 13, 288, 203, 5411, 5405, 343, 3304, 18, 2107, 10262, 343, 3304, 273, 374, 31, 203, 5411, 5405, 343, 3304, 18, 354, 1403, 298, 54, 834, 548, 273, 767, 1403, 298, 54, 834, 548, 31, 203, 3639, 289, 203, 540, 203, 3639, 309, 261, 12688, 343, 3304, 18, 2107, 10262, 343, 3304, 422, 5405, 343, 3304, 18, 6470, 2413, 13809, 9540, 18, 2469, 13, 288, 203, 5411, 5405, 343, 3304, 18, 6470, 2413, 13809, 9540, 18, 2469, 1011, 404, 31, 203, 3639, 289, 203, 540, 203, 3639, 767, 1403, 298, 6264, 2413, 13809, 9540, 1011, 3844, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xB64686d1aF5544950D73b1ebdb3426ea498BA7dB/sources/project_/contracts/RoyaltyNFT.sol
mapping(uint256 => string) private SkillIdentifier;
contract RoyaltyNFT is ERC721Enumerable, Ownable { using Strings for uint256; bool public paused = false; uint256 public total_volume = 0; mapping(address => uint256) private royaltysBalance; mapping(address => bool) private registered; constructor( ) pragma solidity >= 0.7.0 < 0.9.0; }
1,933,394
[ 1, 6770, 12, 11890, 5034, 516, 533, 13, 3238, 15821, 3004, 31, 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, 16351, 534, 13372, 15006, 50, 4464, 353, 4232, 39, 27, 5340, 3572, 25121, 16, 14223, 6914, 288, 203, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 225, 1426, 1071, 17781, 273, 629, 31, 203, 203, 225, 2254, 5034, 1071, 2078, 67, 9491, 273, 374, 31, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 721, 93, 2390, 1900, 13937, 31, 203, 203, 225, 2874, 12, 2867, 516, 1426, 13, 3238, 4104, 31, 203, 203, 203, 203, 225, 3885, 12, 21281, 225, 262, 225, 203, 683, 9454, 18035, 560, 1545, 374, 18, 27, 18, 20, 411, 374, 18, 29, 18, 20, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import './IYuanYangPot.sol'; contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
Passthrough function to add pool.
function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); }
911,612
[ 1, 52, 345, 24283, 445, 358, 527, 2845, 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, 202, 915, 527, 2864, 12, 203, 202, 202, 11890, 5034, 389, 9853, 2148, 16, 203, 202, 202, 45, 654, 39, 3462, 389, 9953, 1345, 16, 203, 202, 202, 6430, 389, 291, 3715, 16, 203, 202, 202, 6430, 389, 1918, 1891, 203, 202, 13, 1071, 1338, 43, 1527, 288, 203, 202, 202, 7525, 18411, 18, 1289, 2864, 24899, 9853, 2148, 16, 389, 9953, 1345, 16, 389, 291, 3715, 16, 389, 1918, 1891, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x9D4C63565D5618310271bF3F3c01b2954C1D1639/sources/src/GitcoinGovernor.sol
@dev We override this function to resolve ambiguity between inherited contracts.
function _execute( uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal virtual override(Governor, GovernorTimelockCompound) { return GovernorTimelockCompound._execute(proposalId, targets, values, calldatas, descriptionHash); }
15,763,225
[ 1, 3218, 3849, 333, 445, 358, 2245, 13232, 8810, 560, 3086, 12078, 20092, 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, 225, 445, 389, 8837, 12, 203, 565, 2254, 5034, 14708, 548, 16, 203, 565, 1758, 8526, 3778, 5774, 16, 203, 565, 2254, 5034, 8526, 3778, 924, 16, 203, 565, 1731, 8526, 3778, 745, 13178, 16, 203, 565, 1731, 1578, 2477, 2310, 203, 225, 262, 2713, 5024, 3849, 12, 43, 1643, 29561, 16, 611, 1643, 29561, 10178, 292, 975, 16835, 13, 288, 203, 565, 327, 203, 1377, 611, 1643, 29561, 10178, 292, 975, 16835, 6315, 8837, 12, 685, 8016, 548, 16, 5774, 16, 924, 16, 745, 13178, 16, 2477, 2310, 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 ]
./full_match/5/0x72C189Df5676A72975489C63fecF6d2B45b6359d/sources/contracts/CreamPaiToken.sol
Taxes Max tx/wallet amounts Whitelisting Uniswap controls
contract CreamPaiToken is ERC20Base { string private _name = "CreamPAI"; string private _symbol = "PAI"; uint8 private _decimals = 18; uint256 private _supply = 69000000000; address public marketingWallet = 0x6Fe13903740d78296D70252f8498d4B82f1fA671; address public DEAD = 0x000000000000000000000000000000000000dEaD; uint256 public taxForLiquidity = 47; uint256 public sellTaxForMarketing = 47; uint256 public buyTaxForMarketing = 47; uint256 public numTokensSellToAddToLiquidity = 1380000 * 10 ** _decimals; uint256 public numTokensSellToAddToETH = 690000 * 10 ** _decimals; uint256 public _marketingReserves; uint256 public maxTxAmount = 690000000 * 10 ** _decimals; uint256 public maxWalletAmount = 690000000 * 10 ** _decimals; event MarketingWalletUpdated(address _address); event MaxWalletAmountUpdated(uint256 _amount); event MaxTransactionAmountUpdated(uint256 _amount); event TaxUpdated( uint256 _taxForLiquidity, uint256 _buyTaxForMarketing, uint256 _sellTaxForMarketing ); mapping(address => bool) public _isExcludedFromFee; event ExcludedFromFeeUpdated(address _address, bool _status); IUniswapV2Router02 public immutable uniswapV2Router; address public uniswapV2Pair; bool public publicTradingActive; event PairUpdated(address _address); event PublicTradingStarted(); event SwapThresholdUpdated( uint256 _numTokensSellToAddToLiquidity, uint256 _numTokensSellToAddToETH ); bool private inSwapAndLiquify; event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() payable ERC20Base(_name, _symbol) { _mint(msg.sender, (_supply * 10 ** _decimals)); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[address(uniswapV2Router)] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[msg.sender] = true; _isExcludedFromFee[marketingWallet] = true; } function updatePair(address _pair) external onlyOwner { require(_pair != DEAD, "LP Pair cannot be DEAD"); require(_pair != address(0), "LP Pair cannot be 0!"); uniswapV2Pair = _pair; emit PairUpdated(_pair); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "Cannot transfer to 0"); require(to != address(0), "Cannot transfer from 0"); require(balanceOf(from) >= amount, "Amount exceeds balance"); if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { super._transfer(from, to, amount); return; } require(publicTradingActive, "Trading not active"); (from == uniswapV2Pair || to == uniswapV2Pair) && !inSwapAndLiquify ) { if (from != uniswapV2Pair) { uint256 contractLiquidityBalance = balanceOf(address(this)) - _marketingReserves; if (contractLiquidityBalance >= numTokensSellToAddToLiquidity) { _swapAndLiquify(numTokensSellToAddToLiquidity); } if ((_marketingReserves) >= numTokensSellToAddToETH) { _swapTokensForEth(numTokensSellToAddToETH); _marketingReserves -= numTokensSellToAddToETH; bool sent = payable(marketingWallet).send( address(this).balance ); require(sent, "Failed to send ETH"); } } require(amount <= maxTxAmount, "Max transaction amount exceeded"); if (from == uniswapV2Pair) { require( (amount + balanceOf(to)) <= maxWalletAmount, "Max wallet amount exceeded" ); } uint256 taxForMarketing = 0; if (from == uniswapV2Pair) { taxForMarketing = buyTaxForMarketing; } else if (to == uniswapV2Pair) { taxForMarketing = sellTaxForMarketing; } uint256 liquidityShare = ((amount * taxForLiquidity) / 100); uint256 transferAmount = amount - (marketingShare + liquidityShare); from, address(this), (marketingShare + liquidityShare) ); super._transfer(from, to, amount); } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "Cannot transfer to 0"); require(to != address(0), "Cannot transfer from 0"); require(balanceOf(from) >= amount, "Amount exceeds balance"); if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { super._transfer(from, to, amount); return; } require(publicTradingActive, "Trading not active"); (from == uniswapV2Pair || to == uniswapV2Pair) && !inSwapAndLiquify ) { if (from != uniswapV2Pair) { uint256 contractLiquidityBalance = balanceOf(address(this)) - _marketingReserves; if (contractLiquidityBalance >= numTokensSellToAddToLiquidity) { _swapAndLiquify(numTokensSellToAddToLiquidity); } if ((_marketingReserves) >= numTokensSellToAddToETH) { _swapTokensForEth(numTokensSellToAddToETH); _marketingReserves -= numTokensSellToAddToETH; bool sent = payable(marketingWallet).send( address(this).balance ); require(sent, "Failed to send ETH"); } } require(amount <= maxTxAmount, "Max transaction amount exceeded"); if (from == uniswapV2Pair) { require( (amount + balanceOf(to)) <= maxWalletAmount, "Max wallet amount exceeded" ); } uint256 taxForMarketing = 0; if (from == uniswapV2Pair) { taxForMarketing = buyTaxForMarketing; } else if (to == uniswapV2Pair) { taxForMarketing = sellTaxForMarketing; } uint256 liquidityShare = ((amount * taxForLiquidity) / 100); uint256 transferAmount = amount - (marketingShare + liquidityShare); from, address(this), (marketingShare + liquidityShare) ); super._transfer(from, to, amount); } } if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "Cannot transfer to 0"); require(to != address(0), "Cannot transfer from 0"); require(balanceOf(from) >= amount, "Amount exceeds balance"); if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { super._transfer(from, to, amount); return; } require(publicTradingActive, "Trading not active"); (from == uniswapV2Pair || to == uniswapV2Pair) && !inSwapAndLiquify ) { if (from != uniswapV2Pair) { uint256 contractLiquidityBalance = balanceOf(address(this)) - _marketingReserves; if (contractLiquidityBalance >= numTokensSellToAddToLiquidity) { _swapAndLiquify(numTokensSellToAddToLiquidity); } if ((_marketingReserves) >= numTokensSellToAddToETH) { _swapTokensForEth(numTokensSellToAddToETH); _marketingReserves -= numTokensSellToAddToETH; bool sent = payable(marketingWallet).send( address(this).balance ); require(sent, "Failed to send ETH"); } } require(amount <= maxTxAmount, "Max transaction amount exceeded"); if (from == uniswapV2Pair) { require( (amount + balanceOf(to)) <= maxWalletAmount, "Max wallet amount exceeded" ); } uint256 taxForMarketing = 0; if (from == uniswapV2Pair) { taxForMarketing = buyTaxForMarketing; } else if (to == uniswapV2Pair) { taxForMarketing = sellTaxForMarketing; } uint256 liquidityShare = ((amount * taxForLiquidity) / 100); uint256 transferAmount = amount - (marketingShare + liquidityShare); from, address(this), (marketingShare + liquidityShare) ); super._transfer(from, to, amount); } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "Cannot transfer to 0"); require(to != address(0), "Cannot transfer from 0"); require(balanceOf(from) >= amount, "Amount exceeds balance"); if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { super._transfer(from, to, amount); return; } require(publicTradingActive, "Trading not active"); (from == uniswapV2Pair || to == uniswapV2Pair) && !inSwapAndLiquify ) { if (from != uniswapV2Pair) { uint256 contractLiquidityBalance = balanceOf(address(this)) - _marketingReserves; if (contractLiquidityBalance >= numTokensSellToAddToLiquidity) { _swapAndLiquify(numTokensSellToAddToLiquidity); } if ((_marketingReserves) >= numTokensSellToAddToETH) { _swapTokensForEth(numTokensSellToAddToETH); _marketingReserves -= numTokensSellToAddToETH; bool sent = payable(marketingWallet).send( address(this).balance ); require(sent, "Failed to send ETH"); } } require(amount <= maxTxAmount, "Max transaction amount exceeded"); if (from == uniswapV2Pair) { require( (amount + balanceOf(to)) <= maxWalletAmount, "Max wallet amount exceeded" ); } uint256 taxForMarketing = 0; if (from == uniswapV2Pair) { taxForMarketing = buyTaxForMarketing; } else if (to == uniswapV2Pair) { taxForMarketing = sellTaxForMarketing; } uint256 liquidityShare = ((amount * taxForLiquidity) / 100); uint256 transferAmount = amount - (marketingShare + liquidityShare); from, address(this), (marketingShare + liquidityShare) ); super._transfer(from, to, amount); } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "Cannot transfer to 0"); require(to != address(0), "Cannot transfer from 0"); require(balanceOf(from) >= amount, "Amount exceeds balance"); if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { super._transfer(from, to, amount); return; } require(publicTradingActive, "Trading not active"); (from == uniswapV2Pair || to == uniswapV2Pair) && !inSwapAndLiquify ) { if (from != uniswapV2Pair) { uint256 contractLiquidityBalance = balanceOf(address(this)) - _marketingReserves; if (contractLiquidityBalance >= numTokensSellToAddToLiquidity) { _swapAndLiquify(numTokensSellToAddToLiquidity); } if ((_marketingReserves) >= numTokensSellToAddToETH) { _swapTokensForEth(numTokensSellToAddToETH); _marketingReserves -= numTokensSellToAddToETH; bool sent = payable(marketingWallet).send( address(this).balance ); require(sent, "Failed to send ETH"); } } require(amount <= maxTxAmount, "Max transaction amount exceeded"); if (from == uniswapV2Pair) { require( (amount + balanceOf(to)) <= maxWalletAmount, "Max wallet amount exceeded" ); } uint256 taxForMarketing = 0; if (from == uniswapV2Pair) { taxForMarketing = buyTaxForMarketing; } else if (to == uniswapV2Pair) { taxForMarketing = sellTaxForMarketing; } uint256 liquidityShare = ((amount * taxForLiquidity) / 100); uint256 transferAmount = amount - (marketingShare + liquidityShare); from, address(this), (marketingShare + liquidityShare) ); super._transfer(from, to, amount); } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "Cannot transfer to 0"); require(to != address(0), "Cannot transfer from 0"); require(balanceOf(from) >= amount, "Amount exceeds balance"); if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { super._transfer(from, to, amount); return; } require(publicTradingActive, "Trading not active"); (from == uniswapV2Pair || to == uniswapV2Pair) && !inSwapAndLiquify ) { if (from != uniswapV2Pair) { uint256 contractLiquidityBalance = balanceOf(address(this)) - _marketingReserves; if (contractLiquidityBalance >= numTokensSellToAddToLiquidity) { _swapAndLiquify(numTokensSellToAddToLiquidity); } if ((_marketingReserves) >= numTokensSellToAddToETH) { _swapTokensForEth(numTokensSellToAddToETH); _marketingReserves -= numTokensSellToAddToETH; bool sent = payable(marketingWallet).send( address(this).balance ); require(sent, "Failed to send ETH"); } } require(amount <= maxTxAmount, "Max transaction amount exceeded"); if (from == uniswapV2Pair) { require( (amount + balanceOf(to)) <= maxWalletAmount, "Max wallet amount exceeded" ); } uint256 taxForMarketing = 0; if (from == uniswapV2Pair) { taxForMarketing = buyTaxForMarketing; } else if (to == uniswapV2Pair) { taxForMarketing = sellTaxForMarketing; } uint256 liquidityShare = ((amount * taxForLiquidity) / 100); uint256 transferAmount = amount - (marketingShare + liquidityShare); from, address(this), (marketingShare + liquidityShare) ); super._transfer(from, to, amount); } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "Cannot transfer to 0"); require(to != address(0), "Cannot transfer from 0"); require(balanceOf(from) >= amount, "Amount exceeds balance"); if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { super._transfer(from, to, amount); return; } require(publicTradingActive, "Trading not active"); (from == uniswapV2Pair || to == uniswapV2Pair) && !inSwapAndLiquify ) { if (from != uniswapV2Pair) { uint256 contractLiquidityBalance = balanceOf(address(this)) - _marketingReserves; if (contractLiquidityBalance >= numTokensSellToAddToLiquidity) { _swapAndLiquify(numTokensSellToAddToLiquidity); } if ((_marketingReserves) >= numTokensSellToAddToETH) { _swapTokensForEth(numTokensSellToAddToETH); _marketingReserves -= numTokensSellToAddToETH; bool sent = payable(marketingWallet).send( address(this).balance ); require(sent, "Failed to send ETH"); } } require(amount <= maxTxAmount, "Max transaction amount exceeded"); if (from == uniswapV2Pair) { require( (amount + balanceOf(to)) <= maxWalletAmount, "Max wallet amount exceeded" ); } uint256 taxForMarketing = 0; if (from == uniswapV2Pair) { taxForMarketing = buyTaxForMarketing; } else if (to == uniswapV2Pair) { taxForMarketing = sellTaxForMarketing; } uint256 liquidityShare = ((amount * taxForLiquidity) / 100); uint256 transferAmount = amount - (marketingShare + liquidityShare); from, address(this), (marketingShare + liquidityShare) ); super._transfer(from, to, amount); } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "Cannot transfer to 0"); require(to != address(0), "Cannot transfer from 0"); require(balanceOf(from) >= amount, "Amount exceeds balance"); if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { super._transfer(from, to, amount); return; } require(publicTradingActive, "Trading not active"); (from == uniswapV2Pair || to == uniswapV2Pair) && !inSwapAndLiquify ) { if (from != uniswapV2Pair) { uint256 contractLiquidityBalance = balanceOf(address(this)) - _marketingReserves; if (contractLiquidityBalance >= numTokensSellToAddToLiquidity) { _swapAndLiquify(numTokensSellToAddToLiquidity); } if ((_marketingReserves) >= numTokensSellToAddToETH) { _swapTokensForEth(numTokensSellToAddToETH); _marketingReserves -= numTokensSellToAddToETH; bool sent = payable(marketingWallet).send( address(this).balance ); require(sent, "Failed to send ETH"); } } require(amount <= maxTxAmount, "Max transaction amount exceeded"); if (from == uniswapV2Pair) { require( (amount + balanceOf(to)) <= maxWalletAmount, "Max wallet amount exceeded" ); } uint256 taxForMarketing = 0; if (from == uniswapV2Pair) { taxForMarketing = buyTaxForMarketing; } else if (to == uniswapV2Pair) { taxForMarketing = sellTaxForMarketing; } uint256 liquidityShare = ((amount * taxForLiquidity) / 100); uint256 transferAmount = amount - (marketingShare + liquidityShare); from, address(this), (marketingShare + liquidityShare) ); super._transfer(from, to, amount); } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "Cannot transfer to 0"); require(to != address(0), "Cannot transfer from 0"); require(balanceOf(from) >= amount, "Amount exceeds balance"); if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { super._transfer(from, to, amount); return; } require(publicTradingActive, "Trading not active"); (from == uniswapV2Pair || to == uniswapV2Pair) && !inSwapAndLiquify ) { if (from != uniswapV2Pair) { uint256 contractLiquidityBalance = balanceOf(address(this)) - _marketingReserves; if (contractLiquidityBalance >= numTokensSellToAddToLiquidity) { _swapAndLiquify(numTokensSellToAddToLiquidity); } if ((_marketingReserves) >= numTokensSellToAddToETH) { _swapTokensForEth(numTokensSellToAddToETH); _marketingReserves -= numTokensSellToAddToETH; bool sent = payable(marketingWallet).send( address(this).balance ); require(sent, "Failed to send ETH"); } } require(amount <= maxTxAmount, "Max transaction amount exceeded"); if (from == uniswapV2Pair) { require( (amount + balanceOf(to)) <= maxWalletAmount, "Max wallet amount exceeded" ); } uint256 taxForMarketing = 0; if (from == uniswapV2Pair) { taxForMarketing = buyTaxForMarketing; } else if (to == uniswapV2Pair) { taxForMarketing = sellTaxForMarketing; } uint256 liquidityShare = ((amount * taxForLiquidity) / 100); uint256 transferAmount = amount - (marketingShare + liquidityShare); from, address(this), (marketingShare + liquidityShare) ); super._transfer(from, to, amount); } } uint256 marketingShare = ((amount * taxForMarketing) / 100); _marketingReserves += marketingShare; super._transfer( super._transfer(from, to, transferAmount); } else { function enablePublicTrading() external onlyOwner { publicTradingActive = true; emit PublicTradingStarted(); } function excludeFromFee(address _address, bool _status) external onlyOwner { _isExcludedFromFee[_address] = _status; emit ExcludedFromFeeUpdated(_address, _status); } function _swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 half = contractTokenBalance >> 1; uint256 otherHalf = (contractTokenBalance - half); uint256 initialBalance = address(this).balance; _swapTokensForEth(half); uint256 newBalance = (address(this).balance - initialBalance); _addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function _swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function _addLiquidity( uint256 tokenAmount, uint256 ethAmount ) private lockTheSwap { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, 0, 0, marketingWallet, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function changeMarketingWallet( address newWallet ) external onlyOwner returns (bool) { require(newWallet != DEAD, "LP Pair cannot be DEAD"); require(newWallet != address(0), "LP Pair cannot be 0"); marketingWallet = newWallet; emit MarketingWalletUpdated(newWallet); return true; } function changeTaxForLiquidityAndMarketing( uint256 _taxForLiquidity, uint256 _buyTaxForMarketing, uint256 _sellTaxForMarketing ) external onlyOwner returns (bool) { require( (_taxForLiquidity + _buyTaxForMarketing) < 11, "Max tax is 10%" ); require( (_taxForLiquidity + _sellTaxForMarketing) < 11, "Max tax is 10%" ); taxForLiquidity = _taxForLiquidity; buyTaxForMarketing = _buyTaxForMarketing; sellTaxForMarketing = _sellTaxForMarketing; emit TaxUpdated( _taxForLiquidity, _buyTaxForMarketing, _sellTaxForMarketing ); return true; } function changeSwapThresholds( uint256 _numTokensSellToAddToLiquidity, uint256 _numTokensSellToAddToETH ) external onlyOwner returns (bool) { require( _numTokensSellToAddToLiquidity < _supply / 98, "Max 2% of total supply" ); require( _numTokensSellToAddToETH < _supply / 98, "Max 2% of total supply" ); numTokensSellToAddToLiquidity = _numTokensSellToAddToLiquidity * 10 ** _decimals; numTokensSellToAddToETH = _numTokensSellToAddToETH * 10 ** _decimals; emit SwapThresholdUpdated( _numTokensSellToAddToLiquidity, _numTokensSellToAddToETH ); return true; } function changeMaxTxAmount( uint256 _maxTxAmount ) external onlyOwner returns (bool) { maxTxAmount = _maxTxAmount; emit MaxTransactionAmountUpdated(_maxTxAmount); return true; } function changeMaxWalletAmount( uint256 _maxWalletAmount ) external onlyOwner returns (bool) { maxWalletAmount = _maxWalletAmount; emit MaxWalletAmountUpdated(_maxWalletAmount); return true; } }
7,047,775
[ 1, 7731, 281, 4238, 2229, 19, 19177, 30980, 3497, 7523, 310, 1351, 291, 91, 438, 11022, 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, 16351, 385, 793, 52, 10658, 1345, 353, 4232, 39, 3462, 2171, 288, 203, 565, 533, 3238, 389, 529, 273, 315, 39, 793, 4066, 45, 14432, 203, 565, 533, 3238, 389, 7175, 273, 315, 4066, 45, 14432, 203, 565, 2254, 28, 3238, 389, 31734, 273, 6549, 31, 203, 565, 2254, 5034, 3238, 389, 2859, 1283, 273, 20963, 2787, 11706, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 273, 374, 92, 26, 2954, 24347, 4630, 5608, 20, 72, 8285, 5540, 26, 40, 7301, 2947, 22, 74, 5193, 10689, 72, 24, 38, 11149, 74, 21, 29534, 9599, 21, 31, 203, 565, 1758, 1071, 2030, 1880, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 203, 565, 2254, 5034, 1071, 5320, 1290, 48, 18988, 24237, 273, 17495, 31, 203, 565, 2254, 5034, 1071, 357, 80, 7731, 1290, 3882, 21747, 273, 17495, 31, 203, 565, 2254, 5034, 1071, 30143, 7731, 1290, 3882, 21747, 273, 17495, 31, 203, 565, 2254, 5034, 1071, 818, 5157, 55, 1165, 13786, 774, 48, 18988, 24237, 273, 5958, 28, 2787, 380, 1728, 2826, 389, 31734, 31, 203, 565, 2254, 5034, 1071, 818, 5157, 55, 1165, 13786, 774, 1584, 44, 273, 20963, 2787, 380, 1728, 2826, 389, 31734, 31, 203, 565, 2254, 5034, 1071, 389, 3355, 21747, 607, 264, 3324, 31, 203, 203, 565, 2254, 5034, 1071, 943, 4188, 6275, 273, 20963, 17877, 380, 1728, 2826, 389, 31734, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 6275, 273, 20963, 17877, 380, 1728, 2826, 389, 31734, 31, 203, 565, 871, 6622, 2 ]
// https://t.me/supergokucoin // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; 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; } } 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); } 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; } } 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); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface 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); } 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; } // Contract implementation contract SuperGoku is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 690000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Super Goku'; string private _symbol = 'SuperGoku'; uint8 private _decimals = 9; // Tax and Goku fees will start at 0 so we don't have a big impact when deploying to Uniswap // Goku wallet address is null but the method to set the address is exposed uint256 private _taxFee = 0; uint256 private _GokuFee = 7; uint256 private _previousTaxFee = _taxFee; uint256 private _previousGokuFee = _GokuFee; address payable public _GokuWalletAddress; address payable public _marketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 690000000 * 10**9; // We will set a minimum amount of tokens to be swaped => 5M uint256 private _numOfTokensToExchangeForGoku = 2000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable GokuWalletAddress, address payable marketingWalletAddress) public { _GokuWalletAddress = GokuWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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; } 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 isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _GokuFee == 0) return; _previousTaxFee = _taxFee; _previousGokuFee = _GokuFee; _taxFee = 0; _GokuFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _GokuFee = _previousGokuFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap? // also, don't get caught in a circular Goku event. // also, don't swap if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForGoku; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { // We need to swap the current tokens to ETH and send to the Goku wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToGoku(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } //transfer amount, it will take tax and Goku fee _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToGoku(uint256 amount) private { _GokuWalletAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToGoku(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tGoku) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeGoku(tGoku); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tGoku) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeGoku(tGoku); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tGoku) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeGoku(tGoku); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tGoku) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeGoku(tGoku); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeGoku(uint256 tGoku) private { uint256 currentRate = _getRate(); uint256 rGoku = tGoku.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rGoku); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tGoku); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tGoku) = _getTValues(tAmount, _taxFee, _GokuFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tGoku); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 GokuFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tGoku = tAmount.mul(GokuFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tGoku); return (tTransferAmount, tFee, tGoku); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 10, 'taxFee should be in 1 - 10'); _taxFee = taxFee; } function _setGokuFee(uint256 GokuFee) external onlyOwner() { require(GokuFee >= 1 && GokuFee <= 99, 'GokuFee should be in 1 - 99'); _GokuFee = GokuFee; } function _setGokuWallet(address payable GokuWalletAddress) external onlyOwner() { _GokuWalletAddress = GokuWalletAddress; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } }
Create a uniswap pair for this new token set the rest of the contract variables Exclude owner and this contract from fee
constructor (address payable GokuWalletAddress, address payable marketingWalletAddress) public { _GokuWalletAddress = GokuWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); }
10,035,374
[ 1, 1684, 279, 640, 291, 91, 438, 3082, 364, 333, 394, 1147, 444, 326, 3127, 434, 326, 6835, 3152, 20760, 3410, 471, 333, 6835, 628, 14036, 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, 3885, 261, 2867, 8843, 429, 611, 20924, 16936, 1887, 16, 1758, 8843, 429, 13667, 310, 16936, 1887, 13, 1071, 288, 203, 3639, 389, 43, 20924, 16936, 1887, 273, 611, 20924, 16936, 1887, 31, 203, 3639, 389, 3355, 21747, 16936, 1887, 273, 13667, 310, 16936, 1887, 31, 203, 3639, 389, 86, 5460, 329, 63, 67, 3576, 12021, 1435, 65, 273, 389, 86, 5269, 31, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 8443, 1435, 65, 273, 638, 31, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 389, 3576, 12021, 9334, 389, 88, 5269, 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 ]
pragma solidity ^0.8.4; import "../../contracts/dnssec-oracle/RRUtils.sol"; import "../../contracts/dnssec-oracle/BytesUtils.sol"; contract TestRRUtils { using BytesUtils for *; using RRUtils for *; uint16 constant DNSTYPE_A = 1; uint16 constant DNSTYPE_CNAME = 5; uint16 constant DNSTYPE_MX = 15; uint16 constant DNSTYPE_TEXT = 16; uint16 constant DNSTYPE_RRSIG = 46; uint16 constant DNSTYPE_NSEC = 47; uint16 constant DNSTYPE_TYPE1234 = 1234; function testNameLength() public pure { require(hex'00'.nameLength(0) == 1, "nameLength('.') == 1"); require(hex'0361626300'.nameLength(4) == 1, "nameLength('.') == 1"); require(hex'0361626300'.nameLength(0) == 5, "nameLength('abc.') == 5"); } function testLabelCount() public pure { require(hex'00'.labelCount(0) == 0, "labelCount('.') == 0"); require(hex'016100'.labelCount(0) == 1, "labelCount('a.') == 1"); require(hex'016201610000'.labelCount(0) == 2, "labelCount('b.a.') == 2"); require(hex'066574686c61620378797a00'.labelCount(6 +1) == 1, "nameLength('(bthlab).xyz.') == 6"); } function testIterateRRs() public pure { // a. IN A 3600 127.0.0.1 // b.a. IN A 3600 192.168.1.1 bytes memory rrs = hex'0161000001000100000e1000047400000101620161000001000100000e100004c0a80101'; string[2] memory names = [hex'016100', hex'0162016100']; string[2] memory rdatas = [hex'74000001', hex'c0a80101']; uint i = 0; for(RRUtils.RRIterator memory iter = rrs.iterateRRs(0); !iter.done(); iter.next()) { require(uint(iter.dnstype) == 1, "Type matches"); require(uint(iter.class) == 1, "Class matches"); require(uint(iter.ttl) == 3600, "TTL matches"); require(keccak256(iter.name()) == keccak256(bytes(names[i])), "Name matches"); require(keccak256(iter.rdata()) == keccak256(bytes(rdatas[i])), "Rdata matches"); i++; } require(i == 2, "Expected 2 records"); } function testCheckTypeBitmapTextType() public pure { bytes memory tb = hex'0003000080'; require(tb.checkTypeBitmap(0, DNSTYPE_TEXT) == true, "A record should exist in type bitmap"); } function testCheckTypeBitmap() public pure { // From https://tools.ietf.org/html/rfc4034#section-4.3 // alfa.example.com. 86400 IN NSEC host.example.com. ( // A MX RRSIG NSEC TYPE1234 bytes memory tb = hex'FF0006400100000003041b000000000000000000000000000000000000000000000000000020'; // Exists in bitmap require(tb.checkTypeBitmap(1, DNSTYPE_A) == true, "A record should exist in type bitmap"); // Does not exist, but in a window that is included require(tb.checkTypeBitmap(1, DNSTYPE_CNAME) == false, "CNAME record should not exist in type bitmap"); // Does not exist, past the end of a window that is included require(tb.checkTypeBitmap(1, 64) == false, "Type 64 should not exist in type bitmap"); // Does not exist, in a window that does not exist require(tb.checkTypeBitmap(1, 769) == false, "Type 769 should not exist in type bitmap"); // Exists in a subsequent window require(tb.checkTypeBitmap(1, DNSTYPE_TYPE1234) == true, "Type 1234 should exist in type bitmap"); // Does not exist, past the end of the bitmap windows require(tb.checkTypeBitmap(1, 1281) == false, "Type 1281 should not exist in type bitmap"); } // Canonical ordering https://tools.ietf.org/html/rfc4034#section-6.1 function testCompareNames() public pure { bytes memory bthLabXyz = hex'066274686c61620378797a00'; bytes memory ethLabXyz = hex'066574686c61620378797a00'; bytes memory xyz = hex'0378797a00'; bytes memory a_b_c = hex'01610162016300'; bytes memory b_b_c = hex'01620162016300'; bytes memory c = hex'016300'; bytes memory d = hex'016400'; bytes memory a_d_c = hex'01610164016300'; bytes memory b_a_c = hex'01620161016300'; bytes memory ab_c_d = hex'0261620163016400'; bytes memory a_c_d = hex'01610163016400'; require(hex'0301616100'.compareNames(hex'0302616200') < 0, "label lengths are correctly checked"); require(a_b_c.compareNames(c) > 0, "one name has a difference of >1 label to with the same root name"); require(a_b_c.compareNames(d) < 0, "one name has a difference of >1 label to with different root name"); require(a_b_c.compareNames(a_d_c) < 0, "two names start the same but have differences in later labels"); require(a_b_c.compareNames(b_a_c) > 0, "the first label sorts later, but the first label sorts earlier"); require(ab_c_d.compareNames(a_c_d) > 0, "two names where the first label on one is a prefix of the first label on the other"); require(a_b_c.compareNames(b_b_c) < 0, "two names where the first label on one is a prefix of the first label on the other"); require(xyz.compareNames(ethLabXyz) < 0, "xyz comes before ethLab.xyz"); require(bthLabXyz.compareNames(ethLabXyz) < 0, "bthLab.xyz comes before ethLab.xyz"); require(bthLabXyz.compareNames(bthLabXyz) == 0, "bthLab.xyz and bthLab.xyz are the same"); require(ethLabXyz.compareNames(bthLabXyz) > 0, "ethLab.xyz comes after bethLab.xyz"); require(bthLabXyz.compareNames(xyz) > 0, "bthLab.xyz comes after xyz"); } function testSerialNumberGt() public pure { require(RRUtils.serialNumberGte(1, 0), "1 >= 0"); require(!RRUtils.serialNumberGte(0, 1), "!(0 <= 1)"); require(RRUtils.serialNumberGte(0, 0xFFFFFFFF), "0 >= 0xFFFFFFFF"); require(!RRUtils.serialNumberGte(0xFFFFFFFF, 0), "!(0 <= 0xFFFFFFFF)"); require(RRUtils.serialNumberGte(0x11111111, 0xAAAAAAAA), "0x11111111 >= 0xAAAAAAAA"); require(RRUtils.serialNumberGte(1, 1), "1 >= 1"); } }
From https:tools.ietf.org/html/rfc4034#section-4.3 alfa.example.com. 86400 IN NSEC host.example.com. ( A MX RRSIG NSEC TYPE1234 Exists in bitmap Does not exist, but in a window that is included Does not exist, past the end of a window that is included Does not exist, in a window that does not exist Exists in a subsequent window Does not exist, past the end of the bitmap windows
function testCheckTypeBitmap() public pure { bytes memory tb = hex'FF0006400100000003041b000000000000000000000000000000000000000000000000000020'; require(tb.checkTypeBitmap(1, DNSTYPE_A) == true, "A record should exist in type bitmap"); require(tb.checkTypeBitmap(1, DNSTYPE_CNAME) == false, "CNAME record should not exist in type bitmap"); require(tb.checkTypeBitmap(1, 64) == false, "Type 64 should not exist in type bitmap"); require(tb.checkTypeBitmap(1, 769) == false, "Type 769 should not exist in type bitmap"); require(tb.checkTypeBitmap(1, DNSTYPE_TYPE1234) == true, "Type 1234 should exist in type bitmap"); require(tb.checkTypeBitmap(1, 1281) == false, "Type 1281 should not exist in type bitmap"); }
1,758,378
[ 1, 1265, 2333, 30, 6642, 18, 18508, 18, 3341, 19, 2620, 19, 16784, 24, 4630, 24, 3464, 17, 24, 18, 23, 565, 524, 507, 18, 8236, 18, 832, 18, 21451, 2120, 423, 11944, 1479, 18, 8236, 18, 832, 18, 261, 1171, 9079, 432, 26929, 21618, 18513, 423, 11944, 3463, 28462, 17277, 316, 9389, 9637, 486, 1005, 16, 1496, 316, 279, 2742, 716, 353, 5849, 9637, 486, 1005, 16, 8854, 326, 679, 434, 279, 2742, 716, 353, 5849, 9637, 486, 1005, 16, 316, 279, 2742, 716, 1552, 486, 1005, 17277, 316, 279, 10815, 2742, 9637, 486, 1005, 16, 8854, 326, 679, 434, 326, 9389, 9965, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 1842, 1564, 559, 12224, 1435, 1071, 16618, 288, 203, 565, 1731, 3778, 8739, 273, 3827, 11, 2246, 3784, 1105, 11664, 17877, 23, 3028, 21, 70, 12648, 12648, 12648, 12648, 12648, 12648, 2787, 3462, 13506, 203, 203, 565, 2583, 12, 18587, 18, 1893, 559, 12224, 12, 21, 16, 18001, 882, 1738, 67, 37, 13, 422, 638, 16, 315, 37, 1409, 1410, 1005, 316, 618, 9389, 8863, 203, 565, 2583, 12, 18587, 18, 1893, 559, 12224, 12, 21, 16, 18001, 882, 1738, 67, 39, 1985, 13, 422, 629, 16, 315, 39, 1985, 1409, 1410, 486, 1005, 316, 618, 9389, 8863, 203, 565, 2583, 12, 18587, 18, 1893, 559, 12224, 12, 21, 16, 5178, 13, 422, 629, 16, 315, 559, 5178, 1410, 486, 1005, 316, 618, 9389, 8863, 203, 565, 2583, 12, 18587, 18, 1893, 559, 12224, 12, 21, 16, 2371, 8148, 13, 422, 629, 16, 315, 559, 2371, 8148, 1410, 486, 1005, 316, 618, 9389, 8863, 203, 565, 2583, 12, 18587, 18, 1893, 559, 12224, 12, 21, 16, 18001, 882, 1738, 67, 2399, 28462, 13, 422, 638, 16, 315, 559, 30011, 1410, 1005, 316, 618, 9389, 8863, 203, 565, 2583, 12, 18587, 18, 1893, 559, 12224, 12, 21, 16, 8038, 21, 13, 422, 629, 16, 315, 559, 8038, 21, 1410, 486, 1005, 316, 618, 9389, 8863, 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 ]
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../utility/ContractRegistryClient.sol"; import "../token/ReserveToken.sol"; import "./interfaces/IConverter.sol"; import "./interfaces/IConverterUpgrader.sol"; import "./interfaces/IConverterFactory.sol"; interface ILegacyConverterVersion45 is IConverter { function withdrawTokens( IReserveToken _token, address _to, uint256 _amount ) external; function withdrawETH(address payable _to) external; } /** * @dev This contract contract allows upgrading an older converter contract (0.4 and up) * to the latest version. * To begin the upgrade process, simply execute the 'upgrade' function. * At the end of the process, the ownership of the newly upgraded converter will be transferred * back to the original owner and the original owner will need to execute the 'acceptOwnership' function. * * The address of the new converter is available in the ConverterUpgrade event. * * Note that for older converters that don't yet have the 'upgrade' function, ownership should first * be transferred manually to the ConverterUpgrader contract using the 'transferOwnership' function * and then the upgrader 'upgrade' function should be executed directly. */ contract ConverterUpgrader is IConverterUpgrader, ContractRegistryClient { using ReserveToken for IReserveToken; /** * @dev triggered when the contract accept a converter ownership * * @param _converter converter address * @param _owner new owner - local upgrader address */ event ConverterOwned(IConverter indexed _converter, address indexed _owner); /** * @dev triggered when the upgrading process is done * * @param _oldConverter old converter address * @param _newConverter new converter address */ event ConverterUpgrade(address indexed _oldConverter, address indexed _newConverter); /** * @dev initializes a new ConverterUpgrader instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) public ContractRegistryClient(_registry) {} /** * @dev upgrades an old converter to the latest version * will throw if ownership wasn't transferred to the upgrader before calling this function. * ownership of the new converter will be transferred back to the original owner. * fires the ConverterUpgrade event upon success. * can only be called by a converter * * @param _version old converter version */ function upgrade(bytes32 _version) external override { upgradeOld(IConverter(msg.sender), _version); } /** * @dev upgrades an old converter to the latest version * will throw if ownership wasn't transferred to the upgrader before calling this function. * ownership of the new converter will be transferred back to the original owner. * fires the ConverterUpgrade event upon success. * can only be called by a converter * * @param _version old converter version */ function upgrade(uint16 _version) external override { upgrade(IConverter(msg.sender), _version); } /** * @dev upgrades an old converter to the latest version * will throw if ownership wasn't transferred to the upgrader before calling this function. * ownership of the new converter will be transferred back to the original owner. * fires the ConverterUpgrade event upon success. * * @param _converter old converter contract address */ function upgradeOld( IConverter _converter, bytes32 /* _version */ ) public { // the upgrader doesn't require the version for older converters upgrade(_converter, 0); } /** * @dev upgrades an old converter to the latest version * will throw if ownership wasn't transferred to the upgrader before calling this function. * ownership of the new converter will be transferred back to the original owner. * fires the ConverterUpgrade event upon success. * * @param _converter old converter contract address * @param _version old converter version */ function upgrade(IConverter _converter, uint16 _version) private { IConverter converter = IConverter(_converter); address prevOwner = converter.owner(); acceptConverterOwnership(converter); IConverter newConverter = createConverter(converter); copyReserves(converter, newConverter); copyConversionFee(converter, newConverter); transferReserveBalances(converter, newConverter, _version); IConverterAnchor anchor = converter.token(); if (anchor.owner() == address(converter)) { converter.transferTokenOwnership(address(newConverter)); newConverter.acceptAnchorOwnership(); } converter.transferOwnership(prevOwner); newConverter.transferOwnership(prevOwner); newConverter.onUpgradeComplete(); emit ConverterUpgrade(address(converter), address(newConverter)); } /** * @dev the first step when upgrading a converter is to transfer the ownership to the local contract. * the upgrader contract then needs to accept the ownership transfer before initiating * the upgrade process. * fires the ConverterOwned event upon success * * @param _oldConverter converter to accept ownership of */ function acceptConverterOwnership(IConverter _oldConverter) private { _oldConverter.acceptOwnership(); emit ConverterOwned(_oldConverter, address(this)); } /** * @dev creates a new converter with same basic data as the original old converter * the newly created converter will have no reserves at this step. * * @param _oldConverter old converter contract address * * @return the new converter new converter contract address */ function createConverter(IConverter _oldConverter) private returns (IConverter) { IConverterAnchor anchor = _oldConverter.token(); uint32 maxConversionFee = _oldConverter.maxConversionFee(); uint16 reserveTokenCount = _oldConverter.connectorTokenCount(); // determine new converter type uint16 newType = 0; // new converter - get the type from the converter itself if (isV28OrHigherConverter(_oldConverter)) { newType = _oldConverter.converterType(); } else if (reserveTokenCount > 1) { // old converter - if it has 1 reserve token, the type is a liquid token, otherwise the type liquidity pool newType = 1; } if (newType == 1 && reserveTokenCount == 2) { (, uint32 weight0, , , ) = _oldConverter.connectors(_oldConverter.connectorTokens(0)); (, uint32 weight1, , , ) = _oldConverter.connectors(_oldConverter.connectorTokens(1)); if (weight0 == PPM_RESOLUTION / 2 && weight1 == PPM_RESOLUTION / 2) { newType = 3; } } IConverterFactory converterFactory = IConverterFactory(addressOf(CONVERTER_FACTORY)); IConverter converter = converterFactory.createConverter(newType, anchor, registry, maxConversionFee); converter.acceptOwnership(); return converter; } /** * @dev copies the reserves from the old converter to the new one. * note that this will not work for an unlimited number of reserves due to block gas limit constraints. * * @param _oldConverter old converter contract address * @param _newConverter new converter contract address */ function copyReserves(IConverter _oldConverter, IConverter _newConverter) private { uint16 reserveTokenCount = _oldConverter.connectorTokenCount(); for (uint16 i = 0; i < reserveTokenCount; i++) { IReserveToken reserveAddress = _oldConverter.connectorTokens(i); (, uint32 weight, , , ) = _oldConverter.connectors(reserveAddress); _newConverter.addReserve(reserveAddress, weight); } } /** * @dev copies the conversion fee from the old converter to the new one * * @param _oldConverter old converter contract address * @param _newConverter new converter contract address */ function copyConversionFee(IConverter _oldConverter, IConverter _newConverter) private { uint32 conversionFee = _oldConverter.conversionFee(); _newConverter.setConversionFee(conversionFee); } /** * @dev transfers the balance of each reserve in the old converter to the new one. * note that the function assumes that the new converter already has the exact same number of reserves * also, this will not work for an unlimited number of reserves due to block gas limit constraints. * * @param _oldConverter old converter contract address * @param _newConverter new converter contract address * @param _version old converter version */ function transferReserveBalances( IConverter _oldConverter, IConverter _newConverter, uint16 _version ) private { if (_version <= 45) { transferReserveBalancesVersion45(ILegacyConverterVersion45(address(_oldConverter)), _newConverter); return; } _oldConverter.transferReservesOnUpgrade(address(_newConverter)); } /** * @dev transfers the balance of each reserve in the old converter to the new one. * note that the function assumes that the new converter already has the exact same number of reserves * also, this will not work for an unlimited number of reserves due to block gas limit constraints. * * @param _oldConverter old converter contract address * @param _newConverter new converter contract address */ function transferReserveBalancesVersion45(ILegacyConverterVersion45 _oldConverter, IConverter _newConverter) private { uint16 reserveTokenCount = _oldConverter.connectorTokenCount(); for (uint16 i = 0; i < reserveTokenCount; i++) { IReserveToken reserveToken = _oldConverter.connectorTokens(i); uint256 reserveBalance = reserveToken.balanceOf(address(_oldConverter)); if (reserveBalance > 0) { if (reserveToken.isNativeToken()) { _oldConverter.withdrawETH(address(_newConverter)); } else { _oldConverter.withdrawTokens(reserveToken, address(_newConverter), reserveBalance); } } } } bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()")); // using a static call to identify converter version // can't rely on the version number since the function had a different signature in older converters function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) { bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR); (bool success, bytes memory returnData) = address(_converter).staticcall{ gas: 4000 }(data); if (success && returnData.length == 32) { return abi.decode(returnData, (bool)); } return false; } }
* @dev copies the reserves from the old converter to the new one. note that this will not work for an unlimited number of reserves due to block gas limit constraints. @param _oldConverter old converter contract address @param _newConverter new converter contract address/
function copyReserves(IConverter _oldConverter, IConverter _newConverter) private { uint16 reserveTokenCount = _oldConverter.connectorTokenCount(); for (uint16 i = 0; i < reserveTokenCount; i++) { IReserveToken reserveAddress = _oldConverter.connectorTokens(i); (, uint32 weight, , , ) = _oldConverter.connectors(reserveAddress); _newConverter.addReserve(reserveAddress, weight); } }
12,942,735
[ 1, 22295, 606, 326, 400, 264, 3324, 628, 326, 1592, 6027, 358, 326, 394, 1245, 18, 4721, 716, 333, 903, 486, 1440, 364, 392, 640, 21325, 1300, 434, 400, 264, 3324, 6541, 358, 1203, 16189, 1800, 6237, 18, 225, 389, 1673, 5072, 565, 1592, 6027, 6835, 1758, 225, 389, 2704, 5072, 565, 394, 6027, 6835, 1758, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 1610, 607, 264, 3324, 12, 45, 5072, 389, 1673, 5072, 16, 467, 5072, 389, 2704, 5072, 13, 3238, 288, 203, 3639, 2254, 2313, 20501, 1345, 1380, 273, 389, 1673, 5072, 18, 23159, 1345, 1380, 5621, 203, 203, 3639, 364, 261, 11890, 2313, 277, 273, 374, 31, 277, 411, 20501, 1345, 1380, 31, 277, 27245, 288, 203, 5411, 467, 607, 6527, 1345, 20501, 1887, 273, 389, 1673, 5072, 18, 23159, 5157, 12, 77, 1769, 203, 5411, 261, 16, 2254, 1578, 3119, 16, 269, 269, 262, 273, 389, 1673, 5072, 18, 4646, 18886, 12, 455, 6527, 1887, 1769, 203, 203, 5411, 389, 2704, 5072, 18, 1289, 607, 6527, 12, 455, 6527, 1887, 16, 3119, 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 ]
/* * LibertyPie Project (https://libertypie.com) * @author https://github.com/libertypie ([email protected]) * @license SPDX-License-Identifier: MIT */ pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "./StoreEditor.sol"; contract BasicStore is StoreEditor { /** * @dev scalar values */ //uint256 store mapping(bytes32 => uint256) private uint256Store; //int store mapping(bytes32 => int256) private int256Store; //string store mapping(bytes32 => string) private stringStore; //bool store mapping(bytes32 => bool) private boolStore; //address store mapping(bytes32 => address) private addressStore; //bytes store mapping(bytes32 => bytes) private bytesStore; //mapping store // key => mapping mapping(bytes32 => mapping(bytes32 => bytes)) private mappingStore; // nested mapping store mapping(bytes32 => mapping(bytes32 => mapping(bytes32 => bytes))) private nestedMappingStore; /** * Setters */ /** * @dev set uint256 */ function setUint256(bytes32 _key, uint256 _data) external onlyStoreEditor { uint256Store[_key] = _data; } /** * @dev increment uint256 this adds a +1 to the exiting data */ function incrementUint256(bytes32 _key) external onlyStoreEditor returns(uint256) { uint256Store[_key] += 1; } /** * @dev set int256 */ function setInt256(bytes32 _key, int256 _data) external onlyStoreEditor { int256Store[_key] = _data; } /** * @dev set string */ function setString(bytes32 _key, string calldata _data) external onlyStoreEditor { stringStore[_key] = _data; } /** * @dev set boolean */ function setBool(bytes32 _key, bool _data) external onlyStoreEditor { boolStore[_key] = _data; } /** * @dev set address */ function setAddress(bytes32 _key, address _data) external onlyStoreEditor { addressStore[_key] = _data; } /** * @dev set bytes data */ function setBytes(bytes32 _key, bytes memory _data) external onlyStoreEditor { bytesStore[_key] = _data; } /** * Getters */ /** * get uint256 */ function getUint256(bytes32 _key) public view returns(uint256) { return uint256Store[_key]; } /** * get int256 */ function getInt256(bytes32 _key) public view returns(int256) { return int256Store[_key]; } /** * get bool */ function getBool(bytes32 _key) public view returns(bool) { return boolStore[_key]; } /** * get address */ function getAddress(bytes32 _key) public view returns(address) { return addressStore[_key]; } /** * get string */ function getString(bytes32 _key) public view returns(string memory) { return stringStore[_key]; } }
* @dev set bytes data/
function setBytes(bytes32 _key, bytes memory _data) external onlyStoreEditor { bytesStore[_key] = _data; }
948,183
[ 1, 542, 1731, 501, 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, 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, 377, 445, 444, 2160, 12, 3890, 1578, 389, 856, 16, 1731, 3778, 389, 892, 13, 3903, 1338, 2257, 6946, 288, 203, 3639, 1731, 2257, 63, 67, 856, 65, 273, 389, 892, 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, -100, -100, -100, -100 ]
pragma solidity ^0.4.17; contract Ownable { address owner; address potentialOwner; modifier onlyOwner() { require(owner == msg.sender); _; } function Ownable() public { owner = msg.sender; } /* * PUBLIC * Check whether you `own` this Lottery */ function amIOwner() public view returns (bool) { return msg.sender == owner; } /* * RESTRICTED * Transfer ownership to another address (goes into effect when other address accepts) */ function transferOwnership(address _newOwner) public onlyOwner { potentialOwner = _newOwner; } /* * RESTRICTED * Accept ownership of the Lottery (if a transfer has been initiated with your address) */ function acceptOwnership() public { require(msg.sender == potentialOwner); owner = msg.sender; potentialOwner = address(0); } } contract Linkable is Ownable { address[] linked; modifier onlyLinked() { require(checkPermissions() == true); _; } /* * RESTRICTED * Link an address to this contract. This address has access to * any `onlyLinked` function */ function link(address _address) public onlyOwner { linked.push(_address); } /* * PUBLIC * Check if you have been linked to this contract */ function checkPermissions() public view returns (bool) { for (uint i = 0; i < linked.length; i++) if (linked[i] == msg.sender) return true; return false; } } contract Activity is Ownable, Linkable { struct Event { uint id; uint gameId; address source; address[] winners; uint winningNumber; uint amount; uint timestamp; } /* * Get an event by it's id (index) */ Event[] public events; /* * Add a new event */ function newEvent(uint _gameId, address[] _winners, uint _winningNumber, uint _amount) public onlyLinked { require(_gameId > 0); events.push(Event(events.length, _gameId, msg.sender, _winners, _winningNumber, _amount, now)); } /* * Get the activity feed for all games * * NOTE: set gameId to 0 for a feed of all games * * RETURNS: * (ids[], gameIds[], sources[], winners[] (index 0 OR msg.sender if they won), numWinners[], winningNums[], jackpots[], timestamps[]) */ function getFeed(uint _gameId, uint _page, uint _pageSize) public view returns (uint[], uint[], address[], uint[], uint[], uint[], uint[]) { return constructResponse(getFiltered(_gameId, _page - 1, _pageSize)); } // ------------------------------------------------------------ // Private Helpers function constructResponse(Event[] _events) private view returns (uint[], uint[], address[], uint[], uint[], uint[], uint[]) { uint[] memory _ids = new uint[](_events.length); uint[] memory _gameIds = new uint[](_events.length); uint[] memory _amounts = new uint[](_events.length); uint[] memory _timestamps = new uint[](_events.length); for (uint i = 0; i < _events.length; i++) { _ids[i] = _events[i].id; _gameIds[i] = _events[i].gameId; _amounts[i] = _events[i].amount; _timestamps[i] = _events[i].timestamp; } WinData memory _win = contructWinData(_events); return (_ids, _gameIds, _win.winners, _win.numWinners, _win.winningNumbers, _amounts, _timestamps); } struct WinData { address[] winners; uint[] numWinners; uint[] winningNumbers; } function contructWinData(Event[] _events) private view returns (WinData) { address[] memory _winners = new address[](_events.length); uint[] memory _numWinners = new uint[](_events.length); uint[] memory _winningNumbers = new uint[](_events.length); for (uint i = 0; i < _events.length; i++) { _winners[i] = chooseWinnerToDisplay(_events[i].winners, msg.sender); _numWinners[i] = _events[i].winners.length; _winningNumbers[i] = _events[i].winningNumber; } return WinData(_winners, _numWinners, _winningNumbers); } function chooseWinnerToDisplay(address[] _winners, address _user) private pure returns (address) { if (_winners.length < 1) return address(0); address _picked = _winners[0]; if (_winners.length == 1) return _picked; for (uint i = 1; i < _winners.length; i++) if (_winners[i] == _user) _picked = _user; return _picked; } function getFiltered(uint _gameId, uint _page, uint _pageSize) private view returns (Event[]) { Event[] memory _filtered = new Event[](_pageSize); uint _filteredIndex; uint _minIndex = _page * _pageSize; uint _maxIndex = _minIndex + _pageSize; uint _count; for (uint i = events.length; i > 0; i--) { if (_gameId == 0 || events[i - 1].gameId == _gameId) { if (_filteredIndex >= _minIndex && _filteredIndex < _maxIndex) { _filtered[_count] = events[i - 1]; _count++; } _filteredIndex++; } } Event[] memory _events = new Event[](_count); for (uint b = 0; b < _count; b++) _events[b] = _filtered[b]; return _events; } } contract Affiliates is Ownable, Linkable { bool open = true; bool promoted = true; /* * Open/Close registration of new affiliates */ function setRegistrationOpen(bool _open) public onlyOwner { open = _open; } function isRegistrationOpen() public view returns (bool) { return open; } /* * Should promote registration of new affiliates */ function setPromoted(bool _promoted) public onlyOwner { promoted = _promoted; } function isPromoted() public view returns (bool) { return promoted; } // ----------------------------------------------------------- mapping(uint => uint) balances; // (affiliateCode => balance) mapping(address => uint) links; // (buyer => affiliateCode) mapping(uint => bool) living; // whether a code has been used before (used for open/closing of program) /* * PUBLIC * Get the code for an affiliate */ function getCode() public view returns (uint) { return code(msg.sender); } // Convert an affiliate's address into a code function code(address _affiliate) private pure returns (uint) { uint num = uint(uint256(keccak256(_affiliate))); return num / 10000000000000000000000000000000000000000000000000000000000000000000000; } /* * PUBLIC * Get the address who originally referred the given user. Returns 0 if not referred */ function getAffiliation(address _user) public view onlyLinked returns (uint) { return links[_user]; } /* * PUBLIC * Set the affiliation of a user to a given code. Returns the address of the referrer * linked to that code OR, if a user has already been linked to a referer, returns the * address of their original referer */ function setAffiliation(address _user, uint _code) public onlyLinked returns (uint) { uint _affiliateCode = links[_user]; if (_affiliateCode != 0) return _affiliateCode; links[_user] = _code; return _code; } /* * RESTRICTED * Add Wei to multiple affiliates, be sure to send an amount of ether * equivalent to the sum of the _amounts array */ function deposit(uint[] _affiliateCodes, uint[] _amounts) public payable onlyLinked { require(_affiliateCodes.length == _amounts.length && _affiliateCodes.length > 0); uint _total; for (uint i = 0; i < _affiliateCodes.length; i++) { balances[_affiliateCodes[i]] += _amounts[i]; _total += _amounts[i]; } require(_total == msg.value && _total > 0); } event Withdrawn(address affiliate, uint amount); /* * PUBLIC * Withdraw Wei into your wallet (will revert if you have no balance) */ function withdraw() public returns (uint) { uint _code = code(msg.sender); uint _amount = balances[_code]; require(_amount > 0); balances[_code] = 0; msg.sender.transfer(_amount); Withdrawn(msg.sender, _amount); return _amount; } /* * PUBLIC * Get the amount of Wei you can withdraw */ function getBalance() public view returns (uint) { return balances[code(msg.sender)]; } } contract Lottery is Ownable { function Lottery() public { owner = msg.sender; } // --------------------------------------------------------------------- // Lottery Identification - mainly used for Activity events uint id; function setId(uint _id) public onlyOwner { require(_id > 0); id = _id; } // --------------------------------------------------------------------- // Linking /* * id: a unique non-zero id for this instance. Used for Activity events * activity: address pointing to the Activity instance */ function link(uint _id, address _activity, address _affiliates) public onlyOwner { require(_id > 0); id = _id; linkActivity(_activity); linkAffiliates(_affiliates); initialized(); } // Implement this function initialized() internal; // --------------------------------------------------------------------- // Activity Integration address public activityAddress; Activity activity; function linkActivity(address _address) internal onlyOwner { activity = Activity(_address); require(activity.checkPermissions() == true); activityAddress = _address; } function postEvent(address[] _winners, uint _winningNumber, uint _jackpot) internal { activity.newEvent(id, _winners, _winningNumber, _jackpot); } function postEvent(address _winner, uint _winningNumber, uint _jackpot) internal { address[] memory _winners = new address[](1); _winners[0] = _winner; postEvent(_winners, _winningNumber, _jackpot); } // --------------------------------------------------------------------- // Payment transfers address public affiliatesAddress; Affiliates affiliates; function linkAffiliates(address _address) internal onlyOwner { require(affiliatesAddress == address(0)); affiliates = Affiliates(_address); require(affiliates.checkPermissions() == true); affiliatesAddress = _address; } function setUserAffiliate(uint _code) internal returns (uint) { return affiliates.setAffiliation(msg.sender, _code); } function userAffiliate() internal view returns (uint) { return affiliates.getAffiliation(msg.sender); } function payoutToAffiliates(uint[] _addresses, uint[] _amounts, uint _total) internal { affiliates.deposit.value(_total)(_addresses, _amounts); } // --------------------------------------------------------------------- // Randomness function getRandomNumber(uint _max) internal returns (uint) { return uint(block.blockhash(block.number-1)) % _max + 1; } } contract SlotLottery is Lottery { function SlotLottery() Lottery() public { state = State.Uninitialized; } // --------------------------------------------------------------------- // Linking function initialized() internal { state = State.NotRunning; } // --------------------------------------------------------------------- // State State state; enum State { Uninitialized, Running, Pending, GameOver, NotRunning } modifier only(State _state) { require(state == _state); _; } modifier not(State _state) { require(state != _state); _; } modifier oneOf(State[2] memory _states) { bool _valid = false; for (uint i = 0; i < _states.length; i++) if (state == _states[i]) _valid = true; require(_valid); _; } /* * PUBLIC * Get the current state of the Lottery */ function getState() public view returns (State) { return state; } // --------------------------------------------------------------------- // Administrative /* * RESTRICTED * Start up a new game with the given game rules */ function startGame(uint _jackpot, uint _slots, uint _price, uint _max) public only(State.NotRunning) onlyOwner { require(_price * _slots > _jackpot); nextGame(verifiedGameRules(_jackpot, _slots, _price, _max)); } /* * RESTRICTED * When the currently running game ends, a new game won't be automatically started */ function suspendGame() public onlyOwner { game.loop = false; } /* * RESTRICTED * When the currently running game ends, a new game will be automatically started (this is the default behavior) */ function gameShouldRestart() public onlyOwner { game.loop = true; } /* * RESTRICTED * In the event that some error occurs and the contract never gets the random callback * the owner of the Lottery can trigger another random number to be retrieved */ function triggerFindWinner() public only(State.Pending) payable onlyOwner { state = State.Running; findWinner(); } /* * RESTRICTED * Set new rules for the next game */ function setNextRules(uint _jackpot, uint _slots, uint _price, uint _max) public not(State.NotRunning) onlyOwner { require(game.loop == true); game.nextGameRules = verifiedGameRules(_jackpot, _slots, _price, _max); } /* * RESTRICTED * Get the rules for the upcoming game (if there even is one) * (jackpot, numberOfTickets, ticketPrice, maxTicketsPer, willStartNewGameUponCompletion) */ function getNextRules() public view onlyOwner returns (uint, uint, uint, uint, bool) { return (game.nextGameRules.jackpot, game.nextGameRules.slots, game.nextGameRules.ticketPrice, game.nextGameRules.maxTicketsPer, game.loop); } // --------------------------------------------------------------------- // Lifecycle function nextGame(GameRules _rules) internal oneOf([State.GameOver, State.NotRunning]) { uint _newId = lastGame.id + 1; game = Game({ id: _newId, rules: _rules, nextGameRules: _rules, loop: true, startedAt: block.timestamp, ticketsSold: 0, winner: address(0), winningNumber: 0, finishedAt: 0 }); for(uint i = 1; i <= game.rules.slots; i++) game.tickets[i] = address(0); state = State.Running; } function findWinner() internal only(State.Running) { require(game.ticketsSold >= game.rules.slots); require(this.balance >= game.rules.jackpot); state = State.Pending; uint _winningNumber = getRandomNumber(game.rules.slots); winnerChosen(_winningNumber); } function winnerChosen(uint _winningNumber) internal only(State.Pending) { state = State.GameOver; address _winner = game.tickets[_winningNumber]; bool _startNew = game.loop; GameRules memory _nextRules = game.nextGameRules; game.finishedAt = block.timestamp; game.winner = _winner; game.winningNumber = _winningNumber; lastGame = game; // Pay winner, affiliates, and owner _winner.transfer(game.rules.jackpot); payAffiliates(); owner.transfer(this.balance); // Post new event to Activity contract postEvent(_winner, _winningNumber, game.rules.jackpot); if (!_startNew) { state = State.NotRunning; return; } nextGame(_nextRules); } // --------------------------------------------------------------------- // Lottery Game game; Game lastGame; enum PurchaseError { InvalidTicket, OutOfTickets, NotEnoughFunds, LotteryClosed, TooManyTickets, TicketUnavailable, Unknown } event TicketsPurchased(address buyer, uint[] tickets, uint[] failedTickets, PurchaseError[] errors); event PurchaseFailed(address buyer, PurchaseError error); /* * PUBLIC * Buy tickets for the Lottery by passing in an array of ticket numbers (starting at 1 not 0) * This function doesn't revert when tickets fail to be purchased, it triggers events and * refunds you for the tickets that failed to be purchased. * * Events: * TicketsPurchased: One or more tickets were successfully purchased * PurchaseFailed: Failed to purchase all of the tickets */ function purchaseTickets(uint[] _tickets) public payable { purchaseTicketsWithReferral(_tickets, 0); } /* * PUBLIC * Buy tickets with a referral code */ function purchaseTicketsWithReferral(uint[] _tickets, uint _affiliateCode) public payable { // Check game state if (state != State.Running) { if (state == State.NotRunning) return failPurchase(PurchaseError.LotteryClosed); return failPurchase(PurchaseError.OutOfTickets); } // Check sent funds if (msg.value < _tickets.length * game.rules.ticketPrice) return failPurchase(PurchaseError.NotEnoughFunds); uint[] memory _userTickets = getMyTickets(); // Check max tickets (checked again in the loop below) if (_userTickets.length >= game.rules.maxTicketsPer) return failPurchase(PurchaseError.TooManyTickets); // Some tickets may fail while others succeed, lets keep track of all of that so it // can be returned to the frontend user uint[] memory _successful = new uint[](_tickets.length); uint[] memory _failed = new uint[](_tickets.length); PurchaseError[] memory _errors = new PurchaseError[](_tickets.length); uint _successCount; uint _errorCount; for(uint i = 0; i < _tickets.length; i++) { uint _ticket = _tickets[i]; // Check that the ticket is a valid number if (_ticket <= 0 || _ticket > game.rules.slots) { _failed[_errorCount] = _ticket; _errors[_errorCount] = PurchaseError.InvalidTicket; _errorCount++; continue; } // Check that the ticket is available for purchase if (game.tickets[_ticket] != address(0)) { _failed[_errorCount] = _ticket; _errors[_errorCount] = PurchaseError.TicketUnavailable; _errorCount++; continue; } // Check that the user hasn't reached their max tickets if (_userTickets.length + _successCount >= game.rules.maxTicketsPer) { _failed[_errorCount] = _ticket; _errors[_errorCount] = PurchaseError.TooManyTickets; _errorCount++; continue; } game.tickets[_ticket] = msg.sender; game.ticketsSold++; _successful[_successCount] = _ticket; _successCount++; } // Refund for failed tickets // Cannot refund more than received, will send what was given if refunding the free ticket if (_errorCount > 0) refund(_errorCount * game.rules.ticketPrice); // Affiliates uint _userAffiliateCode = userAffiliate(); if (_affiliateCode != 0 && _userAffiliateCode == 0) _userAffiliateCode = setUserAffiliate(_affiliateCode); if (_userAffiliateCode != 0) addAffiliate(_userAffiliateCode, _successCount); // TicketsPurchased(msg.sender, _normalizedSuccessful, _normalizedFailures, _normalizedErrors); TicketsPurchased(msg.sender, _successful, _failed, _errors); // If the last ticket was sold, signal to find a winner if (game.ticketsSold >= game.rules.slots) findWinner(); } /* * PUBLIC * Get the tickets you have purchased for the current game */ function getMyTickets() public view returns (uint[]) { uint _userTicketCount; for(uint i = 0; i < game.rules.slots; i++) if (game.tickets[i + 1] == msg.sender) _userTicketCount += 1; uint[] memory _tickets = new uint[](_userTicketCount); uint _index; for(uint b = 0; b < game.rules.slots; b++) { if (game.tickets[b + 1] == msg.sender) { _tickets[_index] = b + 1; _index++; } } return _tickets; } // --------------------------------------------------------------------- // Game struct GameRules { uint jackpot; uint slots; uint ticketPrice; uint maxTicketsPer; } function verifiedGameRules(uint _jackpot, uint _slots, uint _price, uint _max) internal pure returns (GameRules) { require((_price * _slots) - _jackpot > 100000000000000000); // margin is greater than 0.1 ETH (for callback fees) require(_max <= _slots); return GameRules(_jackpot, _slots, _price, _max); } struct Game { uint id; GameRules rules; mapping(uint => address) tickets; // (ticketNumber => buyerAddress) uint ticketsSold; GameRules nextGameRules; // These rules will be used if the game recreates itself address winner; uint winningNumber; bool loop; uint startedAt; uint finishedAt; } /* * PUBLIC * Get information pertaining to the current game * * returns: (id, jackpot, totalTickets, ticketsRemaining, ticketPrice, maxTickets, state, tickets[], yourTickets[]) * NOTE: tickets[] is an array of booleans, true = available and false = sold */ function getCurrentGame() public view returns (uint, uint, uint, uint, uint, uint, State, bool[], uint[]) { uint _remainingTickets = game.rules.slots - game.ticketsSold; bool[] memory _tickets = new bool[](game.rules.slots); uint[] memory _userTickets = getMyTickets(); for (uint i = 0; i < game.rules.slots; i++) _tickets[i] = game.tickets[i + 1] == address(0); return (game.id, game.rules.jackpot, game.rules.slots, _remainingTickets, game.rules.ticketPrice, game.rules.maxTicketsPer, state, _tickets, _userTickets); } /* * PUBLIC * Get information pertaining to the last game * * returns: (id, jackpot, totalTickets, ticketPrice, winner, finishedAt) * NOTE: tickets[] is an array of booleans, true = available and false = sold */ function getLastGame() public view returns(uint, uint, uint, uint, address, uint) { return (lastGame.id, lastGame.rules.jackpot, lastGame.rules.slots, lastGame.rules.ticketPrice, lastGame.winner, lastGame.finishedAt); } // --------------------------------------------------------------------- // Affiliates uint[] currentGameAffiliates; uint numAffiliates; uint affiliateCut = 2; // Example: 2 = 1/2 (50%), 3 = 1/3 (33%), etc. function addAffiliate(uint _affiliate, uint _ticketCount) internal { for (uint i = 0; i < _ticketCount; i++) { if (numAffiliates >= currentGameAffiliates.length) currentGameAffiliates.length += 1; currentGameAffiliates[numAffiliates++] = _affiliate; } } function payAffiliates() internal { uint profit = (game.rules.slots * game.rules.ticketPrice) - game.rules.jackpot; if (profit > this.balance) profit = this.balance; uint _payment = (profit / game.rules.slots) / affiliateCut; uint _pool = _payment * numAffiliates; uint[] memory _affiliates = new uint[](numAffiliates); uint[] memory _amounts = new uint[](numAffiliates); for (uint i = 0; i < numAffiliates; i++) { _affiliates[i] = currentGameAffiliates[i]; _amounts[i] = _payment; } // payout to given affiliates with given amounts if (numAffiliates > 0) payoutToAffiliates(_affiliates, _amounts, _pool); // Clear the affiliates numAffiliates = 0; } // --------------------------------------------------------------------- // Utilities function randomNumberFound(uint _number, uint _secret) internal { require(state == State.Pending); require(game.id == _secret); require(_number >= 1 && _number <= game.rules.slots); winnerChosen(_number); } function failPurchase(PurchaseError _error) internal { PurchaseFailed(msg.sender, _error); refund(msg.value); } function refund(uint _amount) internal { if (_amount > 0 && _amount <= msg.value) { msg.sender.transfer(_amount); } else if (_amount > msg.value) { msg.sender.transfer(msg.value); } } }
RESTRICTED Start up a new game with the given game rules/
function startGame(uint _jackpot, uint _slots, uint _price, uint _max) public only(State.NotRunning) onlyOwner { require(_price * _slots > _jackpot); nextGame(verifiedGameRules(_jackpot, _slots, _price, _max)); }
15,800,058
[ 1, 12030, 2259, 15494, 3603, 731, 279, 394, 7920, 598, 326, 864, 7920, 2931, 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, 202, 915, 787, 12496, 12, 11890, 389, 78, 484, 13130, 16, 2254, 389, 18875, 16, 2254, 389, 8694, 16, 2254, 389, 1896, 13, 1071, 1338, 12, 1119, 18, 1248, 7051, 13, 1338, 5541, 288, 203, 202, 202, 6528, 24899, 8694, 380, 389, 18875, 405, 389, 78, 484, 13130, 1769, 203, 202, 202, 4285, 12496, 12, 19685, 12496, 4478, 24899, 78, 484, 13130, 16, 389, 18875, 16, 389, 8694, 16, 389, 1896, 10019, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, 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/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^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 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"); } } } // File interfaces/IPreparable.sol pragma solidity 0.8.9; interface IPreparable { event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay); event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay); event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue); event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue); event ConfigReset(bytes32 indexed key); } // File interfaces/IStrategy.sol pragma solidity 0.8.9; interface IStrategy { function name() external view returns (string memory); function deposit() external payable returns (bool); function balance() external view returns (uint256); function withdraw(uint256 amount) external returns (bool); function withdrawAll() external returns (uint256); function harvestable() external view returns (uint256); function harvest() external returns (uint256); function strategist() external view returns (address); function shutdown() external returns (bool); function hasPendingFunds() external view returns (bool); } // File interfaces/IVault.sol pragma solidity 0.8.9; /** * @title Interface for a Vault */ interface IVault is IPreparable { event StrategyActivated(address indexed strategy); event StrategyDeactivated(address indexed strategy); /** * @dev 'netProfit' is the profit after all fees have been deducted */ event Harvest(uint256 indexed netProfit, uint256 indexed loss); function initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) external; function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256); function deposit() external payable; function withdraw(uint256 amount) external returns (bool); function initializeStrategy(address strategy_) external returns (bool); function withdrawAll() external; function withdrawFromReserve(uint256 amount) external; function getStrategy() external view returns (IStrategy); function getStrategiesWaitingForRemoval() external view returns (address[] memory); function getAllocatedToStrategyWaitingForRemoval(address strategy) external view returns (uint256); function getTotalUnderlying() external view returns (uint256); function getUnderlying() external view returns (address); } // File interfaces/pool/ILiquidityPool.sol pragma solidity 0.8.9; interface ILiquidityPool is IPreparable { event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens); event DepositFor( address indexed minter, address indexed mintee, uint256 depositAmount, uint256 mintedLpTokens ); event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens); event LpTokenSet(address indexed lpToken); event StakerVaultSet(address indexed stakerVault); function redeem(uint256 redeemTokens) external returns (uint256); function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256); function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256); function deposit(uint256 mintAmount) external payable returns (uint256); function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256); function depositAndStake(uint256 depositAmount, uint256 minTokenAmount) external payable returns (uint256); function depositFor(address account, uint256 depositAmount) external payable returns (uint256); function depositFor( address account, uint256 depositAmount, uint256 minTokenAmount ) external payable returns (uint256); function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount) external returns (uint256); function handleLpTokenTransfer( address from, address to, uint256 amount ) external; function executeNewVault() external returns (address); function executeNewMaxWithdrawalFee() external returns (uint256); function executeNewRequiredReserves() external returns (uint256); function executeNewReserveDeviation() external returns (uint256); function setLpToken(address _lpToken) external returns (bool); function setStaker() external returns (bool); function isCapped() external returns (bool); function uncap() external returns (bool); function updateDepositCap(uint256 _depositCap) external returns (bool); function getUnderlying() external view returns (address); function getLpToken() external view returns (address); function getWithdrawalFee(address account, uint256 amount) external view returns (uint256); function getVault() external view returns (IVault); function exchangeRate() external view returns (uint256); } // File interfaces/IGasBank.sol pragma solidity 0.8.9; interface IGasBank { event Deposit(address indexed account, uint256 value); event Withdraw(address indexed account, address indexed receiver, uint256 value); function depositFor(address account) external payable; function withdrawUnused(address account) external; function withdrawFrom(address account, uint256 amount) external; function withdrawFrom( address account, address payable to, uint256 amount ) external; function balanceOf(address account) external view returns (uint256); } // File interfaces/oracles/IOracleProvider.sol pragma solidity 0.8.9; interface IOracleProvider { /// @notice Quotes the USD price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the USD price of the asset function getPriceUSD(address baseAsset) external view returns (uint256); /// @notice Quotes the ETH price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the ETH price of the asset function getPriceETH(address baseAsset) external view returns (uint256); } // File libraries/AddressProviderMeta.sol pragma solidity 0.8.9; library AddressProviderMeta { struct Meta { bool freezable; bool frozen; } function fromUInt(uint256 value) internal pure returns (Meta memory) { Meta memory meta; meta.freezable = (value & 1) == 1; meta.frozen = ((value >> 1) & 1) == 1; return meta; } function toUInt(Meta memory meta) internal pure returns (uint256) { uint256 value; value |= meta.freezable ? 1 : 0; value |= meta.frozen ? 1 << 1 : 0; return value; } } // File interfaces/IAddressProvider.sol pragma solidity 0.8.9; // solhint-disable ordering interface IAddressProvider is IPreparable { event KnownAddressKeyAdded(bytes32 indexed key); event StakerVaultListed(address indexed stakerVault); event StakerVaultDelisted(address indexed stakerVault); event ActionListed(address indexed action); event PoolListed(address indexed pool); event PoolDelisted(address indexed pool); event VaultUpdated(address indexed previousVault, address indexed newVault); /** Key functions */ function getKnownAddressKeys() external view returns (bytes32[] memory); function freezeAddress(bytes32 key) external; /** Pool functions */ function allPools() external view returns (address[] memory); function addPool(address pool) external; function poolsCount() external view returns (uint256); function getPoolAtIndex(uint256 index) external view returns (address); function isPool(address pool) external view returns (bool); function removePool(address pool) external returns (bool); function getPoolForToken(address token) external view returns (ILiquidityPool); function safeGetPoolForToken(address token) external view returns (address); /** Vault functions */ function updateVault(address previousVault, address newVault) external; function allVaults() external view returns (address[] memory); function vaultsCount() external view returns (uint256); function getVaultAtIndex(uint256 index) external view returns (address); function isVault(address vault) external view returns (bool); /** Action functions */ function allActions() external view returns (address[] memory); function addAction(address action) external returns (bool); function isAction(address action) external view returns (bool); /** Address functions */ function initializeAddress( bytes32 key, address initialAddress, bool frezable ) external; function initializeAndFreezeAddress(bytes32 key, address initialAddress) external; function getAddress(bytes32 key) external view returns (address); function getAddress(bytes32 key, bool checkExists) external view returns (address); function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory); function prepareAddress(bytes32 key, address newAddress) external returns (bool); function executeAddress(bytes32 key) external returns (address); function resetAddress(bytes32 key) external returns (bool); /** Staker vault functions */ function allStakerVaults() external view returns (address[] memory); function tryGetStakerVault(address token) external view returns (bool, address); function getStakerVault(address token) external view returns (address); function addStakerVault(address stakerVault) external returns (bool); function isStakerVault(address stakerVault, address token) external view returns (bool); function isStakerVaultRegistered(address stakerVault) external view returns (bool); function isWhiteListedFeeHandler(address feeHandler) external view returns (bool); } // File interfaces/tokenomics/IInflationManager.sol pragma solidity 0.8.9; interface IInflationManager { event KeeperGaugeListed(address indexed pool, address indexed keeperGauge); event AmmGaugeListed(address indexed token, address indexed ammGauge); event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge); event AmmGaugeDelisted(address indexed token, address indexed ammGauge); /** Pool functions */ function setKeeperGauge(address pool, address _keeperGauge) external returns (bool); function setAmmGauge(address token, address _ammGauge) external returns (bool); function getAllAmmGauges() external view returns (address[] memory); function getLpRateForStakerVault(address stakerVault) external view returns (uint256); function getKeeperRateForPool(address pool) external view returns (uint256); function getAmmRateForToken(address token) external view returns (uint256); function getKeeperWeightForPool(address pool) external view returns (uint256); function getAmmWeightForToken(address pool) external view returns (uint256); function getLpPoolWeight(address pool) external view returns (uint256); function getKeeperGaugeForPool(address pool) external view returns (address); function getAmmGaugeForToken(address token) external view returns (address); function isInflationWeightManager(address account) external view returns (bool); function removeStakerVaultFromInflation(address stakerVault, address lpToken) external; function addGaugeForVault(address lpToken) external returns (bool); function whitelistGauge(address gauge) external; function checkpointAllGauges() external returns (bool); function mintRewards(address beneficiary, uint256 amount) external; function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool) external returns (bool); /** Weight setter functions **/ function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool); function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool); function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool); function executeLpPoolWeight(address lpToken) external returns (uint256); function executeAmmTokenWeight(address token) external returns (uint256); function executeKeeperPoolWeight(address pool) external returns (uint256); function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights) external returns (bool); function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights) external returns (bool); function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights) external returns (bool); function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool); function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool); function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool); } // File interfaces/IController.sol pragma solidity 0.8.9; // solhint-disable ordering interface IController is IPreparable { function addressProvider() external view returns (IAddressProvider); function inflationManager() external view returns (IInflationManager); function addStakerVault(address stakerVault) external returns (bool); function removePool(address pool) external returns (bool); /** Keeper functions */ function prepareKeeperRequiredStakedBKD(uint256 amount) external; function executeKeeperRequiredStakedBKD() external; function getKeeperRequiredStakedBKD() external view returns (uint256); function canKeeperExecuteAction(address keeper) external view returns (bool); /** Miscellaneous functions */ function getTotalEthRequiredForGas(address payer) external view returns (uint256); } // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, 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 interfaces/ILpToken.sol pragma solidity 0.8.9; interface ILpToken is IERC20Upgradeable { function mint(address account, uint256 lpTokens) external; function burn(address account, uint256 burnAmount) external returns (uint256); function burn(uint256 burnAmount) external; function minter() external view returns (address); function initialize( string memory name_, string memory symbol_, uint8 _decimals, address _minter ) external returns (bool); } // File interfaces/IStakerVault.sol pragma solidity 0.8.9; interface IStakerVault { event Staked(address indexed account, uint256 amount); event Unstaked(address indexed account, uint256 amount); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function initialize(address _token) external; function initializeLpGauge(address _lpGauge) external returns (bool); function stake(uint256 amount) external returns (bool); function stakeFor(address account, uint256 amount) external returns (bool); function unstake(uint256 amount) external returns (bool); function unstakeFor( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function transfer(address account, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function getToken() external view returns (address); function balanceOf(address account) external view returns (uint256); function stakedAndActionLockedBalanceOf(address account) external view returns (uint256); function actionLockedBalanceOf(address account) external view returns (uint256); function increaseActionLockedBalance(address account, uint256 amount) external returns (bool); function decreaseActionLockedBalance(address account, uint256 amount) external returns (bool); function getStakedByActions() external view returns (uint256); function addStrategy(address strategy) external returns (bool); function getPoolTotalStaked() external view returns (uint256); function prepareLpGauge(address _lpGauge) external returns (bool); function executeLpGauge() external returns (bool); function getLpGauge() external view returns (address); function poolCheckpoint() external returns (bool); function isStrategy(address user) external view returns (bool); } // File interfaces/IVaultReserve.sol pragma solidity 0.8.9; interface IVaultReserve { event Deposit(address indexed vault, address indexed token, uint256 amount); event Withdraw(address indexed vault, address indexed token, uint256 amount); event VaultListed(address indexed vault); function deposit(address token, uint256 amount) external payable returns (bool); function withdraw(address token, uint256 amount) external returns (bool); function getBalance(address vault, address token) external view returns (uint256); function canWithdraw(address vault) external view returns (bool); } // File interfaces/IRoleManager.sol pragma solidity 0.8.9; interface IRoleManager { event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, address account ) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, bytes32 role3, address account ) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } // File interfaces/tokenomics/IBkdToken.sol pragma solidity 0.8.9; interface IBkdToken is IERC20 { function mint(address account, uint256 amount) external; } // File libraries/AddressProviderKeys.sol pragma solidity 0.8.9; library AddressProviderKeys { bytes32 internal constant _TREASURY_KEY = "treasury"; bytes32 internal constant _GAS_BANK_KEY = "gasBank"; bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve"; bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry"; bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider"; bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory"; bytes32 internal constant _CONTROLLER_KEY = "controller"; bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker"; bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager"; } // File libraries/AddressProviderHelpers.sol pragma solidity 0.8.9; library AddressProviderHelpers { /** * @return The address of the treasury. */ function getTreasury(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._TREASURY_KEY); } /** * @return The gas bank. */ function getGasBank(IAddressProvider provider) internal view returns (IGasBank) { return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY)); } /** * @return The address of the vault reserve. */ function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) { return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY)); } /** * @return The address of the swapperRegistry. */ function getSwapperRegistry(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY); } /** * @return The oracleProvider. */ function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) { return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY)); } /** * @return the address of the BKD locker */ function getBKDLocker(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY); } /** * @return the address of the BKD locker */ function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) { return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY)); } /** * @return the controller */ function getController(IAddressProvider provider) internal view returns (IController) { return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY)); } } // File libraries/Errors.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Error { string internal constant ADDRESS_WHITELISTED = "address already whitelisted"; string internal constant ADMIN_ALREADY_SET = "admin has already been set once"; string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted"; string internal constant ADDRESS_NOT_FOUND = "address not found"; string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once"; string internal constant CONTRACT_PAUSED = "contract is paused"; string internal constant INVALID_AMOUNT = "invalid amount"; string internal constant INVALID_INDEX = "invalid index"; string internal constant INVALID_VALUE = "invalid msg.value"; string internal constant INVALID_SENDER = "invalid msg.sender"; string internal constant INVALID_TOKEN = "token address does not match pool's LP token address"; string internal constant INVALID_DECIMALS = "incorrect number of decimals"; string internal constant INVALID_ARGUMENT = "invalid argument"; string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted"; string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_POOL_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_LP_TOKEN_IMPLEMENTATION = "invalid LP Token implementation for given coin"; string internal constant INVALID_VAULT_IMPLEMENTATION = "invalid vault implementation for given coin"; string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION = "invalid stakerVault implementation for given coin"; string internal constant INSUFFICIENT_BALANCE = "insufficient balance"; string internal constant ADDRESS_ALREADY_SET = "Address is already set"; string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance"; string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received"; string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist"; string internal constant ADDRESS_FROZEN = "address is frozen"; string internal constant ROLE_EXISTS = "role already exists"; string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role"; string internal constant UNAUTHORIZED_ACCESS = "unauthorized access"; string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed"; string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed"; string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed"; string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed"; string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10"; string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold"; string internal constant NO_POSITION_EXISTS = "no position exists"; string internal constant POSITION_ALREADY_EXISTS = "position already exists"; string internal constant PROTOCOL_NOT_FOUND = "protocol not found"; string internal constant TOP_UP_FAILED = "top up failed"; string internal constant SWAP_PATH_NOT_FOUND = "swap path not found"; string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported"; string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN = "not enough funds were withdrawn from the pool"; string internal constant FAILED_TRANSFER = "transfer failed"; string internal constant FAILED_MINT = "mint failed"; string internal constant FAILED_REPAY_BORROW = "repay borrow failed"; string internal constant FAILED_METHOD_CALL = "method call failed"; string internal constant NOTHING_TO_CLAIM = "there is no claimable balance"; string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance"; string internal constant INVALID_MINTER = "the minter address of the LP token and the pool address do not match"; string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token"; string internal constant DEADLINE_NOT_ZERO = "deadline must be 0"; string internal constant DEADLINE_NOT_SET = "deadline is 0"; string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet"; string internal constant DELAY_TOO_SHORT = "delay be at least 3 days"; string internal constant INSUFFICIENT_UPDATE_BALANCE = "insufficient funds for updating the position"; string internal constant SAME_AS_CURRENT = "value must be different to existing value"; string internal constant NOT_CAPPED = "the pool is not currently capped"; string internal constant ALREADY_CAPPED = "the pool is already capped"; string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap"; string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas"; string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw"; string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas"; string internal constant DEPOSIT_FAILED = "deposit failed"; string internal constant GAS_TOO_HIGH = "too much ETH used for gas"; string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas"; string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add"; string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed"; string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet"; string internal constant UNDERLYING_NOT_WITHDRAWABLE = "pool does not support additional underlying coins to be withdrawn"; string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down"; string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist"; string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported"; string internal constant NO_DEX_SET = "no dex has been set for token"; string internal constant INVALID_TOKEN_PAIR = "invalid token pair"; string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action"; string internal constant ADDRESS_NOT_ACTION = "address is not registered action"; string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance"; string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve"; string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block"; string internal constant GAUGE_EXISTS = "Gauge already exists"; string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist"; string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex"; string internal constant PREPARED_WITHDRAWAL = "Cannot relock funds when withdrawal is being prepared"; string internal constant ASSET_NOT_SUPPORTED = "Asset not supported"; string internal constant STALE_PRICE = "Price is stale"; string internal constant NEGATIVE_PRICE = "Price is negative"; string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked"; string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded"; } // File libraries/ScaledMath.sol pragma solidity 0.8.9; /* * @dev To use functions of this contract, at least one of the numbers must * be scaled to `DECIMAL_SCALE`. The result will scaled to `DECIMAL_SCALE` * if both numbers are scaled to `DECIMAL_SCALE`, otherwise to the scale * of the number not scaled by `DECIMAL_SCALE` */ library ScaledMath { // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant DECIMAL_SCALE = 1e18; // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant ONE = 1e18; /** * @notice Performs a multiplication between two scaled numbers */ function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) { return (a * b) / DECIMAL_SCALE; } /** * @notice Performs a division between two scaled numbers */ function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE) / b; } /** * @notice Performs a division between two numbers, rounding up the result */ function scaledDivRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE + b - 1) / b; } /** * @notice Performs a division between two numbers, ignoring any scaling and rounding up the result */ function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a + b - 1) / b; } } // File libraries/Roles.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Roles { bytes32 internal constant GOVERNANCE = "governance"; bytes32 internal constant ADDRESS_PROVIDER = "address_provider"; bytes32 internal constant POOL_FACTORY = "pool_factory"; bytes32 internal constant CONTROLLER = "controller"; bytes32 internal constant GAUGE_ZAP = "gauge_zap"; bytes32 internal constant MAINTENANCE = "maintenance"; bytes32 internal constant INFLATION_MANAGER = "inflation_manager"; bytes32 internal constant POOL = "pool"; bytes32 internal constant VAULT = "vault"; } // File contracts/access/AuthorizationBase.sol pragma solidity 0.8.9; /** * @notice Provides modifiers for authorization */ abstract contract AuthorizationBase { /** * @notice Only allows a sender with `role` to perform the given action */ modifier onlyRole(bytes32 role) { require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with GOVERNANCE role to perform the given action */ modifier onlyGovernance() { require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles2(bytes32 role1, bytes32 role2) { require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles3( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _roleManager().hasAnyRole(role1, role2, role3, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } function roleManager() external view virtual returns (IRoleManager) { return _roleManager(); } function _roleManager() internal view virtual returns (IRoleManager); } // File contracts/access/Authorization.sol pragma solidity 0.8.9; contract Authorization is AuthorizationBase { IRoleManager internal immutable __roleManager; constructor(IRoleManager roleManager) { __roleManager = roleManager; } function _roleManager() internal view override returns (IRoleManager) { return __roleManager; } } // File contracts/utils/Preparable.sol pragma solidity 0.8.9; /** * @notice Implements the base logic for a two-phase commit * @dev This does not implements any access-control so publicly exposed * callers should make sure to have the proper checks in palce */ contract Preparable is IPreparable { uint256 private constant _MIN_DELAY = 3 days; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingUInts256; mapping(bytes32 => address) public currentAddresses; mapping(bytes32 => uint256) public currentUInts256; /** * @dev Deadlines shares the same namespace regardless of the type * of the pending variable so this needs to be enforced in the caller */ mapping(bytes32 => uint256) public deadlines; function _prepareDeadline(bytes32 key, uint256 delay) internal { require(deadlines[key] == 0, Error.DEADLINE_NOT_ZERO); require(delay >= _MIN_DELAY, Error.DELAY_TOO_SHORT); deadlines[key] = block.timestamp + delay; } /** * @notice Prepares an uint256 that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, uint256 value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingUInts256[key] = value; emit ConfigPreparedNumber(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,uint256,uint256)` but uses a default delay */ function _prepare(bytes32 key, uint256 value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Prepares an address that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, address value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingAddresses[key] = value; emit ConfigPreparedAddress(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,address,uint256)` but uses a default delay */ function _prepare(bytes32 key, address value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Reset a uint256 key * @return `true` if success. */ function _resetUInt256Config(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingUInts256[key] = 0; emit ConfigReset(key); return true; } /** * @notice Reset an address key * @return `true` if success. */ function _resetAddressConfig(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingAddresses[key] = address(0); emit ConfigReset(key); return true; } /** * @dev Checks the deadline of the key and reset it */ function _executeDeadline(bytes32 key) internal { uint256 deadline = deadlines[key]; require(block.timestamp >= deadline, Error.DEADLINE_NOT_REACHED); require(deadline != 0, Error.DEADLINE_NOT_SET); deadlines[key] = 0; } /** * @notice Execute uint256 config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeUInt256(bytes32 key) internal returns (uint256) { _executeDeadline(key); uint256 newValue = pendingUInts256[key]; _setConfig(key, newValue); return newValue; } /** * @notice Execute address config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeAddress(bytes32 key) internal returns (address) { _executeDeadline(key); address newValue = pendingAddresses[key]; _setConfig(key, newValue); return newValue; } function _setConfig(bytes32 key, address value) internal returns (address) { address oldValue = currentAddresses[key]; currentAddresses[key] = value; pendingAddresses[key] = address(0); deadlines[key] = 0; emit ConfigUpdatedAddress(key, oldValue, value); return value; } function _setConfig(bytes32 key, uint256 value) internal returns (uint256) { uint256 oldValue = currentUInts256[key]; currentUInts256[key] = value; pendingUInts256[key] = 0; deadlines[key] = 0; emit ConfigUpdatedNumber(key, oldValue, value); return value; } } // File contracts/utils/Pausable.sol pragma solidity 0.8.9; abstract contract Pausable { bool public isPaused; modifier notPaused() { require(!isPaused, Error.CONTRACT_PAUSED); _; } modifier onlyAuthorizedToPause() { require(_isAuthorizedToPause(msg.sender), Error.CONTRACT_PAUSED); _; } /** * @notice Pause the contract. * @return `true` if success. */ function pause() external onlyAuthorizedToPause returns (bool) { isPaused = true; return true; } /** * @notice Unpause the contract. * @return `true` if success. */ function unpause() external onlyAuthorizedToPause returns (bool) { isPaused = false; return true; } /** * @notice Returns true if `account` is authorized to pause the contract * @dev This should be implemented in contracts inheriting `Pausable` * to provide proper access control */ function _isAuthorizedToPause(address account) internal view virtual returns (bool); } // File contracts/pool/LiquidityPool.sol pragma solidity 0.8.9; /** * @dev Pausing/unpausing the pool will disable/re-enable deposits. */ abstract contract LiquidityPool is ILiquidityPool, Authorization, Preparable, Pausable, Initializable { using AddressProviderHelpers for IAddressProvider; using ScaledMath for uint256; using SafeERC20 for IERC20; struct WithdrawalFeeMeta { uint64 timeToWait; uint64 feeRatio; uint64 lastActionTimestamp; } bytes32 internal constant _VAULT_KEY = "Vault"; bytes32 internal constant _RESERVE_DEVIATION_KEY = "ReserveDeviation"; bytes32 internal constant _REQUIRED_RESERVES_KEY = "RequiredReserves"; bytes32 internal constant _MAX_WITHDRAWAL_FEE_KEY = "MaxWithdrawalFee"; bytes32 internal constant _MIN_WITHDRAWAL_FEE_KEY = "MinWithdrawalFee"; bytes32 internal constant _WITHDRAWAL_FEE_DECREASE_PERIOD_KEY = "WithdrawalFeeDecreasePeriod"; uint256 internal constant _INITIAL_RESERVE_DEVIATION = 0.005e18; // 0.5% uint256 internal constant _INITIAL_FEE_DECREASE_PERIOD = 1 weeks; uint256 internal constant _INITIAL_MAX_WITHDRAWAL_FEE = 0.03e18; // 3% /** * @notice even through admin votes and later governance, the withdrawal * fee will never be able to go above this value */ uint256 internal constant _MAX_WITHDRAWAL_FEE = 0.05e18; /** * @notice Keeps track of the withdrawal fees on a per-address basis */ mapping(address => WithdrawalFeeMeta) public withdrawalFeeMetas; IController public immutable controller; IAddressProvider public immutable addressProvider; uint256 public depositCap; IStakerVault public staker; ILpToken public lpToken; string public name; constructor(IController _controller) Authorization(_controller.addressProvider().getRoleManager()) { require(address(_controller) != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); controller = IController(_controller); addressProvider = IController(_controller).addressProvider(); } /** * @notice Deposit funds into liquidity pool and mint LP tokens in exchange. * @param depositAmount Amount of the underlying asset to supply. * @return The actual amount minted. */ function deposit(uint256 depositAmount) external payable override returns (uint256) { return depositFor(msg.sender, depositAmount, 0); } /** * @notice Deposit funds into liquidity pool and mint LP tokens in exchange. * @param depositAmount Amount of the underlying asset to supply. * @param minTokenAmount Minimum amount of LP tokens that should be minted. * @return The actual amount minted. */ function deposit(uint256 depositAmount, uint256 minTokenAmount) external payable override returns (uint256) { return depositFor(msg.sender, depositAmount, minTokenAmount); } /** * @notice Deposit funds into liquidity pool and stake LP Tokens in Staker Vault. * @param depositAmount Amount of the underlying asset to supply. * @param minTokenAmount Minimum amount of LP tokens that should be minted. * @return The actual amount minted and staked. */ function depositAndStake(uint256 depositAmount, uint256 minTokenAmount) external payable override returns (uint256) { uint256 amountMinted_ = depositFor(address(this), depositAmount, minTokenAmount); staker.stakeFor(msg.sender, amountMinted_); return amountMinted_; } /** * @notice Withdraws all funds from vault. * @dev Should be called in case of emergencies. */ function withdrawAll() external onlyGovernance { getVault().withdrawAll(); } function setLpToken(address _lpToken) external override onlyRoles2(Roles.GOVERNANCE, Roles.POOL_FACTORY) returns (bool) { require(address(lpToken) == address(0), Error.ADDRESS_ALREADY_SET); require(ILpToken(_lpToken).minter() == address(this), Error.INVALID_MINTER); lpToken = ILpToken(_lpToken); _approveStakerVaultSpendingLpTokens(); emit LpTokenSet(_lpToken); return true; } /** * @notice Checkpoint function to update a user's withdrawal fees on deposit and redeem * @param from Address sending from * @param to Address sending to * @param amount Amount to redeem or deposit */ function handleLpTokenTransfer( address from, address to, uint256 amount ) external override { require( msg.sender == address(lpToken) || msg.sender == address(staker), Error.UNAUTHORIZED_ACCESS ); if ( addressProvider.isStakerVault(to, address(lpToken)) || addressProvider.isStakerVault(from, address(lpToken)) || addressProvider.isAction(to) || addressProvider.isAction(from) ) { return; } if (to != address(0)) { _updateUserFeesOnDeposit(to, from, amount); } } /** * @notice Prepare update of required reserve ratio (with time delay enforced). * @param _newRatio New required reserve ratio. * @return `true` if success. */ function prepareNewRequiredReserves(uint256 _newRatio) external onlyGovernance returns (bool) { require(_newRatio <= ScaledMath.ONE, Error.INVALID_AMOUNT); return _prepare(_REQUIRED_RESERVES_KEY, _newRatio); } /** * @notice Execute required reserve ratio update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New required reserve ratio. */ function executeNewRequiredReserves() external override returns (uint256) { uint256 requiredReserveRatio = _executeUInt256(_REQUIRED_RESERVES_KEY); _rebalanceVault(); return requiredReserveRatio; } /** * @notice Reset the prepared required reserves. * @return `true` if success. */ function resetRequiredReserves() external onlyGovernance returns (bool) { return _resetUInt256Config(_REQUIRED_RESERVES_KEY); } /** * @notice Prepare update of reserve deviation ratio (with time delay enforced). * @param newRatio New reserve deviation ratio. * @return `true` if success. */ function prepareNewReserveDeviation(uint256 newRatio) external onlyGovernance returns (bool) { require(newRatio <= (ScaledMath.DECIMAL_SCALE * 50) / 100, Error.INVALID_AMOUNT); return _prepare(_RESERVE_DEVIATION_KEY, newRatio); } /** * @notice Execute reserve deviation ratio update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New reserve deviation ratio. */ function executeNewReserveDeviation() external override returns (uint256) { uint256 reserveDeviation = _executeUInt256(_RESERVE_DEVIATION_KEY); _rebalanceVault(); return reserveDeviation; } /** * @notice Reset the prepared reserve deviation. * @return `true` if success. */ function resetNewReserveDeviation() external onlyGovernance returns (bool) { return _resetUInt256Config(_RESERVE_DEVIATION_KEY); } /** * @notice Prepare update of min withdrawal fee (with time delay enforced). * @param newFee New min withdrawal fee. * @return `true` if success. */ function prepareNewMinWithdrawalFee(uint256 newFee) external onlyGovernance returns (bool) { _checkFeeInvariants(newFee, getMaxWithdrawalFee()); return _prepare(_MIN_WITHDRAWAL_FEE_KEY, newFee); } /** * @notice Execute min withdrawal fee update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New withdrawal fee. */ function executeNewMinWithdrawalFee() external returns (uint256) { uint256 newFee = _executeUInt256(_MIN_WITHDRAWAL_FEE_KEY); _checkFeeInvariants(newFee, getMaxWithdrawalFee()); return newFee; } /** * @notice Reset the prepared min withdrawal fee * @return `true` if success. */ function resetNewMinWithdrawalFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_MIN_WITHDRAWAL_FEE_KEY); } /** * @notice Prepare update of max withdrawal fee (with time delay enforced). * @param newFee New max withdrawal fee. * @return `true` if success. */ function prepareNewMaxWithdrawalFee(uint256 newFee) external onlyGovernance returns (bool) { _checkFeeInvariants(getMinWithdrawalFee(), newFee); return _prepare(_MAX_WITHDRAWAL_FEE_KEY, newFee); } /** * @notice Execute max withdrawal fee update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New max withdrawal fee. */ function executeNewMaxWithdrawalFee() external override returns (uint256) { uint256 newFee = _executeUInt256(_MAX_WITHDRAWAL_FEE_KEY); _checkFeeInvariants(getMinWithdrawalFee(), newFee); return newFee; } /** * @notice Reset the prepared max fee. * @return `true` if success. */ function resetNewMaxWithdrawalFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_MAX_WITHDRAWAL_FEE_KEY); } /** * @notice Prepare update of withdrawal decrease fee period (with time delay enforced). * @param newPeriod New withdrawal fee decrease period. * @return `true` if success. */ function prepareNewWithdrawalFeeDecreasePeriod(uint256 newPeriod) external onlyGovernance returns (bool) { return _prepare(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY, newPeriod); } /** * @notice Execute withdrawal fee decrease period update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New withdrawal fee decrease period. */ function executeNewWithdrawalFeeDecreasePeriod() external returns (uint256) { return _executeUInt256(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY); } /** * @notice Reset the prepared withdrawal fee decrease period update. * @return `true` if success. */ function resetNewWithdrawalFeeDecreasePeriod() external onlyGovernance returns (bool) { return _resetUInt256Config(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY); } /** * @notice Set the staker vault for this pool's LP token * @dev Staker vault and LP token pairs are immutable and the staker vault can only be set once for a pool. * Only one vault exists per LP token. This information will be retrieved from the controller of the pool. * @return Address of the new staker vault for the pool. */ function setStaker() external override onlyRoles2(Roles.GOVERNANCE, Roles.POOL_FACTORY) returns (bool) { require(address(staker) == address(0), Error.ADDRESS_ALREADY_SET); address stakerVault = addressProvider.getStakerVault(address(lpToken)); require(stakerVault != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); staker = IStakerVault(stakerVault); _approveStakerVaultSpendingLpTokens(); emit StakerVaultSet(stakerVault); return true; } /** * @notice Prepare setting a new Vault (with time delay enforced). * @param _vault Address of new Vault contract. * @return `true` if success. */ function prepareNewVault(address _vault) external onlyGovernance returns (bool) { _prepare(_VAULT_KEY, _vault); return true; } /** * @notice Execute Vault update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return Address of new Vault contract. */ function executeNewVault() external override returns (address) { IVault vault = getVault(); if (address(vault) != address(0)) { vault.withdrawAll(); } address newVault = _executeAddress(_VAULT_KEY); addressProvider.updateVault(address(vault), newVault); return newVault; } /** * @notice Reset the vault deadline. * @return `true` if success. */ function resetNewVault() external onlyGovernance returns (bool) { return _resetAddressConfig(_VAULT_KEY); } /** * @notice Redeems the underlying asset by burning LP tokens. * @param redeemLpTokens Number of tokens to burn for redeeming the underlying. * @return Actual amount of the underlying redeemed. */ function redeem(uint256 redeemLpTokens) external override returns (uint256) { return redeem(redeemLpTokens, 0); } /** * @notice Uncap the pool to remove the deposit limit. * @return `true` if success. */ function uncap() external override onlyGovernance returns (bool) { require(isCapped(), Error.NOT_CAPPED); depositCap = 0; return true; } /** * @notice Update the deposit cap value. * @param _depositCap The maximum allowed deposits per address in the pool * @return `true` if success. */ function updateDepositCap(uint256 _depositCap) external override onlyGovernance returns (bool) { require(isCapped(), Error.NOT_CAPPED); require(depositCap != _depositCap, Error.SAME_AS_CURRENT); require(_depositCap > 0, Error.INVALID_AMOUNT); depositCap = _depositCap; return true; } /** * @notice Rebalance vault according to required underlying backing reserves. */ function rebalanceVault() external onlyGovernance { _rebalanceVault(); } /** * @notice Deposit funds for an address into liquidity pool and mint LP tokens in exchange. * @param account Account to deposit for. * @param depositAmount Amount of the underlying asset to supply. * @return Actual amount minted. */ function depositFor(address account, uint256 depositAmount) external payable override returns (uint256) { return depositFor(account, depositAmount, 0); } /** * @notice Redeems the underlying asset by burning LP tokens, unstaking any LP tokens needed. * @param redeemLpTokens Number of tokens to unstake and/or burn for redeeming the underlying. * @param minRedeemAmount Minimum amount of underlying that should be received. * @return Actual amount of the underlying redeemed. */ function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount) external override returns (uint256) { uint256 lpBalance_ = lpToken.balanceOf(msg.sender); require( lpBalance_ + staker.balanceOf(msg.sender) >= redeemLpTokens, Error.INSUFFICIENT_BALANCE ); if (lpBalance_ < redeemLpTokens) { staker.unstakeFor(msg.sender, msg.sender, redeemLpTokens - lpBalance_); } return redeem(redeemLpTokens, minRedeemAmount); } /** * @notice Returns the address of the LP token of this pool * @return The address of the LP token */ function getLpToken() external view override returns (address) { return address(lpToken); } /** * @notice Calculates the amount of LP tokens that need to be redeemed to get a certain amount of underlying (includes fees and exchange rate) * @param account Address of the account redeeming. * @param underlyingAmount The amount of underlying desired. * @return Amount of LP tokens that need to be redeemed. */ function calcRedeem(address account, uint256 underlyingAmount) external view override returns (uint256) { require(underlyingAmount > 0, Error.INVALID_AMOUNT); ILpToken lpToken_ = lpToken; require(lpToken_.balanceOf(account) > 0, Error.INSUFFICIENT_BALANCE); uint256 currentExchangeRate = exchangeRate(); uint256 withoutFeesLpAmount = underlyingAmount.scaledDiv(currentExchangeRate); if (withoutFeesLpAmount == lpToken_.totalSupply()) { return withoutFeesLpAmount; } WithdrawalFeeMeta memory meta = withdrawalFeeMetas[account]; uint256 currentFeeRatio = 0; if (!addressProvider.isAction(account)) { currentFeeRatio = getNewCurrentFees( meta.timeToWait, meta.lastActionTimestamp, meta.feeRatio ); } uint256 scalingFactor = currentExchangeRate.scaledMul((ScaledMath.ONE - currentFeeRatio)); uint256 neededLpTokens = underlyingAmount.scaledDivRoundUp(scalingFactor); return neededLpTokens; } function getUnderlying() external view virtual override returns (address); /** * @notice Deposit funds for an address into liquidity pool and mint LP tokens in exchange. * @param account Account to deposit for. * @param depositAmount Amount of the underlying asset to supply. * @param minTokenAmount Minimum amount of LP tokens that should be minted. * @return Actual amount minted. */ function depositFor( address account, uint256 depositAmount, uint256 minTokenAmount ) public payable override notPaused returns (uint256) { uint256 rate = exchangeRate(); if (isCapped()) { uint256 lpBalance = lpToken.balanceOf(account); uint256 stakedAndLockedBalance = staker.stakedAndActionLockedBalanceOf(account); uint256 currentUnderlyingBalance = (lpBalance + stakedAndLockedBalance).scaledMul(rate); require( currentUnderlyingBalance + depositAmount <= depositCap, Error.EXCEEDS_DEPOSIT_CAP ); } _doTransferIn(msg.sender, depositAmount); uint256 mintedLp = depositAmount.scaledDiv(rate); require(mintedLp >= minTokenAmount, Error.INVALID_AMOUNT); lpToken.mint(account, mintedLp); _rebalanceVault(); if (msg.sender == account || address(this) == account) { emit Deposit(msg.sender, depositAmount, mintedLp); } else { emit DepositFor(msg.sender, account, depositAmount, mintedLp); } return mintedLp; } /** * @notice Redeems the underlying asset by burning LP tokens. * @param redeemLpTokens Number of tokens to burn for redeeming the underlying. * @param minRedeemAmount Minimum amount of underlying that should be received. * @return Actual amount of the underlying redeemed. */ function redeem(uint256 redeemLpTokens, uint256 minRedeemAmount) public override returns (uint256) { require(redeemLpTokens > 0, Error.INVALID_AMOUNT); ILpToken lpToken_ = lpToken; require(lpToken_.balanceOf(msg.sender) >= redeemLpTokens, Error.INSUFFICIENT_BALANCE); uint256 withdrawalFee = addressProvider.isAction(msg.sender) ? 0 : getWithdrawalFee(msg.sender, redeemLpTokens); uint256 redeemMinusFees = redeemLpTokens - withdrawalFee; // Pay no fees on the last withdrawal (avoid locking funds in the pool) if (redeemLpTokens == lpToken_.totalSupply()) { redeemMinusFees = redeemLpTokens; } uint256 redeemUnderlying = redeemMinusFees.scaledMul(exchangeRate()); require(redeemUnderlying >= minRedeemAmount, Error.NOT_ENOUGH_FUNDS_WITHDRAWN); _rebalanceVault(redeemUnderlying); lpToken_.burn(msg.sender, redeemLpTokens); _doTransferOut(payable(msg.sender), redeemUnderlying); emit Redeem(msg.sender, redeemUnderlying, redeemLpTokens); return redeemUnderlying; } /** * @return the current required reserves ratio */ function getRequiredReserveRatio() public view virtual returns (uint256) { return currentUInts256[_REQUIRED_RESERVES_KEY]; } /** * @return the current maximum reserve deviation ratio */ function getMaxReserveDeviationRatio() public view virtual returns (uint256) { return currentUInts256[_RESERVE_DEVIATION_KEY]; } /** * @notice Returns the current minimum withdrawal fee */ function getMinWithdrawalFee() public view returns (uint256) { return currentUInts256[_MIN_WITHDRAWAL_FEE_KEY]; } /** * @notice Returns the current maximum withdrawal fee */ function getMaxWithdrawalFee() public view returns (uint256) { return currentUInts256[_MAX_WITHDRAWAL_FEE_KEY]; } /** * @notice Returns the current withdrawal fee decrease period */ function getWithdrawalFeeDecreasePeriod() public view returns (uint256) { return currentUInts256[_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY]; } /** * @return the current vault of the liquidity pool */ function getVault() public view virtual override returns (IVault) { return IVault(currentAddresses[_VAULT_KEY]); } /** * @notice Compute current exchange rate of LP tokens to underlying scaled to 1e18. * @dev Exchange rate means: underlying = LP token * exchangeRate * @return Current exchange rate. */ function exchangeRate() public view override returns (uint256) { uint256 totalUnderlying_ = totalUnderlying(); uint256 totalSupply = lpToken.totalSupply(); if (totalSupply == 0 || totalUnderlying_ == 0) { return ScaledMath.ONE; } return totalUnderlying_.scaledDiv(totalSupply); } /** * @notice Compute total amount of underlying tokens for this pool. * @return Total amount of underlying in pool. */ function totalUnderlying() public view returns (uint256) { IVault vault = getVault(); uint256 balanceUnderlying = _getBalanceUnderlying(); if (address(vault) == address(0)) { return balanceUnderlying; } uint256 investedUnderlying = vault.getTotalUnderlying(); return investedUnderlying + balanceUnderlying; } /** * @notice Retuns if the pool has an active deposit limit * @return `true` if there is currently a deposit limit */ function isCapped() public view override returns (bool) { return depositCap != 0; } /** * @notice Returns the withdrawal fee for `account` * @param account Address to get the withdrawal fee for * @param amount Amount to calculate the withdrawal fee for * @return Withdrawal fee in LP tokens */ function getWithdrawalFee(address account, uint256 amount) public view override returns (uint256) { WithdrawalFeeMeta memory meta = withdrawalFeeMetas[account]; if (lpToken.balanceOf(account) == 0) { return 0; } uint256 currentFee = getNewCurrentFees( meta.timeToWait, meta.lastActionTimestamp, meta.feeRatio ); return amount.scaledMul(currentFee); } /** * @notice Calculates the withdrawal fee a user would currently need to pay on currentBalance. * @param timeToWait The total time to wait until the withdrawal fee reached the min. fee * @param lastActionTimestamp Timestamp of the last fee update * @param feeRatio Fees that would currently be paid on the user's entire balance * @return Updated fee amount on the currentBalance */ function getNewCurrentFees( uint256 timeToWait, uint256 lastActionTimestamp, uint256 feeRatio ) public view returns (uint256) { uint256 timeElapsed = _getTime() - lastActionTimestamp; uint256 minFeePercentage = getMinWithdrawalFee(); if (timeElapsed >= timeToWait) { return minFeePercentage; } uint256 elapsedShare = timeElapsed.scaledDiv(timeToWait); return feeRatio - (feeRatio - minFeePercentage).scaledMul(elapsedShare); } function _rebalanceVault() internal { _rebalanceVault(0); } function _initialize( string memory name_, uint256 depositCap_, address vault_ ) internal initializer returns (bool) { name = name_; depositCap = depositCap_; _setConfig(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY, _INITIAL_FEE_DECREASE_PERIOD); _setConfig(_MAX_WITHDRAWAL_FEE_KEY, _INITIAL_MAX_WITHDRAWAL_FEE); _setConfig(_REQUIRED_RESERVES_KEY, ScaledMath.ONE); _setConfig(_RESERVE_DEVIATION_KEY, _INITIAL_RESERVE_DEVIATION); _setConfig(_VAULT_KEY, vault_); return true; } function _approveStakerVaultSpendingLpTokens() internal { address staker_ = address(staker); address lpToken_ = address(lpToken); if (staker_ == address(0) || lpToken_ == address(0)) return; IERC20(lpToken_).safeApprove(staker_, type(uint256).max); } function _doTransferIn(address from, uint256 amount) internal virtual; function _doTransferOut(address payable to, uint256 amount) internal virtual; /** * @dev Rebalances the pool's allocations to the vault * @param underlyingToWithdraw Amount of underlying to withdraw such that after the withdrawal the pool and vault allocations are correctly balanced. */ function _rebalanceVault(uint256 underlyingToWithdraw) internal { IVault vault = getVault(); if (address(vault) == address(0)) return; uint256 lockedLp = staker.getStakedByActions(); uint256 totalUnderlyingStaked = lockedLp.scaledMul(exchangeRate()); uint256 underlyingBalance = _getBalanceUnderlying(true); uint256 maximumDeviation = totalUnderlyingStaked.scaledMul(getMaxReserveDeviationRatio()); uint256 nextTargetBalance = totalUnderlyingStaked.scaledMul(getRequiredReserveRatio()); if ( underlyingToWithdraw > underlyingBalance || (underlyingBalance - underlyingToWithdraw) + maximumDeviation < nextTargetBalance ) { uint256 requiredDeposits = nextTargetBalance + underlyingToWithdraw - underlyingBalance; vault.withdraw(requiredDeposits); } else { uint256 nextBalance = underlyingBalance - underlyingToWithdraw; if (nextBalance > nextTargetBalance + maximumDeviation) { uint256 excessDeposits = nextBalance - nextTargetBalance; _doTransferOut(payable(address(vault)), excessDeposits); vault.deposit(); } } } function _updateUserFeesOnDeposit( address account, address from, uint256 amountAdded ) internal { WithdrawalFeeMeta storage meta = withdrawalFeeMetas[account]; uint256 balance = lpToken.balanceOf(account) + staker.stakedAndActionLockedBalanceOf(account); uint256 newCurrentFeeRatio = getNewCurrentFees( meta.timeToWait, meta.lastActionTimestamp, meta.feeRatio ); uint256 shareAdded = amountAdded.scaledDiv(amountAdded + balance); uint256 shareExisting = ScaledMath.ONE - shareAdded; uint256 feeOnDeposit; if (from == address(0)) { feeOnDeposit = getMaxWithdrawalFee(); } else { WithdrawalFeeMeta storage fromMeta = withdrawalFeeMetas[from]; feeOnDeposit = getNewCurrentFees( fromMeta.timeToWait, fromMeta.lastActionTimestamp, fromMeta.feeRatio ); } uint256 newFeeRatio = shareExisting.scaledMul(newCurrentFeeRatio) + shareAdded.scaledMul(feeOnDeposit); meta.feeRatio = uint64(newFeeRatio); meta.timeToWait = uint64(getWithdrawalFeeDecreasePeriod()); meta.lastActionTimestamp = uint64(_getTime()); } function _getBalanceUnderlying() internal view virtual returns (uint256); function _getBalanceUnderlying(bool transferInDone) internal view virtual returns (uint256); function _isAuthorizedToPause(address account) internal view override returns (bool) { return _roleManager().hasRole(Roles.GOVERNANCE, account); } /** * @dev Overriden for testing */ function _getTime() internal view virtual returns (uint256) { return block.timestamp; } function _checkFeeInvariants(uint256 minFee, uint256 maxFee) internal pure { require(maxFee >= minFee, Error.INVALID_AMOUNT); require(maxFee <= _MAX_WITHDRAWAL_FEE, Error.INVALID_AMOUNT); } } // File interfaces/pool/IErc20Pool.sol pragma solidity 0.8.9; interface IErc20Pool { function initialize( string memory name_, address underlying_, uint256 depositCap_, address vault_ ) external returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // File contracts/pool/Erc20Pool.sol pragma solidity 0.8.9; contract Erc20Pool is LiquidityPool, IErc20Pool { using SafeERC20 for IERC20; address private _underlying; constructor(IController _controller) LiquidityPool(_controller) {} function initialize( string memory name_, address underlying_, uint256 depositCap_, address vault_ ) public override returns (bool) { require(underlying_ != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); _underlying = underlying_; return _initialize(name_, depositCap_, vault_); } function getUnderlying() public view override returns (address) { return _underlying; } function _doTransferIn(address from, uint256 amount) internal override { require(msg.value == 0, Error.INVALID_VALUE); IERC20(_underlying).safeTransferFrom(from, address(this), amount); } function _doTransferOut(address payable to, uint256 amount) internal override { IERC20(_underlying).safeTransfer(to, amount); } function _getBalanceUnderlying() internal view override returns (uint256) { return IERC20(_underlying).balanceOf(address(this)); } function _getBalanceUnderlying(bool) internal view override returns (uint256) { return _getBalanceUnderlying(); } }
* @notice Compute total amount of underlying tokens for this pool. @return Total amount of underlying in pool./
function totalUnderlying() public view returns (uint256) { IVault vault = getVault(); uint256 balanceUnderlying = _getBalanceUnderlying(); if (address(vault) == address(0)) { return balanceUnderlying; } uint256 investedUnderlying = vault.getTotalUnderlying(); return investedUnderlying + balanceUnderlying; }
10,436,111
[ 1, 7018, 2078, 3844, 434, 6808, 2430, 364, 333, 2845, 18, 327, 10710, 3844, 434, 6808, 316, 2845, 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 ]
[ 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, 565, 445, 2078, 14655, 6291, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 467, 12003, 9229, 273, 11031, 3714, 5621, 203, 3639, 2254, 5034, 11013, 14655, 6291, 273, 389, 588, 13937, 14655, 6291, 5621, 203, 3639, 309, 261, 2867, 12, 26983, 13, 422, 1758, 12, 20, 3719, 288, 203, 5411, 327, 11013, 14655, 6291, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 2198, 3149, 14655, 6291, 273, 9229, 18, 588, 5269, 14655, 6291, 5621, 203, 3639, 327, 2198, 3149, 14655, 6291, 397, 11013, 14655, 6291, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 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 Required interface of an ERC721 compliant contract. */ interface IERC721 { /** * @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; } interface IVaultConfig { function fee() external view returns (uint256); function gasLimit() external view returns (uint256); function ownerReward() external view returns (uint256); } /* * @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 returns (address) { 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; } function _msgValue() internal view returns (uint256) { return msg.value; } } /** * @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; address private _newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor (address owner_) { _owner = owner_; 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(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Accept the ownership transfer. This is to make sure that the contract is * transferred to a working address * * Can only be called by the newly transfered owner. */ function acceptOwnership() public { require(_msgSender() == _newOwner, "Ownable: only new owner can accept ownership"); address oldOwner = _owner; _owner = _newOwner; _newOwner = address(0); emit OwnershipTransferred(oldOwner, _owner); } /** * @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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); _newOwner = newOwner; } } /** * @dev Enable contract to receive gas token */ abstract contract Payable { event Deposited(address indexed sender, uint256 value); fallback() external payable { if(msg.value > 0) { emit Deposited(msg.sender, msg.value); } } /// @dev enable wallet to receive ETH receive() external payable { if(msg.value > 0) { emit Deposited(msg.sender, msg.value); } } } /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } /** * @dev Coin98Vault contract to enable vesting funds to investors */ contract Coin98Vault is Ownable, Payable { address private _factory; address[] private _admins; mapping(address => bool) private _adminStatuses; mapping(uint256 => EventData) private _eventDatas; mapping(uint256 => mapping(uint256 => bool)) private _eventRedemptions; /// @dev Initialize a new vault /// @param factory_ Back reference to the factory initialized this vault for global configuration /// @param owner_ Owner of this vault constructor(address factory_, address owner_) Ownable(owner_) { _factory = factory_; } struct EventData { uint256 timestamp; bytes32 merkleRoot; address receivingToken; address sendingToken; uint8 isActive; } event AdminAdded(address indexed admin); event AdminRemoved(address indexed admin); event EventCreated(uint256 eventId, EventData eventData); event EventUpdated(uint256 eventId, uint8 isActive); event Redeemed(uint256 eventId, uint256 index, address indexed recipient, address indexed receivingToken, uint256 receivingTokenAmount, address indexed sendingToken, uint256 sendingTokenAmount); event Withdrawn(address indexed owner, address indexed recipient, address indexed token, uint256 value); function _setRedemption(uint256 eventId_, uint256 index_) private { _eventRedemptions[eventId_][index_] = true; } /// @dev Access Control, only owner and admins are able to access the specified function modifier onlyAdmin() { require(owner() == _msgSender() || _adminStatuses[_msgSender()], "Ownable: caller is not an admin"); _; } /// @dev returns current admins who can manage the vault function admins() public view returns (address[] memory) { return _admins; } /// @dev returns info of an event /// @param eventId_ ID of the event function eventInfo(uint256 eventId_) public view returns (EventData memory) { return _eventDatas[eventId_]; } /// @dev address of the factory function factory() public view returns (address) { return _factory; } /// @dev check an index whether it's redeemed /// @param eventId_ event ID /// @param index_ index of redemption pre-assigned to user function isRedeemed(uint256 eventId_, uint256 index_) public view returns (bool) { return _eventRedemptions[eventId_][index_]; } /// @dev claim the token which user is eligible from schedule /// @param eventId_ event ID /// @param index_ index of redemption pre-assigned to user /// @param recipient_ index of redemption pre-assigned to user /// @param receivingAmount_ amount of *receivingToken* user is eligible to redeem /// @param sendingAmount_ amount of *sendingToken* user must send the contract to get *receivingToken* /// @param proofs additional data to validate that the inputted information is valid function redeem(uint256 eventId_, uint256 index_, address recipient_, uint256 receivingAmount_, uint256 sendingAmount_, bytes32[] calldata proofs) public payable { uint256 fee = IVaultConfig(_factory).fee(); uint256 gasLimit = IVaultConfig(_factory).gasLimit(); if(fee > 0) { require(_msgValue() == fee, "C98Vault: Invalid fee"); } EventData storage eventData = _eventDatas[eventId_]; require(eventData.isActive > 0, "C98Vault: Invalid event"); require(eventData.timestamp <= block.timestamp, "C98Vault: Schedule locked"); require(recipient_ != address(0), "C98Vault: Invalid schedule"); bytes32 node = keccak256(abi.encodePacked(index_, recipient_, receivingAmount_, sendingAmount_)); require(MerkleProof.verify(proofs, eventData.merkleRoot, node), "C98Vault: Invalid proof"); require(!isRedeemed(eventId_, index_), "C98Vault: Redeemed"); uint256 availableAmount; if(eventData.receivingToken == address(0)) { availableAmount = address(this).balance; } else { availableAmount = IERC20(eventData.receivingToken).balanceOf(address(this)); } require(receivingAmount_ <= availableAmount, "C98Vault: Insufficient token"); _setRedemption(eventId_, index_); if(fee > 0) { uint256 reward = IVaultConfig(_factory).ownerReward(); uint256 finalFee = fee - reward; (bool success, bytes memory data) = _factory.call{value:finalFee, gas:gasLimit}(""); require(success, "C98Vault: Unable to charge fee"); } if(sendingAmount_ > 0) { IERC20(eventData.sendingToken).transferFrom(_msgSender(), address(this), sendingAmount_); } if(eventData.receivingToken == address(0)) { recipient_.call{value:receivingAmount_, gas:gasLimit}(""); } else { IERC20(eventData.receivingToken).transfer(recipient_, receivingAmount_); } emit Redeemed(eventId_, index_, recipient_, eventData.receivingToken, receivingAmount_, eventData.sendingToken, sendingAmount_); } /// @dev withdraw the token in the vault, no limit /// @param token_ address of the token, use address(0) to withdraw gas token /// @param destination_ recipient address to receive the fund /// @param amount_ amount of fund to withdaw function withdraw(address token_, address destination_, uint256 amount_) public onlyAdmin { require(destination_ != address(0), "C98Vault: Destination is zero address"); uint256 availableAmount; if(token_ == address(0)) { availableAmount = address(this).balance; } else { availableAmount = IERC20(token_).balanceOf(address(this)); } require(amount_ <= availableAmount, "C98Vault: Not enough balance"); uint256 gasLimit = IVaultConfig(_factory).gasLimit(); if(token_ == address(0)) { destination_.call{value:amount_, gas:gasLimit}(""); } else { IERC20(token_).transfer(destination_, amount_); } emit Withdrawn(_msgSender(), destination_, token_, amount_); } /// @dev withdraw NFT from contract /// @param token_ address of the token, use address(0) to withdraw gas token /// @param destination_ recipient address to receive the fund /// @param tokenId_ ID of NFT to withdraw function withdrawNft(address token_, address destination_, uint256 tokenId_) public onlyAdmin { require(destination_ != address(0), "C98Vault: destination is zero address"); IERC721(token_).transferFrom(address(this), destination_, tokenId_); emit Withdrawn(_msgSender(), destination_, token_, 1); } /// @dev create an event to specify how user can claim their token /// @param eventId_ event ID /// @param timestamp_ when the token will be available for redemption /// @param receivingToken_ token user will be receiving, mandatory /// @param sendingToken_ token user need to send in order to receive *receivingToken_* function createEvent(uint256 eventId_, uint256 timestamp_, bytes32 merkleRoot_, address receivingToken_, address sendingToken_) public onlyAdmin { require(_eventDatas[eventId_].timestamp == 0, "C98Vault: Event existed"); require(timestamp_ != 0, "C98Vault: Invalid timestamp"); _eventDatas[eventId_].timestamp = timestamp_; _eventDatas[eventId_].merkleRoot = merkleRoot_; _eventDatas[eventId_].receivingToken = receivingToken_; _eventDatas[eventId_].sendingToken = sendingToken_; _eventDatas[eventId_].isActive = 1; emit EventCreated(eventId_, _eventDatas[eventId_]); } /// @dev enable/disable a particular event /// @param eventId_ event ID /// @param isActive_ zero to inactive, any number to active function setEventStatus(uint256 eventId_, uint8 isActive_) public onlyAdmin { require(_eventDatas[eventId_].timestamp != 0, "C98Vault: Invalid event"); _eventDatas[eventId_].isActive = isActive_; emit EventUpdated(eventId_, isActive_); } /// @dev add/remove admin of the vault. /// @param nAdmins_ list to address to update /// @param nStatuses_ address with same index will be added if true, or remove if false /// admins will have access to all tokens in the vault, and can define vesting schedule function setAdmins(address[] memory nAdmins_, bool[] memory nStatuses_) public onlyOwner { require(nAdmins_.length != 0, "C98Vault: Empty arguments"); require(nStatuses_.length != 0, "C98Vault: Empty arguments"); require(nAdmins_.length == nStatuses_.length, "C98Vault: Invalid arguments"); uint256 i; for(i = 0; i < nAdmins_.length; i++) { address nAdmin = nAdmins_[i]; if(nStatuses_[i]) { if(!_adminStatuses[nAdmin]) { _admins.push(nAdmin); _adminStatuses[nAdmin] = nStatuses_[i]; emit AdminAdded(nAdmin); } } else { uint256 j; for(j = 0; j < _admins.length; j++) { if(_admins[j] == nAdmin) { _admins[j] = _admins[_admins.length - 1]; _admins.pop(); delete _adminStatuses[nAdmin]; emit AdminRemoved(nAdmin); break; } } } } } } contract Coin98VaultFactory is Ownable, Payable, IVaultConfig { uint256 private _fee; uint256 private _gasLimit; uint256 private _ownerReward; address[] private _vaults; constructor () Ownable(_msgSender()) { _gasLimit = 9000; } /// @dev Emit `FeeUpdated` when a new vault is created event Created(address indexed vault); /// @dev Emit `FeeUpdated` when fee of the protocol is updated event FeeUpdated(uint256 fee); /// @dev Emit `OwnerRewardUpdated` when reward for vault owner is updated event OwnerRewardUpdated(uint256 fee); /// @dev Emit `Withdrawn` when owner withdraw fund from the factory event Withdrawn(address indexed owner, address indexed recipient, address indexed token, uint256 value); /// @dev get current protocol fee in gas token function fee() override external view returns (uint256) { return _fee; } /// @dev limit gas to send native token function gasLimit() override external view returns (uint256) { return _gasLimit; } /// @dev get current owner reward in gas token function ownerReward() override external view returns (uint256) { return _ownerReward; } /// @dev get list of vaults initialized through this factory function vaults() external view returns (address[] memory) { return _vaults; } /// @dev create a new vault /// @param owner_ Owner of newly created vault function createVault(address owner_) external returns (Coin98Vault vault) { vault = new Coin98Vault(address(this), owner_); _vaults.push(address(vault)); emit Created(address(vault)); } function setGasLimit(uint256 limit_) public onlyOwner { _gasLimit = limit_; } /// @dev change protocol fee /// @param fee_ amount of gas token to charge for every redeem. can be ZERO to disable protocol fee /// @param reward_ amount of gas token to incentive vault owner. this reward will be deduce from protocol fee function setFee(uint256 fee_, uint256 reward_) public onlyOwner { require(fee_ >= reward_, "C98Vault: Invalid reward amount"); _fee = fee_; _ownerReward = reward_; emit FeeUpdated(fee_); emit OwnerRewardUpdated(reward_); } /// @dev withdraw fee collected for protocol /// @param token_ address of the token, use address(0) to withdraw gas token /// @param destination_ recipient address to receive the fund /// @param amount_ amount of fund to withdaw function withdraw(address token_, address destination_, uint256 amount_) public onlyOwner { require(destination_ != address(0), "C98Vault: Destination is zero address"); uint256 availableAmount; if(token_ == address(0)) { availableAmount = address(this).balance; } else { availableAmount = IERC20(token_).balanceOf(address(this)); } require(amount_ <= availableAmount, "C98Vault: Not enough balance"); if(token_ == address(0)) { destination_.call{value:amount_, gas:_gasLimit}(""); } else { IERC20(token_).transfer(destination_, amount_); } emit Withdrawn(_msgSender(), destination_, token_, amount_); } /// @dev withdraw NFT from contract /// @param token_ address of the token, use address(0) to withdraw gas token /// @param destination_ recipient address to receive the fund /// @param tokenId_ ID of NFT to withdraw function withdrawNft(address token_, address destination_, uint256 tokenId_) public onlyOwner { require(destination_ != address(0), "C98Vault: destination is zero address"); IERC721(token_).transferFrom(address(this), destination_, tokenId_); emit Withdrawn(_msgSender(), destination_, token_, 1); } }
@dev withdraw fee collected for protocol @param token_ address of the token, use address(0) to withdraw gas token @param destination_ recipient address to receive the fund @param amount_ amount of fund to withdaw
function withdraw(address token_, address destination_, uint256 amount_) public onlyOwner { require(destination_ != address(0), "C98Vault: Destination is zero address"); uint256 availableAmount; if(token_ == address(0)) { availableAmount = address(this).balance; availableAmount = IERC20(token_).balanceOf(address(this)); } require(amount_ <= availableAmount, "C98Vault: Not enough balance"); if(token_ == address(0)) { IERC20(token_).transfer(destination_, amount_); } emit Withdrawn(_msgSender(), destination_, token_, amount_); }
229,433
[ 1, 1918, 9446, 14036, 12230, 364, 1771, 225, 1147, 67, 1758, 434, 326, 1147, 16, 999, 1758, 12, 20, 13, 358, 598, 9446, 16189, 1147, 225, 2929, 67, 8027, 1758, 358, 6798, 326, 284, 1074, 225, 3844, 67, 3844, 434, 284, 1074, 358, 598, 72, 2219, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 598, 9446, 12, 2867, 1147, 67, 16, 1758, 2929, 67, 16, 2254, 5034, 3844, 67, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 12, 10590, 67, 480, 1758, 12, 20, 3631, 315, 39, 10689, 12003, 30, 10691, 353, 3634, 1758, 8863, 203, 203, 565, 2254, 5034, 2319, 6275, 31, 203, 565, 309, 12, 2316, 67, 422, 1758, 12, 20, 3719, 288, 203, 1377, 2319, 6275, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 1377, 2319, 6275, 273, 467, 654, 39, 3462, 12, 2316, 67, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 565, 289, 203, 203, 565, 2583, 12, 8949, 67, 1648, 2319, 6275, 16, 315, 39, 10689, 12003, 30, 2288, 7304, 11013, 8863, 203, 203, 565, 309, 12, 2316, 67, 422, 1758, 12, 20, 3719, 288, 203, 1377, 467, 654, 39, 3462, 12, 2316, 67, 2934, 13866, 12, 10590, 67, 16, 3844, 67, 1769, 203, 565, 289, 203, 203, 565, 3626, 3423, 9446, 82, 24899, 3576, 12021, 9334, 2929, 67, 16, 1147, 67, 16, 3844, 67, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.5 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; contract LevelTwo is Ownable { /// @notice The kind of hand we can bet, explicitly convertable to uint8. enum Hand { rock, paper, scissors } /** * Events * * @param player - The address of player * @param playerHand - The hand of player * @param hostHand - The hand of host * @param amount - The amount of Ether used to bet */ event Won(address indexed player, Hand playerHand, Hand hostHand, uint256 amount); event Draw(address indexed player, Hand playerHand, Hand hostHand, uint256 amount); event Lost(address indexed player, Hand playerHand, Hand hostHand, uint256 amount); /** * The nonce used to generate random. * @dev Not secure! Never! 😞 Hacker can read the value on storage, even though it's private. * That means Hacker may create a hacking contract which never lose, by simulating our random function. */ uint256 private randNonce = 0; /** * The minimal bet fee to play game. * Player needs to pay Ether to bet. * Before betting, player may need to check host's balance to see if it has enough Ether to pay when player wins. */ uint256 public constant MINIMAL_BET_FEE = 1e9; /** * The fomo pool size. */ uint256 public constant FOMO_POOL_SIZE = MINIMAL_BET_FEE * 100; /** * The balance of the fomo pool. */ uint256 public fomoPool = 0; /** * The fomo timer. */ uint256 public fomoEndTime = 0; /** * The last bettor that turned on or extended the timer. */ address public fomoWinner; /** * Fomo Events */ event FomoTimerStart(address indexed winner, uint256 endTime); event FomoTimerIncrease(address indexed winner, uint256 endTime); event NewFomoDeposit(address indexed sender, uint256 amount); event FomoWithdraw(address indexed winner, uint256 amount); /** * Process the fomo pool. * Should be executed prior to any other stuff. * If the fomo timer is ended, the last bettor that either turned on or extended the timer wins * all amount in the fomo pool, and the fomo timer is turned off. */ function _processFomo() internal { if (fomoWinner == address(0)) return; if (fomoEndTime > block.timestamp) return; fomoEndTime = 0; address payable winner = payable(fomoWinner); fomoWinner = address(0); if (fomoPool == 0) return; uint256 value = fomoPool; fomoPool = 0; winner.transfer(value); emit FomoWithdraw(winner, value); } /** * Process the new bet placement. * If the fomo timer is off, the timer starts and is set to end 1 hour later. * Otherwise extend the timer as 1 hour more only if the bet amount is at least 10% of the pool size. */ function _processBid() internal { if (fomoWinner == address(0)) { fomoEndTime = block.timestamp + (1 hours); fomoWinner = msg.sender; emit FomoTimerStart(fomoWinner, fomoEndTime); return; } if (msg.value < FOMO_POOL_SIZE / 10) return; fomoEndTime = fomoEndTime + (1 hours); fomoWinner = msg.sender; emit FomoTimerIncrease(fomoWinner, fomoEndTime); } /** * Increase the fomo pool as the amount. * * @param _amount - The amount to increase */ function _addToFomoPool(uint256 _amount) internal { fomoPool += _amount; emit NewFomoDeposit(msg.sender, _amount); } /** * Play a bet. * Player needs to send Ether to bet, the amount is required greater than the bet fee. * Also, Host needs to have as sufficient Ether as at least the double of amount to return when lose. * If Player won, returns the double amount of Ether used to bet. * If Player lost, do nothing. * If draw, returns just the amount of Ether used to bet. */ function bet(Hand _playerHand) external payable { require(msg.value >= MINIMAL_BET_FEE, "LevelOne: Insufficient bet bee."); /// @dev Bet fee has been included to the host balance already at the point. require(address(this).balance >= msg.value * 2, "LevelOne: Insufficient host fund."); // process fomo pool before doing everything _processFomo(); // place a new bid _processBid(); Hand hostHand = getRandomHand(); int8 result = compareHand(_playerHand, hostHand); if (result == 0) { // equal // Return player's Ether returnFund(msg.value); emit Draw(msg.sender, _playerHand, hostHand, msg.value); return; } else if (result > 0) { // player won! 😄 // Loser host!!!!!! 😫 😫 😫. Return double of player's Ether /// @dev safe for overflow, because we compile in v0.8.0 uint256 rewards = msg.value * 2; // save 5% of rewards to fomo pool uint256 fomoAmount = (rewards * 5) / 100; _addToFomoPool(fomoAmount); returnFund(rewards - fomoAmount); emit Won(msg.sender, _playerHand, hostHand, msg.value); return; } // host won, keep the Ether 💰 // Nothing to do. emit Lost(msg.sender, _playerHand, hostHand, msg.value); } /** * Compare Hands. * * @param _a - The one side * @param _b - The another side * @return The comparison result. 0: equal, 1: _a wins, -1: _b wins */ function compareHand(Hand _a, Hand _b) internal pure returns (int8) { uint8 a = uint8(_a); uint8 b = uint8(_b); if (a == b) return 0; if ((a + 1) % 3 == b) return -1; return 1; } /** * Get the host's hand based on random number. * * @return a different hand every time called. */ function getRandomHand() internal returns (Hand) { uint256 rand = randMod(90); if (rand < 30) { return Hand.rock; } else if (rand < 60) { return Hand.paper; } return Hand.scissors; } /** * Generate random number between 0 to _modulus. * Not secure! 😞 * * @param _modulus - The max - 1 of the random number range */ function randMod(uint256 _modulus) internal returns (uint256) { return uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, ++randNonce))) % _modulus; } /** * Return Ether to player. * * @param _amount - The amount of Ether to return depends on the match result */ function returnFund(uint256 _amount) private { payable(msg.sender).transfer(_amount); } /** * Receive Ether, that will be used to pay winning players. */ receive() external payable {} /** * Withdraw Ether to owner, the only way to take back Ether for owner. * * @param _amount - The amount to withdraw */ function withdraw(uint256 _amount) external onlyOwner { require(address(this).balance >= _amount, "LevelOne: Insufficient balance to withdraw."); address payable _owner = payable(address(uint160(owner()))); _owner.transfer(_amount); } }
* The balance of the fomo pool./
uint256 public fomoPool = 0;
6,438,882
[ 1, 1986, 11013, 434, 326, 284, 362, 83, 2845, 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, 225, 2254, 5034, 1071, 284, 362, 83, 2864, 273, 374, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./traits/TokenTraits.sol"; import "./traits/ITraits.sol"; import "./IVampireGame.sol"; /// @title The Vampire Game NFT contract /// /// Note: The original Wolf Game's contract was used as insipiration, and a /// few parts of the contract were taken directly, in particular the trait selection /// and rarity using Walker's Alias method, and using a separate `Traits` contract /// for getting the tokenURI. /// /// Some info about how this contract works: /// /// ### On-chain vs Off-chain /// /// What is on-chain here? /// - The generated traits /// - The revealed traits metadata /// - The traits img data /// /// What is off-chain? /// - The random number we get for batch reveals. /// - The non-revealed image. /// /// ### Minting and Revealing /// /// 1. The user mints an NFT /// 2. A seed is assigned for OG and Gen0 batches, this reveals the NFTs. /// /// Why? We believe that as long as minting and revealing happens in the same /// transaction, people will be able to cheat. So first you commit to minting, then /// the seed is released. /// /// ### Traits /// /// The traits are all stored on-chain in another contract "Traits" similar to Wolf Game. /// /// ### Game Controllers /// /// For us to be able to expand on this game, future "game controller" contracts will be /// able to freely call `mint` functions, and `transferFrom`, the logic to safeguard /// those functions will be delegated to those contracts. /// contract VampireGame is IVampireGame, IVampireGameControls, ERC721, Ownable, Pausable, ReentrancyGuard { /// ==== Events event TokenRevealed(uint256 indexed tokenId, uint256 seed); event OGRevealed(uint256 seed); event Gen0Revealed(uint256 seed); /// ==== Immutable Properties /// @notice max amount of tokens that can be minted uint16 public immutable maxSupply; /// @notice max amount of og tokens uint16 public immutable ogSupply; /// @notice address to withdraw the eth address private immutable splitter; /// @notice minting price in wei uint256 public immutable mintPrice; /// ==== Mutable Properties /// @notice current amount of minted tokens uint16 public totalSupply; /// @notice max amount of gen 0 tokens (tokens that can be bought with eth) uint16 public genZeroSupply; /// @notice seed for the OGs who minted contract v1 uint256 public ogSeed; /// @notice seed for all Gen 0 except for OGs uint256 public genZeroSeed; /// @notice contract storing the traits data ITraits public traits; /// @notice game controllers they can access special functions mapping(uint16 => uint256) public tokenSeeds; /// @notice game controllers they can access special functions mapping(address => bool) public controllers; /// === Constructor /// @dev constructor, most of the immutable props can be set here so it's easier to test /// @param _mintPrice price to mint one token in wei /// @param _maxSupply maximum amount of available tokens to mint /// @param _genZeroSupply maxiumum amount of tokens that can be bought with eth /// @param _splitter address to where the funds will go constructor( uint256 _mintPrice, uint16 _maxSupply, uint16 _genZeroSupply, uint16 _ogSupply, address _splitter ) ERC721("The Vampire Game", "VGAME") { mintPrice = _mintPrice; maxSupply = _maxSupply; genZeroSupply = _genZeroSupply; ogSupply = _ogSupply; splitter = _splitter; _pause(); } /// ==== Modifiers modifier onlyControllers() { require(controllers[_msgSender()], "ONLY_CONTROLLERS"); _; } /// ==== Airdrop function airdropToOwners( address v1Contract, uint16 from, uint16 to ) external onlyOwner { require(to >= from); IERC721 v1 = IERC721(v1Contract); for (uint16 i = from; i <= to; i++) { _mint(v1.ownerOf(i), i); } totalSupply += (to - from + 1); } /// ==== Minting /// @notice mint an unrevealed token using eth /// @param amount amount to mint function mintWithETH(uint16 amount) external payable whenNotPaused nonReentrant { require(amount > 0, "INVALID_AMOUNT"); require(amount * mintPrice == msg.value, "WRONG_VALUE"); uint16 supply = totalSupply; require(supply + amount <= genZeroSupply, "NOT_ENOUGH_TOKENS"); totalSupply = supply + amount; address to = _msgSender(); for (uint16 i = 0; i < amount; i++) { _safeMint(to, supply + i); } } /// ==== Revealing /// @notice set the seed for the OG tokens. Once this is set, it cannot be changed! function revealOgTokens(uint256 seed) external onlyOwner { require(ogSeed == 0, "ALREADY_SET"); ogSeed = seed; emit OGRevealed(seed); } /// @notice set the seed for the non-og Gen 0 tokens. Once this is set, it cannot be changed! function revealGenZeroTokens(uint256 seed) external onlyOwner { require(genZeroSeed == 0, "ALREADY_SET"); genZeroSeed = seed; emit Gen0Revealed(seed); } /// ==================== /// @notice Calculate the seed for a specific token /// - For OG tokens, the seed is derived from ogSeed /// - For Gen 0 tokens, the seed is derived from genZeroSeed /// - For other tokens, there is a seed for each for each function seedForToken(uint16 tokenId) public view returns (uint256) { uint16 supply = totalSupply; uint16 og = ogSupply; if (tokenId < og) { // amount of minted tokens needs to be greater than or equal to the og supply uint256 seed = ogSeed; if (supply >= og && seed != 0) { return uint256(keccak256(abi.encodePacked(seed, "og", tokenId))); } return 0; } // read from storage only once uint16 pt = genZeroSupply; if (tokenId < pt) { // amount of minted tokens needs to be greater than or equal to the og supply uint256 seed = genZeroSeed; if (supply >= pt && seed != 0) { return uint256(keccak256(abi.encodePacked(seed, "ze", tokenId))); } return 0; } if (supply > tokenId) { return tokenSeeds[tokenId]; } return 0; } /// ==== Functions to calculate traits given a seed function _isVampire(uint256 seed) private pure returns (bool) { return (seed & 0xFFFF) % 10 == 0; } /// Human Traits function _tokenTraitHumanSkin(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 16) & 0xFFFF; uint256 trait = traitSeed % 5; if (traitSeed >> 8 < [50, 15, 15, 250, 255][trait]) return uint8(trait); return [3, 4, 4, 0, 3][trait]; } function _tokenTraitHumanFace(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 32) & 0xFFFF; uint256 trait = traitSeed % 19; if ( traitSeed >> 8 < [ 133, 189, 57, 255, 243, 133, 114, 135, 168, 38, 222, 57, 95, 57, 152, 114, 57, 133, 189 ][trait] ) return uint8(trait); return [1, 0, 3, 1, 3, 3, 3, 4, 7, 4, 8, 4, 8, 10, 10, 10, 18, 18, 14][ trait ]; } function _tokenTraitHumanTShirt(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 48) & 0xFFFF; uint256 trait = traitSeed % 28; if ( traitSeed >> 8 < [ 181, 224, 147, 236, 220, 168, 160, 84, 173, 224, 221, 254, 140, 252, 224, 250, 100, 207, 84, 252, 196, 140, 228, 140, 255, 183, 241, 140 ][trait] ) return uint8(trait); return [ 1, 0, 3, 1, 3, 3, 4, 11, 11, 4, 9, 10, 13, 11, 13, 14, 15, 15, 20, 17, 19, 24, 20, 24, 22, 26, 24, 26 ][trait]; } function _tokenTraitHumanPants(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 64) & 0xFFFF; uint256 trait = traitSeed % 16; if ( traitSeed >> 8 < [ 126, 171, 225, 240, 227, 112, 255, 240, 217, 80, 64, 160, 228, 80, 64, 167 ][trait] ) return uint8(trait); return [2, 0, 1, 2, 3, 3, 4, 6, 7, 4, 6, 7, 8, 8, 15, 12][trait]; } function _tokenTraitHumanBoots(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 80) & 0xFFFF; uint256 trait = traitSeed % 6; if (traitSeed >> 8 < [150, 30, 60, 255, 150, 60][trait]) return uint8(trait); return [0, 3, 3, 0, 3, 4][trait]; } function _tokenTraitHumanAccessory(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 96) & 0xFFFF; uint256 trait = traitSeed % 20; if ( traitSeed >> 8 < [ 210, 135, 80, 245, 235, 110, 80, 100, 190, 100, 255, 160, 215, 80, 100, 185, 250, 240, 240, 100 ][trait] ) return uint8(trait); return [ 0, 0, 3, 0, 3, 4, 10, 12, 4, 16, 8, 16, 10, 17, 18, 12, 15, 16, 17, 18 ][trait]; } function _tokenTraitHumanHair(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 112) & 0xFFFF; uint256 trait = traitSeed % 10; if ( traitSeed >> 8 < [250, 115, 100, 40, 175, 255, 180, 100, 175, 185][trait] ) return uint8(trait); return [0, 0, 4, 6, 0, 4, 5, 9, 6, 8][trait]; } /// ==== Vampire Traits function _tokenTraitVampireSkin(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 16) & 0xFFFF; uint256 trait = traitSeed % 13; if ( traitSeed >> 8 < [234, 239, 234, 234, 255, 234, 244, 249, 130, 234, 234, 247, 234][ trait ] ) return uint8(trait); return [0, 0, 1, 2, 3, 4, 5, 6, 12, 7, 9, 10, 11][trait]; } function _tokenTraitVampireFace(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 32) & 0xFFFF; uint256 trait = traitSeed % 15; if ( traitSeed >> 8 < [ 45, 255, 165, 60, 195, 195, 45, 120, 75, 75, 105, 120, 255, 180, 150 ][trait] ) return uint8(trait); return [1, 0, 1, 4, 2, 4, 5, 12, 12, 13, 13, 14, 5, 12, 13][trait]; } function _tokenTraitVampireClothes(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 48) & 0xFFFF; uint256 trait = traitSeed % 27; if ( traitSeed >> 8 < [ 147, 180, 246, 201, 210, 252, 219, 189, 195, 156, 177, 171, 165, 225, 135, 135, 186, 135, 150, 243, 135, 255, 231, 141, 183, 150, 135 ][trait] ) return uint8(trait); return [ 2, 2, 0, 2, 3, 4, 5, 6, 7, 3, 3, 4, 4, 8, 5, 6, 13, 13, 19, 16, 19, 19, 21, 21, 21, 21, 22 ][trait]; } function _tokenTraitVampireCape(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 128) & 0xFFFF; uint256 trait = traitSeed % 9; if (traitSeed >> 8 < [9, 9, 150, 90, 9, 210, 9, 9, 255][trait]) return uint8(trait); return [5, 5, 0, 2, 8, 3, 8, 8, 5][trait]; } function _tokenTraitVampirePredatorIndex(uint256 seed) private pure returns (uint8) { uint256 traitSeed = (seed >> 144) & 0xFFFF; uint256 trait = traitSeed % 4; if (traitSeed >> 8 < [255, 8, 160, 73][trait]) return uint8(trait); return [0, 0, 0, 2][trait]; } /// ==== State Control /// @notice set the max amount of gen 0 tokens function setGenZeroSupply(uint16 _genZeroSupply) external onlyOwner { require(genZeroSupply != _genZeroSupply, "NO_CHANGES"); genZeroSupply = _genZeroSupply; } /// @notice set the contract for the traits rendering /// @param _traits the contract address function setTraits(address _traits) external onlyOwner { traits = ITraits(_traits); } /// @notice add controller authority to an address /// @param _controller address to the game controller function addController(address _controller) external onlyOwner { controllers[_controller] = true; } /// @notice remove controller authority from an address /// @param _controller address to the game controller function removeController(address _controller) external onlyOwner { controllers[_controller] = false; } /// ==== Withdraw /// @notice withdraw the ether from the contract function withdraw() external onlyOwner { uint256 contractBalance = address(this).balance; // solhint-disable-next-line avoid-low-level-calls (bool sent, ) = splitter.call{value: contractBalance}(""); require(sent, "FAILED_TO_WITHDRAW"); } /// @notice withdraw ERC20 tokens from the contract /// people always randomly transfer ERC20 tokens to the /// @param erc20TokenAddress the ERC20 token address /// @param recipient who will get the tokens /// @param amount how many tokens function withdrawERC20( address erc20TokenAddress, address recipient, uint256 amount ) external onlyOwner { IERC20 erc20Contract = IERC20(erc20TokenAddress); bool sent = erc20Contract.transfer(recipient, amount); require(sent, "ERC20_WITHDRAW_FAILED"); } /// @notice reserve some tokens for the team. Can only reserve gen 0 tokens /// we also need token 0 to so setup market places before mint function reserve(address to, uint16 amount) external onlyOwner { uint16 supply = totalSupply; require(supply + amount < genZeroSupply); totalSupply = supply + amount; for (uint16 i = 0; i < amount; i++) { _safeMint(to, supply + i); } } /// ==== pause/unpause function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } /// ==== IVampireGameControls Overrides /// @notice see {IVampireGameControls.mintFromController} function mintFromController(address receiver, uint16 amount) external override whenNotPaused onlyControllers { uint16 supply = totalSupply; require(supply + amount <= maxSupply, "NOT_ENOUGH_TOKENS"); totalSupply = supply + amount; for (uint256 i = 0; i < amount; i++) { _safeMint(receiver, supply + i); } } /// @notice for a game controller to reveal the metadata of multiple token ids function controllerRevealTokens( uint16[] calldata tokenIds, uint256[] calldata seeds ) external override whenNotPaused onlyControllers { require( tokenIds.length == seeds.length, "INPUTS_SHOULD_HAVE_SAME_LENGTH" ); for (uint256 i = 0; i < tokenIds.length; i++) { require(tokenSeeds[tokenIds[i]] == 0, "ALREADY_REVEALED"); tokenSeeds[tokenIds[i]] = seeds[i]; emit TokenRevealed(tokenIds[i], seeds[i]); } } /// ==== IVampireGame Overrides /// @notice see {IVampireGame.getTotalSupply} function getTotalSupply() external view override returns (uint16) { return totalSupply; } /// @notice see {IVampireGame.getOGSupply} function getOGSupply() external view override returns (uint16) { return ogSupply; } /// @notice see {IVampireGame.getGenZeroSupply} function getGenZeroSupply() external view override returns (uint16) { return genZeroSupply; } /// @notice see {IVampireGame.getMaxSupply} function getMaxSupply() external view override returns (uint16) { return maxSupply; } /// @notice see {IVampireGame.getTokenTraits} function getTokenTraits(uint16 tokenId) external view override returns (TokenTraits memory tt) { uint256 seed = seedForToken(tokenId); require(seed != 0, "NOT_REVEALED"); tt.isVampire = _isVampire(seed); if (tt.isVampire) { tt.skin = _tokenTraitVampireSkin(seed); tt.face = _tokenTraitVampireFace(seed); tt.clothes = _tokenTraitVampireClothes(seed); tt.cape = _tokenTraitVampireCape(seed); tt.predatorIndex = _tokenTraitVampirePredatorIndex(seed); } else { tt.skin = _tokenTraitHumanSkin(seed); tt.face = _tokenTraitHumanFace(seed); tt.clothes = _tokenTraitHumanTShirt(seed); tt.pants = _tokenTraitHumanPants(seed); tt.boots = _tokenTraitHumanBoots(seed); tt.accessory = _tokenTraitHumanAccessory(seed); tt.hair = _tokenTraitHumanHair(seed); } } function isTokenVampire(uint16 tokenId) external view override returns (bool) { return _isVampire(seedForToken(tokenId)); } function getPredatorIndex(uint16 tokenId) external view override returns (uint8) { uint256 seed = seedForToken(tokenId); require(seed != 0, "NOT_REVEALED"); return _tokenTraitVampirePredatorIndex(seed); } /// @notice see {IVampireGame.isTokenRevealed(tokenId)} function isTokenRevealed(uint16 tokenId) public view override returns (bool) { return seedForToken(tokenId) != 0; } /// ==== ERC721 Overrides function transferFrom( address from, address to, uint256 tokenId ) public virtual override { // Hardcode approval of game controllers if (!controllers[_msgSender()]) require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return traits.tokenURI(tokenId); } } // 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 "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.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}. 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 {} } // 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; 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: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _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()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; struct TokenTraits { bool isVampire; // Shared Traits uint8 skin; uint8 face; uint8 clothes; // Human-only Traits uint8 pants; uint8 boots; uint8 accessory; uint8 hair; // Vampire-only Traits uint8 cape; uint8 predatorIndex; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./traits/TokenTraits.sol"; /// @notice Interface to interact with the VampireGame contract interface IVampireGame { /// @notice get the amount of tokens minted function getTotalSupply() external view returns (uint16); /// @notice get tthe amount of og supply function getOGSupply() external view returns (uint16); /// @notice get the total supply of gen-0 function getGenZeroSupply() external view returns (uint16); /// @notice get the total supply of tokens function getMaxSupply() external view returns (uint16); /// @notice get the TokenTraits for a given tokenId function getTokenTraits(uint16 tokenId) external view returns (TokenTraits memory); /// @notice check if token id a vampire function isTokenVampire(uint16 tokenId) external view returns (bool); /// @notice get the Predator Index for a given tokenId function getPredatorIndex(uint16 tokenId) external view returns (uint8); /// @notice returns true if a token is aleady revealed function isTokenRevealed(uint16 tokenId) external view returns (bool); } /// @notice Interface to control parts of the VampireGame ERC 721 interface IVampireGameControls { /// @notice mint any amount of nft to any address /// Requirements: /// - message sender should be an allowed address (game contract) /// - amount + totalSupply() has to be smaller than MAX_SUPPLY function mintFromController(address receiver, uint16 amount) external; /// @notice reveal a list of tokens using specific seeds for each function controllerRevealTokens(uint16[] calldata tokenIds, uint256[] calldata seeds) 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 "../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; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT 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); }
@notice set the seed for the OG tokens. Once this is set, it cannot be changed!
function revealOgTokens(uint256 seed) external onlyOwner { require(ogSeed == 0, "ALREADY_SET"); ogSeed = seed; emit OGRevealed(seed); }
588,773
[ 1, 542, 326, 5009, 364, 326, 531, 43, 2430, 18, 12419, 333, 353, 444, 16, 518, 2780, 506, 3550, 5, 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, 565, 445, 283, 24293, 51, 75, 5157, 12, 11890, 5034, 5009, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 717, 12702, 422, 374, 16, 315, 1013, 20305, 67, 4043, 8863, 203, 3639, 22128, 12702, 273, 5009, 31, 203, 3639, 3626, 531, 43, 426, 537, 18931, 12, 12407, 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 ]
pragma solidity 0.4.21; /** * @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; address public newOwner; 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(address(0) != _newOwner); newOwner = _newOwner; } /** * @dev Need newOwner to receive the Ownership. */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, msg.sender); owner = msg.sender; newOwner = address(0); } } /** * @title MultiToken * @dev The interface of BCZERO Token contract. */ contract IBCZEROToken { function acceptOwnership() public; function transfer(address _to, uint _value) public returns(bool); } /** * @title BCZEROOwner * @dev The management contract of BCZEROToken, to manage the ownership of Token contract. */ contract BCZEROOwner is Ownable{ IBCZEROToken BCZEROToken; bool public exchangeEnabled; address public BCZEROTokenAddr = 0xD45247c07379d94904E0A87b4481F0a1DDfa0C64; // the address of BCZERO Token. event WithdrawETH(uint256 amount); event ExchangeEnabledStatus(bool enabled); /** * @dev Constructor, setting the contract address of BCZERO token and the owner of this contract. * setting exchangeEnabled as true. * @param _owner The owner of this contract. */ function BCZEROOwner(address _owner) public { BCZEROToken = IBCZEROToken(BCZEROTokenAddr); owner = _owner; exchangeEnabled = true; } /** * @dev this contract to accept the ownership. */ function acceptBCZEROOwnership() public onlyOwner { BCZEROToken.acceptOwnership(); } /** * @dev fallback, Let this contract can receive ETH */ function() external payable { require(exchangeEnabled); } /** * @dev Setting whether the BCZERO tokens can be exchanged. * @param _enabled true or false */ function setExchangeEnabled(bool _enabled) public onlyOwner { exchangeEnabled = _enabled; emit ExchangeEnabledStatus(_enabled); } /** * @dev Owner can transfer the ETH of this contract to the owner account by calling this function. */ function withdrawETH() public onlyOwner { uint256 amount = address(this).balance; // getting the balance of this contract(ETH). require(amount > 0); owner.transfer(amount); // sending ETH to owner. emit WithdrawETH(amount); } /** * @dev Owner can transfer the BCZERO token of this contract to the address 'to' by calling this function. */ function transferBCZEROToken(address to, uint256 value) public onlyOwner { BCZEROToken.transfer(to, value); } }
* @dev Setting whether the BCZERO tokens can be exchanged. @param _enabled true or false/
function setExchangeEnabled(bool _enabled) public onlyOwner { exchangeEnabled = _enabled; emit ExchangeEnabledStatus(_enabled); }
6,382,626
[ 1, 5568, 2856, 326, 21225, 24968, 2430, 848, 506, 431, 6703, 18, 225, 389, 5745, 638, 578, 629, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 444, 11688, 1526, 12, 6430, 389, 5745, 13, 1071, 1338, 5541, 288, 203, 3639, 7829, 1526, 273, 389, 5745, 31, 203, 3639, 3626, 18903, 1526, 1482, 24899, 5745, 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 ]
./full_match/3/0x1aa2D6465445C97602F495d34F08535bCABBE75f/sources/contracts/Main.sol
* @title ERC721 Non-Fungible Token Standard basic implementation/ Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` Mapping from holder address to their (enumerable) set of owned tokens Enumerable mapping from token ids to their owners Mapping from token ID to approved address Mapping from owner to operator approvals Token name Token symbol Optional mapping for token URIs Base URI
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; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; mapping (address => EnumerableSet.UintSet) private _holderTokens; EnumerableMap.UintToAddressMap private _tokenOwners; mapping (uint256 => address) private _tokenApprovals; mapping (address => mapping (address => bool)) private _operatorApprovals; string private _name; string private _symbol; mapping (uint256 => string) private _tokenURIs; string private _baseURI; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } 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(); } function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } 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 (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _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 (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _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 (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } } return string(abi.encodePacked(base,'/', tokenId.toString(),'json')); function baseURI() public view virtual returns (string memory) { return _baseURI; } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } function totalSupply() public view virtual override returns (uint256) { return _tokenOwners.length(); } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } 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); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } 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); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } 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); } 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"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } 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)); } d* function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } 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"); } 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); } function _burn(uint256 tokenId) internal virtual { _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } function _burn(uint256 tokenId) internal virtual { _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } function _transfer(address from, address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } 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) private { _tokenApprovals[tokenId] = to; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } }
14,244,457
[ 1, 654, 39, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 8263, 5337, 4471, 19, 19344, 358, 1375, 3890, 24, 12, 79, 24410, 581, 5034, 2932, 265, 654, 39, 27, 5340, 8872, 12, 2867, 16, 2867, 16, 11890, 5034, 16, 3890, 2225, 3719, 68, 1492, 848, 506, 2546, 12700, 487, 1375, 45, 654, 39, 27, 5340, 12952, 12, 20, 2934, 265, 654, 39, 27, 5340, 8872, 18, 9663, 68, 9408, 628, 10438, 1758, 358, 3675, 261, 7924, 25121, 13, 444, 434, 16199, 2430, 6057, 25121, 2874, 628, 1147, 3258, 358, 3675, 25937, 9408, 628, 1147, 1599, 358, 20412, 1758, 9408, 628, 3410, 358, 3726, 6617, 4524, 3155, 508, 3155, 3273, 4055, 2874, 364, 1147, 24565, 3360, 3699, 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, 4232, 39, 27, 5340, 353, 1772, 16, 4232, 39, 28275, 16, 467, 654, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 2277, 16, 467, 654, 39, 27, 5340, 3572, 25121, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 5487, 694, 31, 203, 565, 1450, 6057, 25121, 863, 364, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 654, 39, 27, 5340, 67, 27086, 20764, 273, 374, 92, 23014, 70, 27, 69, 3103, 31, 203, 203, 565, 2874, 261, 2867, 516, 6057, 25121, 694, 18, 5487, 694, 13, 3238, 389, 4505, 5157, 31, 203, 203, 565, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 3238, 389, 2316, 5460, 414, 31, 203, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 2874, 261, 11890, 5034, 516, 533, 13, 3238, 389, 2316, 1099, 2520, 31, 203, 203, 565, 533, 3238, 389, 1969, 3098, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 18865, 67, 734, 67, 654, 39, 27, 5340, 273, 374, 92, 3672, 1077, 8204, 4315, 31, 203, 203, 565, 1731, 24, 3238, 5381, 2 ]
./partial_match/42220/0xeD929BB106d6E593f3dF57CE6B2bF60177DF8806/sources/contracts/CarbonCreditPermissionList.sol
@dev see ICarbonCreditPermissionList
function multiChainAddresses() external view returns (address[] memory) { return _multiChainAddresses.values(); }
3,494,650
[ 1, 5946, 26899, 11801, 16520, 5041, 682, 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, 445, 3309, 3893, 7148, 1435, 3903, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 327, 389, 7027, 3893, 7148, 18, 2372, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x4F1982dcbB37021eA9F8Ed5dFa1C5a4b73f92665/sources/contracts/governance/community/PolicyProposals.sol
* The minimum cost to register a proposal./
uint256 public constant COST_REGISTER = 10000e18;
15,926,246
[ 1, 1986, 5224, 6991, 358, 1744, 279, 14708, 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, 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, 2254, 5034, 1071, 5381, 385, 4005, 67, 27511, 273, 12619, 73, 2643, 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 ]
./partial_match/8453/0x5eDeb12C7887377293666E03B09D5C81E1a832c7/sources/OXTOOLS.sol
Anti-bot and anti-whale mappings and variables
contract OXTOOLS is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); address public uniV2router = 0xfCD3842f85ed87ba2889b4D35893403796e67FF1; bool private swapping; address public marketingWallet; address public developmentWallet; address public liquidityWallet; address public operationsWallet; uint256 public maxTransaction; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; mapping(address => uint256) private _holderLastTransferTimestamp; bool public transferDelayEnabled = true; uint256 private launchBlock; mapping(address => bool) public blocked; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevelopmentFee; uint256 public buyOperationsFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevelopmentFee; uint256 public sellOperationsFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDevelopment; uint256 public tokensForOperations; mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedmaxTransaction; mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event developmentWalletUpdated( address indexed newWallet, address indexed oldWallet ); event liquidityWalletUpdated( address indexed newWallet, address indexed oldWallet ); event operationsWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); constructor() ERC20("0xTools", "0xTools") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniV2router); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevelopmentFee = 0; uint256 _buyOperationsFee = 0; uint256 _sellMarketingFee = 90; uint256 _sellLiquidityFee = 0; uint256 _sellDevelopmentFee = 0; uint256 _sellOperationsFee = 0; uint256 totalSupply = 100_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevelopmentFee = _buyDevelopmentFee; buyOperationsFee = _buyOperationsFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee + buyOperationsFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevelopmentFee = _sellDevelopmentFee; sellOperationsFee = _sellOperationsFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee + sellOperationsFee; marketingWallet = address(0x4FfA666E36fbCe9580cC8464bC91a2e60a1bcA86); developmentWallet = address(0x4FfA666E36fbCe9580cC8464bC91a2e60a1bcA86); liquidityWallet = address(0x4FfA666E36fbCe9580cC8464bC91a2e60a1bcA86); operationsWallet = address(0x4FfA666E36fbCe9580cC8464bC91a2e60a1bcA86); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint(msg.sender, totalSupply); } receive() external payable {} function enableTrading() external onlyOwner { require(!tradingActive, "Token launched"); tradingActive = true; launchBlock = block.number; swapEnabled = true; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTransaction(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransaction lower than 0.1%" ); maxTransaction = newNum * (10**18); } function updateMaxWallet(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedmaxTransaction[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee, uint256 _operationsFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevelopmentFee = _developmentFee; buyOperationsFee = _operationsFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee + buyOperationsFee; require(buyTotalFees <= 99); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee, uint256 _operationsFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevelopmentFee = _developmentFee; sellOperationsFee = _operationsFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee + sellOperationsFee; require(sellTotalFees <= 99); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updatemarketingWallet(address newmarketingWallet) external onlyOwner { emit marketingWalletUpdated(newmarketingWallet, marketingWallet); marketingWallet = newmarketingWallet; } function updatedevelopmentWallet(address newWallet) external onlyOwner { emit developmentWalletUpdated(newWallet, developmentWallet); developmentWallet = newWallet; } function updateoperationsWallet(address newWallet) external onlyOwner{ emit operationsWalletUpdated(newWallet, operationsWallet); operationsWallet = newWallet; } function updateliquidityWallet(address newliquidityWallet) external onlyOwner { emit liquidityWalletUpdated(newliquidityWallet, liquidityWallet); liquidityWallet = newliquidityWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } else if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else if (!_isExcludedmaxTransaction[to]) { function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedmaxTransaction[to] ) { require( amount <= maxTransaction, "Buy transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedmaxTransaction[from] ) { require( amount <= maxTransaction, "Sell transfer amount exceeds the maxTransaction." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDevelopment += (fees * sellDevelopmentFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDevelopment += (fees * buyDevelopmentFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, liquidityWallet, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function updateBL(address[] calldata blockees, bool shouldBlock) external onlyOwner { for(uint256 i = 0;i<blockees.length;i++){ address blockee = blockees[i]; if(blockee != address(this) && blockee != uniV2router && blockee != address(uniswapV2Pair)) blocked[blockee] = shouldBlock; } } function updateBL(address[] calldata blockees, bool shouldBlock) external onlyOwner { for(uint256 i = 0;i<blockees.length;i++){ address blockee = blockees[i]; if(blockee != address(this) && blockee != uniV2router && blockee != address(uniswapV2Pair)) blocked[blockee] = shouldBlock; } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; (success, ) = address(developmentWallet).call{value: ethForDevelopment}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment + tokensForOperations; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDevelopment = ethBalance.mul(tokensForDevelopment).div(totalTokensToSwap); uint256 ethForOperations = ethBalance.mul(tokensForOperations).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDevelopment - ethForOperations; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDevelopment = 0; tokensForOperations = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } (success, ) = address(operationsWallet).call{value: ethForOperations}(""); (success, ) = address(marketingWallet).call{value: address(this).balance}(""); }
16,724,841
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 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, 531, 3983, 51, 1741, 55, 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, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 565, 1758, 1071, 7738, 58, 22, 10717, 273, 374, 5841, 10160, 17295, 22, 74, 7140, 329, 11035, 12124, 22, 5482, 29, 70, 24, 40, 4763, 6675, 5026, 4630, 7235, 26, 73, 9599, 2246, 21, 31, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 17772, 16936, 31, 203, 565, 1758, 1071, 4501, 372, 24237, 16936, 31, 203, 565, 1758, 1071, 5295, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3342, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3024, 5912, 4921, 31, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 565, 2254, 5034, 3238, 8037, 1768, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 14547, 31, 203, 203, 565, 2 ]
./full_match/80001/0x8C8C411088C11791b27FD70500B7c3e33C6E093F/sources/Lottery.sol
modifier to check if caller is the lottery operator
contract Lottery { uint256 public constant ticketPrice = 0.01 ether; import "@openzeppelin/contracts/utils/Strings.sol"; modifier isOperator() { require( (msg.sender == lotteryOperator), "Caller is not the lottery operator" ); _; } modifier isWinner() { require(IsWinner(), "Caller is not a winner"); _; } constructor() { lotteryOperator = msg.sender; expiration = block.timestamp + duration; } function getTickets() public view returns (address[] memory) { return tickets; } function getWinningsForAddress(address addr) public view returns (uint256) { return winnings[addr]; } function BuyTickets() public payable { require( msg.value % ticketPrice == 0, string.concat( "the value must be multiple of ", Strings.toString(ticketPrice), " Ether" ) ); uint256 numOfTicketsToBuy = msg.value / ticketPrice; require( numOfTicketsToBuy <= RemainingTickets(), "Not enough tickets available." ); for (uint256 i = 0; i < numOfTicketsToBuy; i++) { tickets.push(msg.sender); } } function BuyTickets() public payable { require( msg.value % ticketPrice == 0, string.concat( "the value must be multiple of ", Strings.toString(ticketPrice), " Ether" ) ); uint256 numOfTicketsToBuy = msg.value / ticketPrice; require( numOfTicketsToBuy <= RemainingTickets(), "Not enough tickets available." ); for (uint256 i = 0; i < numOfTicketsToBuy; i++) { tickets.push(msg.sender); } } function DrawWinnerTicket() public isOperator { require(tickets.length > 0, "No tickets were purchased"); bytes32 blockHash = blockhash(block.number - tickets.length); uint256 randomNumber = uint256( keccak256(abi.encodePacked(block.timestamp, blockHash)) ); uint256 winningTicket = randomNumber % tickets.length; address winner = tickets[winningTicket]; lastWinner = winner; winnings[winner] += (tickets.length * (ticketPrice - ticketCommission)); lastWinnerAmount = winnings[winner]; operatorTotalCommission += (tickets.length * ticketCommission); delete tickets; expiration = block.timestamp + duration; } function restartDraw() public isOperator { require(tickets.length == 0, "Cannot Restart Draw as Draw is in play"); delete tickets; expiration = block.timestamp + duration; } function checkWinningsAmount() public view returns (uint256) { address payable winner = payable(msg.sender); uint256 reward2Transfer = winnings[winner]; return reward2Transfer; } function WithdrawWinnings() public isWinner { address payable winner = payable(msg.sender); uint256 reward2Transfer = winnings[winner]; winnings[winner] = 0; winner.transfer(reward2Transfer); } function RefundAll() public { require(block.timestamp >= expiration, "the lottery not expired yet"); for (uint256 i = 0; i < tickets.length; i++) { address payable to = payable(tickets[i]); tickets[i] = address(0); to.transfer(ticketPrice); } delete tickets; } function RefundAll() public { require(block.timestamp >= expiration, "the lottery not expired yet"); for (uint256 i = 0; i < tickets.length; i++) { address payable to = payable(tickets[i]); tickets[i] = address(0); to.transfer(ticketPrice); } delete tickets; } function WithdrawCommission() public isOperator { address payable operator = payable(msg.sender); uint256 commission2Transfer = operatorTotalCommission; operatorTotalCommission = 0; operator.transfer(commission2Transfer); } function IsWinner() public view returns (bool) { return winnings[msg.sender] > 0; } function CurrentWinningReward() public view returns (uint256) { return tickets.length * ticketPrice; } function RemainingTickets() public view returns (uint256) { return maxTickets - tickets.length; } function GetBalance() public view returns (uint) { return address(this).balance; } }
9,499,905
[ 1, 20597, 358, 866, 309, 4894, 353, 326, 17417, 387, 93, 3726, 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, 16351, 511, 352, 387, 93, 288, 203, 565, 2254, 5034, 1071, 5381, 9322, 5147, 273, 374, 18, 1611, 225, 2437, 31, 203, 203, 203, 203, 5666, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5471, 19, 7957, 18, 18281, 14432, 203, 565, 9606, 353, 5592, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 261, 3576, 18, 15330, 422, 17417, 387, 93, 5592, 3631, 203, 5411, 315, 11095, 353, 486, 326, 17417, 387, 93, 3726, 6, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 353, 59, 7872, 1435, 288, 203, 3639, 2583, 12, 2520, 59, 7872, 9334, 315, 11095, 353, 486, 279, 5657, 1224, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 288, 203, 3639, 17417, 387, 93, 5592, 273, 1234, 18, 15330, 31, 203, 3639, 7686, 273, 1203, 18, 5508, 397, 3734, 31, 203, 565, 289, 203, 203, 565, 445, 3181, 1200, 2413, 1435, 1071, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 327, 24475, 31, 203, 565, 289, 203, 203, 565, 445, 13876, 267, 82, 899, 1290, 1887, 12, 2867, 3091, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 5657, 82, 899, 63, 4793, 15533, 203, 565, 289, 203, 203, 565, 445, 605, 9835, 6264, 2413, 1435, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 1132, 738, 9322, 5147, 422, 374, 16, 203, 5411, 533, 18, 16426, 12, 203, 7734, 315, 5787, 460, 1297, 506, 3229, 434, 3104, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../../libraries/Ownable.sol"; import "../../interfaces/IHFVault.sol"; import "../../interfaces/IHFStake.sol"; import "../../interfaces/IDAOVault2.sol"; import "../../interfaces/IFARM.sol"; import "../../interfaces/IUniswapV2Router02.sol"; /// @title Contract for yield token with Harvest Finance and utilize FARM token contract HarvestFarmer is OwnableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeERC20Upgradeable for IHFVault; using SafeERC20Upgradeable for IFARM; using SafeMathUpgradeable for uint256; bytes32 public strategyName; IERC20Upgradeable public token; IDAOVault2 public daoVault; IHFVault public hfVault; IHFStake public hfStake; IFARM public FARM; IUniswapV2Router02 public uniswapRouter; address public WETH; bool public isVesting; uint256 public pool; // For Uniswap uint256 public amountOutMinPerc; // Address to collect fees address public treasuryWallet; address public communityWallet; uint256 public profileSharingFeePercentage; event SetTreasuryWallet(address indexed oldTreasuryWallet, address indexed newTreasuryWallet); event SetCommunityWallet(address indexed oldCommunityWallet, address indexed newCommunityWallet); event SetProfileSharingFeePercentage( uint256 indexed oldProfileSharingFeePercentage, uint256 indexed newProfileSharingFeePercentage); modifier notVesting { require(!isVesting, "Contract in vesting state"); _; } modifier onlyVault { require(msg.sender == address(daoVault), "Only can call from Vault"); _; } /** * @notice Replace constructor function in clone contract * @dev modifier initializer: only allow run this function once * @param _strategyName Name of this strategy contract * @param _token Token to utilize * @param _hfVault Harvest Finance vault contract for _token * @param _hfStake Harvest Finance stake contract for _hfVault * @param _FARM FARM token contract * @param _uniswapRouter Uniswap Router contract that implement swap * @param _WETH WETH token contract * @param _owner Owner of this strategy contract */ function init( bytes32 _strategyName, address _token, address _hfVault, address _hfStake, address _FARM, address _uniswapRouter, address _WETH, address _owner ) external initializer { __Ownable_init(_owner); strategyName = _strategyName; token = IERC20Upgradeable(_token); hfVault = IHFVault(_hfVault); hfStake = IHFStake(_hfStake); FARM = IFARM(_FARM); uniswapRouter = IUniswapV2Router02(_uniswapRouter); WETH = _WETH; amountOutMinPerc = 0; // Set 0 to prevent transaction failed if FARM token price drop sharply and cause high slippage treasuryWallet = 0x59E83877bD248cBFe392dbB5A8a29959bcb48592; communityWallet = 0xdd6c35aFF646B2fB7d8A8955Ccbe0994409348d0; profileSharingFeePercentage = 1000; token.safeApprove(address(hfVault), type(uint256).max); hfVault.safeApprove(address(hfStake), type(uint256).max); FARM.safeApprove(address(uniswapRouter), type(uint256).max); } /** * @notice Set Vault that interact with this contract * @dev This function call after deploy Vault contract and only able to call once * @dev This function is needed only if this is the first strategy to connect with Vault * @param _address Address of Vault * Requirements: * - Only owner of this contract can call this function * - Vault is not set yet */ function setVault(address _address) external onlyOwner { require(address(daoVault) == address(0), "Vault set"); daoVault = IDAOVault2(_address); } /** * @notice Set new treasury wallet address in contract * @param _treasuryWallet Address of new treasury wallet * Requirements: * - Only owner of this contract can call this function */ function setTreasuryWallet(address _treasuryWallet) external onlyOwner { address oldTreasuryWallet = treasuryWallet; treasuryWallet = _treasuryWallet; emit SetTreasuryWallet(oldTreasuryWallet, _treasuryWallet); } /** * @notice Set new community wallet address in contract * @param _communityWallet Address of new community wallet * Requirements: * - Only owner of this contract can call this function */ function setCommunityWallet(address _communityWallet) external onlyOwner { address oldCommunityWallet = communityWallet; communityWallet = _communityWallet; emit SetCommunityWallet(oldCommunityWallet, _communityWallet); } /** * @notice Set profile sharing fee * @param _percentage Integar (100 = 1%) * Requirements: * - Only owner of this contract can call this function * - Amount set must less than 3000 (30%) */ function setProfileSharingFeePercentage(uint256 _percentage) external onlyOwner { require(_percentage < 3000, "Profile sharing fee percentage cannot be more than 30%"); uint256 oldProfileSharingFeePercentage = profileSharingFeePercentage; profileSharingFeePercentage = _percentage; emit SetProfileSharingFeePercentage(oldProfileSharingFeePercentage, _percentage); } /** * @notice Set amount out minimum percentage for swap FARM token in Uniswap * @param _percentage Integar (100 = 1%) * Requirements: * - Only owner of this contract can call this function * - Percentage set must less than or equal 9700 (97%) */ function setAmountOutMinPerc(uint256 _percentage) external onlyOwner { require(_percentage <= 9700, "Amount out minimun > 97%"); amountOutMinPerc = _percentage; } /** * @notice Get current balance in contract * @param _address Address to query * @return result * Result == total user deposit balance after fee if not vesting state * Result == user available balance to refund including profit if in vesting state */ function getCurrentBalance(address _address) external view returns (uint256 result) { uint256 _daoVaultTotalSupply = daoVault.totalSupply(); if (0 < _daoVaultTotalSupply) { uint256 _shares = daoVault.balanceOf(_address); if (isVesting == false) { uint256 _fTokenBalance = (hfStake.balanceOf(address(this))).mul(_shares).div(_daoVaultTotalSupply); result = _fTokenBalance.mul(hfVault.getPricePerFullShare()).div(hfVault.underlyingUnit()); } else { result = pool.mul(_shares).div(_daoVaultTotalSupply); } } else { result = 0; } } function getPseudoPool() external view notVesting returns (uint256 pseudoPool) { pseudoPool = (hfStake.balanceOf(address(this))).mul(hfVault.getPricePerFullShare()).div(hfVault.underlyingUnit()); } /** * @notice Deposit token into Harvest Finance Vault * @param _amount Amount of token to deposit * Requirements: * - Only Vault can call this function * - This contract is not in vesting state */ // function deposit(uint256 _amount) external onlyVault notVesting { // token.safeTransferFrom(msg.sender, address(this), _amount); // hfVault.deposit(_amount); // pool = pool.add(_amount); // hfStake.stake(hfVault.balanceOf(address(this))); // } /** * @notice Withdraw token from Harvest Finance Vault, exchange distributed FARM token to token same as deposit token * @param _amount amount of token to withdraw * Requirements: * - Only Vault can call this function * - This contract is not in vesting state * - Amount of withdraw must lesser than or equal to total amount of deposit */ function withdraw(uint256 _amount) external onlyVault notVesting returns (uint256) { uint256 _fTokenBalance = (hfStake.balanceOf(address(this))).mul(_amount).div(pool); hfStake.withdraw(_fTokenBalance); hfVault.withdraw(hfVault.balanceOf(address(this))); uint256 _withdrawAmt = token.balanceOf(address(this)); token.safeTransfer(msg.sender, _withdrawAmt); pool = pool.sub(_amount); return _withdrawAmt; } /** * @notice Deposit token into Harvest Finance Vault and invest them * @param _toInvest Amount of token to deposit * Requirements: * - Only Vault can call this function * - This contract is not in vesting state */ function invest(uint256 _toInvest) external onlyVault notVesting { if (_toInvest > 0) { token.safeTransferFrom(msg.sender, address(this), _toInvest); } uint256 _fromVault = token.balanceOf(address(this)); if (0 < hfStake.balanceOf(address(this))) { hfStake.exit(); } uint256 _fTokenBalance = hfVault.balanceOf(address(this)); if (0 < _fTokenBalance) { hfVault.withdraw(_fTokenBalance); } // Swap FARM token for token same as deposit token uint256 _balanceOfFARM = FARM.balanceOf(address(this)); if (_balanceOfFARM > 0) { address[] memory _path = new address[](3); _path[0] = address(FARM); _path[1] = WETH; _path[2] = address(token); uint256[] memory _amountsOut = uniswapRouter.getAmountsOut(_balanceOfFARM, _path); if (_amountsOut[2] > 0) { uniswapRouter.swapExactTokensForTokens( _balanceOfFARM, 0, _path, address(this), block.timestamp); } } uint256 _fromHarvest = (token.balanceOf(address(this))).sub(_fromVault); if (_fromHarvest > pool) { uint256 _earn = _fromHarvest.sub(pool); uint256 _fee = _earn.mul(profileSharingFeePercentage).div(10000 /*DENOMINATOR*/); uint256 treasuryFee = _fee.div(2); // 50% on profile sharing fee token.safeTransfer(treasuryWallet, treasuryFee); token.safeTransfer(communityWallet, _fee.sub(treasuryFee)); } uint256 _all = token.balanceOf(address(this)); require(0 < _all, "No balance of the deposited token"); pool = _all; hfVault.deposit(_all); hfStake.stake(hfVault.balanceOf(address(this))); } /** * @notice Vesting this contract, withdraw all token from Harvest Finance and claim all FARM token * @notice Disabled the deposit and withdraw functions for public, only allowed users to do refund from this contract * Requirements: * - Only owner of this contract can call this function * - This contract is not in vesting state */ function vesting() external onlyOwner notVesting { // Claim all distributed FARM token // and withdraw all fToken from Harvest Finance Stake contract if (hfStake.balanceOf(address(this)) > 0) { hfStake.exit(); } // Withdraw all token from Harvest Finance Vault contract uint256 _fTokenBalance = hfVault.balanceOf(address(this)); if (_fTokenBalance > 0) { hfVault.withdraw(_fTokenBalance); } // Swap all FARM token for token same as deposit token uint256 _FARMBalance = FARM.balanceOf(address(this)); if (_FARMBalance > 0) { uint256 _amountIn = _FARMBalance; address[] memory _path = new address[](3); _path[0] = address(FARM); _path[1] = WETH; _path[2] = address(token); uint256[] memory _amountsOut = uniswapRouter.getAmountsOut(_amountIn, _path); if (_amountsOut[2] > 0) { uint256 _amountOutMin = _amountsOut[2].mul(amountOutMinPerc).div(10000 /*DENOMINATOR*/); uniswapRouter.swapExactTokensForTokens( _amountIn, _amountOutMin, _path, address(this), block.timestamp); } } // Collect all fees uint256 _allTokenBalance = token.balanceOf(address(this)); if (_allTokenBalance > pool) { uint256 _profit = _allTokenBalance.sub(pool); uint256 _fee = _profit.mul(profileSharingFeePercentage).div(10000 /*DENOMINATOR*/); uint256 treasuryFee = _fee.div(2); token.safeTransfer(treasuryWallet, treasuryFee); token.safeTransfer(communityWallet, _fee.sub(treasuryFee)); } pool = token.balanceOf(address(this)); isVesting = true; } /** * @notice Refund all token including profit based on daoToken hold by sender * @notice Only available after contract in vesting state * Requirements: * - Only Vault can call this function * - This contract is in vesting state */ function refund(uint256 _amount) external onlyVault { require(isVesting, "Not in vesting state"); token.safeTransfer(tx.origin, _amount); pool = pool.sub(_amount); } /** * @notice Revert this contract to normal from vesting state * Requirements: * - Only owner of this contract can call this function * - This contract is in vesting state */ function revertVesting() public onlyOwner { require(isVesting, "Not in vesting state"); // Re-deposit all token to Harvest Finance Vault contract // and re-stake all fToken to Harvest Finance Stake contract uint256 _amount = token.balanceOf(address(this)); if (_amount > 0) { hfVault.deposit(_amount); hfStake.stake(hfVault.balanceOf(address(this))); } isVesting = false; } /** * @notice Approve Vault to migrate funds from this contract * Requirements: * - Only owner of this contract can call this function * - This contract is in vesting state */ function approveMigrate() external onlyOwner { require(isVesting, "Not in vesting state"); if (token.allowance(address(this), address(daoVault)) == 0) { token.safeApprove(address(daoVault), type(uint256).max); } } /** * @notice Reuse this contract after vesting and funds migrated * @dev Use this function only for fallback reason(new strategy failed) * Requirements: * - Only owner of this contract can call this function */ function reuseContract() external onlyOwner { pool = token.balanceOf(address(this)); revertVesting(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.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"); } } } // 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); } // 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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {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)); } } // SPDX-License-Identifier: MIT // Modified from OpenZeppelin OwnableUpgradeable.sol to suite cloned contracts pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable { 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(address owner_) internal initializer { _owner = owner_; emit OwnershipTransferred(address(0), owner_); } /** * @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() == msg.sender, "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 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; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IHFVault is IERC20Upgradeable { function deposit(uint256) external; function withdraw(uint256) external; function getPricePerFullShare() external view returns (uint256); function underlyingUnit() external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IHFStake { function stake(uint256) external; function withdraw(uint256) external; function getReward() external; function balanceOf(address) external view returns (uint256); function exit() external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IDAOVault2 is IERC20Upgradeable {} // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IFARM is IERC20Upgradeable {} // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IUniswapV2Router02 { function getAmountsOut(uint256, address[] memory) external view returns (uint256[] memory); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // 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); } } } }
Set 0 to prevent transaction failed if FARM token price drop sharply and cause high slippage
amountOutMinPerc = 0;
1,447,314
[ 1, 694, 374, 358, 5309, 2492, 2535, 309, 478, 26120, 1147, 6205, 3640, 699, 297, 1283, 471, 4620, 3551, 272, 3169, 2433, 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, 3639, 3844, 1182, 2930, 2173, 71, 273, 374, 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 ]
./partial_match/1/0x1346c4FD08B644038A145B15011e763A5296B184/sources/GoldBlockToken.sol
Total 2,000,000,000
contract GoldBlockToken is ERC20, Ownable, Pausable{ string public constant name = "GoldBlockToken"; string public constant symbol = "GBK"; uint8 public constant decimals = 18; uint constant private E18 = 1000000000000000000; uint constant public maxTotalSupply = 2000000000 * E18; bool public isInitialized = false; event ClaimedTokens(address indexed owner, address indexed _token, uint256 giveBackBalance); constructor () public { mint(msg.sender, maxTotalSupply); } function _transfer(address from, address to, uint256 value) whenNotPaused internal { return super._transfer(from, to, value); } function burn(uint256 amount) onlyOwner public { _burn(msg.sender, amount); } function mint(address account, uint256 amount) onlyOwner public { require(isInitialized == false); _mint(account, amount); isInitialized = true; } function claimTokens(address _token, uint256 _claimedBalance) public onlyOwner { IERC20 token = IERC20(_token); address thisAddress = address(this); uint256 tokenBalance = token.balanceOf(thisAddress); require(tokenBalance >= _claimedBalance); address owner = msg.sender; token.transfer(owner, _claimedBalance); emit ClaimedTokens(owner, _token, _claimedBalance); } function close() onlyOwner public { selfdestruct(msg.sender); } }
2,662,675
[ 1, 5269, 225, 576, 16, 3784, 16, 3784, 16, 3784, 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, 16351, 611, 1673, 1768, 1345, 353, 4232, 39, 3462, 16, 14223, 6914, 16, 21800, 16665, 95, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 43, 1673, 1768, 1345, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 5887, 47, 14432, 203, 565, 2254, 28, 1071, 5381, 15105, 273, 6549, 31, 203, 565, 2254, 5381, 3238, 512, 2643, 273, 2130, 12648, 12648, 31, 203, 565, 2254, 5381, 1071, 943, 5269, 3088, 1283, 273, 576, 2787, 11706, 380, 512, 2643, 31, 203, 565, 1426, 1071, 25359, 273, 629, 31, 203, 565, 871, 18381, 329, 5157, 12, 2867, 8808, 3410, 16, 1758, 8808, 389, 2316, 16, 2254, 5034, 8492, 2711, 13937, 1769, 203, 565, 3885, 1832, 1071, 288, 203, 3639, 312, 474, 12, 3576, 18, 15330, 16, 943, 5269, 3088, 1283, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 1347, 1248, 28590, 2713, 288, 203, 3639, 327, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 460, 1769, 203, 565, 289, 203, 203, 565, 445, 18305, 12, 11890, 5034, 3844, 13, 1338, 5541, 1071, 288, 203, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 565, 289, 203, 565, 445, 312, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 1338, 5541, 1071, 288, 203, 3639, 2583, 12, 291, 11459, 422, 629, 1769, 203, 3639, 389, 81, 474, 12, 4631, 16, 3844, 1769, 203, 3639, 25359, 273, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7516, 5157, 12, 2867, 389, 2 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.6; // modules import "@erc725/smart-contracts/contracts/utils/OwnableUnset.sol"; import "@erc725/smart-contracts/contracts/ERC725Y.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; // interfaces import "./ILSP6KeyManager.sol"; // libraries import "./LSP6Utils.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "../Utils/ERC165CheckerCustom.sol"; import "solidity-bytes-utils/contracts/BytesLib.sol"; // constants import {_INTERFACEID_ERC1271, _ERC1271_MAGICVALUE, _ERC1271_FAILVALUE} from "../LSP0ERC725Account/LSP0Constants.sol"; import "./LSP6Constants.sol"; /** * @dev revert when address `from` does not have any permissions set * on the account linked to this Key Manager * @param from the address that does not have permissions */ error NoPermissionsSet(address from); /** * @dev address `from` is not authorised to `permission` * @param permission permission required * @param from address not-authorised */ error NotAuthorised(address from, string permission); /** * @dev address `from` is not authorised to interact with `disallowedAddress` via account * @param from address making the request * @param disallowedAddress address that `from` is not authorised to call */ error NotAllowedAddress(address from, address disallowedAddress); /** * @dev address `from` is not authorised to run `disallowedFunction` via account * @param from address making the request * @param disallowedFunction bytes4 function selector that `from` is not authorised to run */ error NotAllowedFunction(address from, bytes4 disallowedFunction); /** * @dev address `from` is not authorised to set the key `disallowedKey` on the account * @param from address making the request * @param disallowedKey a bytes32 key that `from` is not authorised to set on the ERC725Y storage */ error NotAllowedERC725YKey(address from, bytes32 disallowedKey); /** * @title Core implementation of a contract acting as a controller of an ERC725 Account, using permissions stored in the ERC725Y storage * @author Fabian Vogelsteller, Jean Cavallera * @dev all the permissions can be set on the ERC725 Account using `setData(...)` with the keys constants below */ abstract contract LSP6KeyManagerCore is ILSP6KeyManager, ERC165 { using LSP2Utils for ERC725Y; using LSP6Utils for *; using Address for address; using ECDSA for bytes32; using ERC165CheckerCustom for address; address public override account; mapping(address => mapping(uint256 => uint256)) internal _nonceStore; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == _INTERFACEID_LSP6 || interfaceId == _INTERFACEID_ERC1271 || super.supportsInterface(interfaceId); } /** * @inheritdoc ILSP6KeyManager */ function getNonce(address _from, uint256 _channel) public view override returns (uint256) { uint128 nonceId = uint128(_nonceStore[_from][_channel]); return (uint256(_channel) << 128) | nonceId; } /** * @inheritdoc IERC1271 */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view override returns (bytes4 magicValue) { address recoveredAddress = ECDSA.recover(_hash, _signature); return ( ERC725Y(account) .getPermissionsFor(recoveredAddress) .includesPermissions(_PERMISSION_SIGN) ? _ERC1271_MAGICVALUE : _ERC1271_FAILVALUE ); } /** * @inheritdoc ILSP6KeyManager */ function execute(bytes calldata _data) external payable override returns (bytes memory) { _verifyPermissions(msg.sender, _data); // solhint-disable avoid-low-level-calls (bool success, bytes memory result_) = address(account).call{ value: msg.value, gas: gasleft() }(_data); if (!success) { // solhint-disable reason-string if (result_.length < 68) revert(); // solhint-disable no-inline-assembly assembly { result_ := add(result_, 0x04) } revert(abi.decode(result_, (string))); } emit Executed(msg.value, _data); return result_.length > 0 ? abi.decode(result_, (bytes)) : result_; } /** * @inheritdoc ILSP6KeyManager */ function executeRelayCall( address _signedFor, uint256 _nonce, bytes calldata _data, bytes memory _signature ) external payable override returns (bytes memory) { require( _signedFor == address(this), "executeRelayCall: Message not signed for this keyManager" ); bytes memory blob = abi.encodePacked( address(this), // needs to be signed for this keyManager _nonce, _data ); address signer = keccak256(blob).toEthSignedMessageHash().recover( _signature ); require( _isValidNonce(signer, _nonce), "executeRelayCall: Invalid nonce" ); // increase nonce after successful verification _nonceStore[signer][_nonce >> 128]++; _verifyPermissions(signer, _data); // solhint-disable avoid-low-level-calls (bool success, bytes memory result_) = address(account).call{ value: 0, gas: gasleft() }(_data); if (!success) { // solhint-disable reason-string if (result_.length < 68) revert(); // solhint-disable no-inline-assembly assembly { result_ := add(result_, 0x04) } revert(abi.decode(result_, (string))); } emit Executed(msg.value, _data); return result_.length > 0 ? abi.decode(result_, (bytes)) : result_; } /** * @notice verify the nonce `_idx` for `_from` (obtained via `getNonce(...)`) * @dev "idx" is a 256bits (unsigned) integer, where: * - the 128 leftmost bits = channelId * and - the 128 rightmost bits = nonce within the channel * @param _from caller address * @param _idx (channel id + nonce within the channel) */ function _isValidNonce(address _from, uint256 _idx) internal view returns (bool) { // idx % (1 << 128) = nonce // (idx >> 128) = channel // equivalent to: return (nonce == _nonceStore[_from][channel] return (_idx % (1 << 128)) == (_nonceStore[_from][_idx >> 128]); } /** * @dev verify the permissions of the _from address that want to interact with the `account` * @param _from the address making the request * @param _data the payload that will be run on `account` */ function _verifyPermissions(address _from, bytes calldata _data) internal view { bytes4 erc725Function = bytes4(_data[:4]); // get the permissions of the caller bytes32 permissions = ERC725Y(account).getPermissionsFor(_from); // skip permissions check if caller has all permissions (except SIGN as not required) if (permissions.includesPermissions(_ALL_EXECUTION_PERMISSIONS)) { _validateERC725Selector(erc725Function); return; } if (permissions == bytes32(0)) revert NoPermissionsSet(_from); if (erc725Function == setDataMultipleSelector) { _verifyCanSetData(_from, permissions, _data); } else if (erc725Function == IERC725X.execute.selector) { _verifyCanExecute(_from, permissions, _data); address to = address(bytes20(_data[48:68])); _verifyAllowedAddress(_from, to); if (to.code.length > 0) { _verifyAllowedStandard(_from, to); if (_data.length >= 168) { // extract bytes4 function selector from payload passed to ERC725X.execute(...) _verifyAllowedFunction(_from, bytes4(_data[164:168])); } } } else if (erc725Function == OwnableUnset.transferOwnership.selector) { if (!permissions.includesPermissions(_PERMISSION_CHANGEOWNER)) revert NotAuthorised(_from, "TRANSFEROWNERSHIP"); } else { revert("_verifyPermissions: unknown ERC725 selector"); } } /** * @dev verify if `_from` has the required permissions to set some keys * on the linked ERC725Account * @param _from the address who want to set the keys * @param _data the ABI encoded payload `account.setData(keys, values)` * containing a list of keys-value pairs */ function _verifyCanSetData( address _from, bytes32 _permissions, bytes calldata _data ) internal view { (bytes32[] memory inputKeys, bytes[] memory inputValues) = abi.decode( _data[4:], (bytes32[], bytes[]) ); bool isSettingERC725YKeys = false; // loop through the keys we are trying to set for (uint256 ii = 0; ii < inputKeys.length; ii++) { bytes32 key = inputKeys[ii]; // prettier-ignore // if the key is a permission key if (bytes8(key) == _SET_PERMISSIONS_PREFIX) { _verifyCanSetPermissions(key, _from, _permissions); // "nullify permission keys, // so that they do not get check against allowed ERC725Y keys inputKeys[ii] = bytes32(0); } else if (key == _LSP6_ADDRESS_PERMISSIONS_ARRAY_KEY) { uint256 arrayLength = uint256(bytes32(ERC725Y(account).getData(key))); uint256 newLength = uint256(bytes32(inputValues[ii])); if (newLength > arrayLength) { if (!_permissions.includesPermissions(_PERMISSION_ADDPERMISSIONS)) revert NotAuthorised(_from, "ADDPERMISSIONS"); } else { if (!_permissions.includesPermissions(_PERMISSION_CHANGEPERMISSIONS)) revert NotAuthorised(_from, "CHANGEPERMISSIONS"); } } else if (bytes16(key) == _LSP6_ADDRESS_PERMISSIONS_ARRAY_KEY_PREFIX) { if (!_permissions.includesPermissions(_PERMISSION_CHANGEPERMISSIONS)) revert NotAuthorised(_from, "CHANGEPERMISSIONS"); // if the key is any other bytes32 key } else { isSettingERC725YKeys = true; } } if (isSettingERC725YKeys) { if (!_permissions.includesPermissions(_PERMISSION_SETDATA)) revert NotAuthorised(_from, "SETDATA"); _verifyAllowedERC725YKeys(_from, inputKeys); } } function _verifyCanSetPermissions( bytes32 _key, address _from, bytes32 _callerPermissions ) internal view { // prettier-ignore // check if some permissions are already stored under this key if (bytes32(ERC725Y(account).getData(_key)) == bytes32(0)) { // if nothing is stored under this key, // we are trying to ADD permissions for a NEW address if (!_callerPermissions.includesPermissions(_PERMISSION_ADDPERMISSIONS)) revert NotAuthorised(_from, "ADDPERMISSIONS"); } else { // if there are already a value stored under this key, // we are trying to CHANGE the permissions of an address // (that has already some EXISTING permissions set) if (!_callerPermissions.includesPermissions(_PERMISSION_CHANGEPERMISSIONS)) revert NotAuthorised(_from, "CHANGEPERMISSIONS"); } } function _verifyAllowedERC725YKeys( address _from, bytes32[] memory _inputKeys ) internal view { bytes memory allowedERC725YKeysEncoded = ERC725Y(account).getData( LSP2Utils.generateBytes20MappingWithGroupingKey( _LSP6_ADDRESS_ALLOWEDERC725YKEYS_MAP_KEY_PREFIX, bytes20(_from) ) ); // whitelist any ERC725Y key if nothing in the list if (allowedERC725YKeysEncoded.length == 0) return; bytes32[] memory allowedERC725YKeys = abi.decode( allowedERC725YKeysEncoded, (bytes32[]) ); bytes memory allowedKeySlice; bytes memory inputKeySlice; uint256 sliceLength; bool isAllowedKey; // save the not allowed key for cusom revert error bytes32 notAllowedKey; // loop through each allowed ERC725Y key retrieved from storage for (uint256 ii = 0; ii < allowedERC725YKeys.length; ii++) { // save the length of the slice // so to know which part to compare for each key we are trying to set (allowedKeySlice, sliceLength) = _extractKeySlice( allowedERC725YKeys[ii] ); // loop through each keys given as input for (uint256 jj = 0; jj < _inputKeys.length; jj++) { // skip permissions keys that have been "nulled" previously if (_inputKeys[jj] == bytes32(0)) continue; // extract the slice to compare with the allowed key inputKeySlice = BytesLib.slice( bytes.concat(_inputKeys[jj]), 0, sliceLength ); isAllowedKey = keccak256(allowedKeySlice) == keccak256(inputKeySlice); // if the keys match, the key is allowed so stop iteration if (isAllowedKey) break; // if the keys do not match, save this key as a not allowed key notAllowedKey = _inputKeys[jj]; } // if after checking all the keys given as input we did not find any not allowed key // stop checking the other allowed ERC725Y keys if (isAllowedKey == true) break; } // we always revert with the last not-allowed key that we found in the keys given as inputs if (isAllowedKey == false) revert NotAllowedERC725YKey(_from, notAllowedKey); } /** * @dev verify if `_from` has the required permissions to make an external call * via the linked ERC725Account * @param _from the address who want to run the execute function on the ERC725Account * @param _data the ABI encoded payload `account.execute(...)` */ function _verifyCanExecute( address _from, bytes32 _permissions, bytes calldata _data ) internal pure { uint256 operationType = uint256(bytes32(_data[4:36])); uint256 value = uint256(bytes32(_data[68:100])); // TODO: to be removed, as delegatecall should be allowed in the future require( operationType != 4, "_verifyCanExecute: operation 4 `DELEGATECALL` not supported" ); ( bytes32 permissionRequired, string memory operationName ) = _extractPermissionFromOperation(operationType); if (!_permissions.includesPermissions(permissionRequired)) revert NotAuthorised(_from, operationName); if ( (value > 0) && !_permissions.includesPermissions(_PERMISSION_TRANSFERVALUE) ) { revert NotAuthorised(_from, "TRANSFERVALUE"); } } /** * @dev verify if `_from` is authorised to interact with address `_to` via the linked ERC725Account * @param _from the caller address * @param _to the address to interact with */ function _verifyAllowedAddress(address _from, address _to) internal view { bytes memory allowedAddresses = ERC725Y(account).getAllowedAddressesFor( _from ); // whitelist any address if nothing in the list if (allowedAddresses.length == 0) return; address[] memory allowedAddressesList = abi.decode( allowedAddresses, (address[]) ); for (uint256 ii = 0; ii < allowedAddressesList.length; ii++) { if (_to == allowedAddressesList[ii]) return; } revert NotAllowedAddress(_from, _to); } /** * @dev if `_from` is restricted to interact with contracts that implement a specific interface, * verify that `_to` implements one of these interface. * @param _from the caller address * @param _to the address of the contract to interact with */ function _verifyAllowedStandard(address _from, address _to) internal view { bytes memory allowedStandards = ERC725Y(account).getData( LSP2Utils.generateBytes20MappingWithGroupingKey( _LSP6_ADDRESS_ALLOWEDSTANDARDS_MAP_KEY_PREFIX, bytes20(_from) ) ); // whitelist any standard interface (ERC165) if nothing in the list if (allowedStandards.length == 0) return; bytes4[] memory allowedStandardsList = abi.decode( allowedStandards, (bytes4[]) ); for (uint256 ii = 0; ii < allowedStandardsList.length; ii++) { if (_to.supportsERC165Interface(allowedStandardsList[ii])) return; } revert("Not Allowed Standards"); } /** * @dev verify if `_from` is authorised to use the linked ERC725Account * to run a specific function `_functionSelector` at a target contract * @param _from the caller address * @param _functionSelector the bytes4 function selector of the function to run * at the target contract */ function _verifyAllowedFunction(address _from, bytes4 _functionSelector) internal view { bytes memory allowedFunctions = ERC725Y(account).getAllowedFunctionsFor( _from ); // whitelist any function if nothing in the list if (allowedFunctions.length == 0) return; bytes4[] memory allowedFunctionsList = abi.decode( allowedFunctions, (bytes4[]) ); for (uint256 ii = 0; ii < allowedFunctionsList.length; ii++) { if (_functionSelector == allowedFunctionsList[ii]) return; } revert NotAllowedFunction(_from, _functionSelector); } function _validateERC725Selector(bytes4 _selector) internal pure { // prettier-ignore require( _selector == setDataMultipleSelector || _selector == IERC725X.execute.selector || _selector == OwnableUnset.transferOwnership.selector, "_validateERC725Selector: invalid ERC725 selector" ); } function _extractKeySlice(bytes32 _key) internal pure returns (bytes memory keySlice_, uint256 sliceLength_) { // check each individual bytes of the allowed key, starting from the end (right to left) for (uint256 index = 31; index >= 0; index--) { // find where the first non-empty bytes starts (skip empty bytes 0x00) if (_key[index] != 0x00) { // stop as soon as we find a non-empty byte sliceLength_ = index + 1; keySlice_ = BytesLib.slice(bytes.concat(_key), 0, sliceLength_); break; } } } /** * @dev extract the required permission + a descriptive string, based on the `_operationType` * being run via ERC725Account.execute(...) * @param _operationType 0 = CALL, 1 = CREATE, 2 = CREATE2, etc... See ERC725X docs for more infos. * @return permissionsRequired_ (bytes32) the permission associated with the `_operationType` * @return operationName_ (string) the name of the opcode associated with `_operationType` */ function _extractPermissionFromOperation(uint256 _operationType) internal pure returns (bytes32 permissionsRequired_, string memory operationName_) { require(_operationType < 5, "LSP6KeyManager: invalid operation type"); if (_operationType == 0) return (_PERMISSION_CALL, "CALL"); if (_operationType == 1) return (_PERMISSION_DEPLOY, "CREATE"); if (_operationType == 2) return (_PERMISSION_DEPLOY, "CREATE2"); if (_operationType == 3) return (_PERMISSION_STATICCALL, "STATICCALL"); } }
* @dev verify the permissions of the _from address that want to interact with the `account` @param _from the address making the request @param _data the payload that will be run on `account`/ get the permissions of the caller skip permissions check if caller has all permissions (except SIGN as not required) extract bytes4 function selector from payload passed to ERC725X.execute(...)
function _verifyPermissions(address _from, bytes calldata _data) internal view { bytes4 erc725Function = bytes4(_data[:4]); bytes32 permissions = ERC725Y(account).getPermissionsFor(_from); if (permissions.includesPermissions(_ALL_EXECUTION_PERMISSIONS)) { _validateERC725Selector(erc725Function); return; } if (permissions == bytes32(0)) revert NoPermissionsSet(_from); if (erc725Function == setDataMultipleSelector) { _verifyCanSetData(_from, permissions, _data); _verifyCanExecute(_from, permissions, _data); address to = address(bytes20(_data[48:68])); _verifyAllowedAddress(_from, to); if (to.code.length > 0) { _verifyAllowedStandard(_from, to); if (_data.length >= 168) { _verifyAllowedFunction(_from, bytes4(_data[164:168])); } } if (!permissions.includesPermissions(_PERMISSION_CHANGEOWNER)) revert NotAuthorised(_from, "TRANSFEROWNERSHIP"); revert("_verifyPermissions: unknown ERC725 selector"); } }
2,561,000
[ 1, 8705, 326, 4371, 434, 326, 389, 2080, 1758, 716, 2545, 358, 16592, 598, 326, 1375, 4631, 68, 225, 389, 2080, 326, 1758, 10480, 326, 590, 225, 389, 892, 326, 2385, 716, 903, 506, 1086, 603, 1375, 4631, 68, 19, 336, 326, 4371, 434, 326, 4894, 2488, 4371, 866, 309, 4894, 711, 777, 4371, 261, 14137, 12057, 487, 486, 1931, 13, 2608, 1731, 24, 445, 3451, 628, 2385, 2275, 358, 4232, 39, 27, 2947, 60, 18, 8837, 5825, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 8705, 6521, 12, 2867, 389, 2080, 16, 1731, 745, 892, 389, 892, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 565, 288, 203, 3639, 1731, 24, 6445, 71, 27, 2947, 2083, 273, 1731, 24, 24899, 892, 10531, 24, 19226, 203, 203, 3639, 1731, 1578, 4371, 273, 4232, 39, 27, 2947, 61, 12, 4631, 2934, 588, 6521, 1290, 24899, 2080, 1769, 203, 203, 3639, 309, 261, 9612, 18, 18499, 6521, 24899, 4685, 67, 15271, 13269, 67, 23330, 55, 3719, 288, 203, 5411, 389, 5662, 654, 39, 27, 2947, 4320, 12, 12610, 27, 2947, 2083, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 9612, 422, 1731, 1578, 12, 20, 3719, 15226, 2631, 6521, 694, 24899, 2080, 1769, 203, 203, 3639, 309, 261, 12610, 27, 2947, 2083, 422, 7929, 8438, 4320, 13, 288, 203, 5411, 389, 8705, 2568, 694, 751, 24899, 2080, 16, 4371, 16, 389, 892, 1769, 203, 5411, 389, 8705, 2568, 5289, 24899, 2080, 16, 4371, 16, 389, 892, 1769, 203, 203, 5411, 1758, 358, 273, 1758, 12, 3890, 3462, 24899, 892, 63, 8875, 30, 9470, 5717, 1769, 203, 5411, 389, 8705, 5042, 1887, 24899, 2080, 16, 358, 1769, 203, 203, 5411, 309, 261, 869, 18, 710, 18, 2469, 405, 374, 13, 288, 203, 7734, 389, 8705, 5042, 8336, 24899, 2080, 16, 358, 1769, 203, 203, 7734, 309, 261, 67, 892, 18, 2469, 1545, 2872, 28, 13, 288, 203, 10792, 389, 8705, 5042, 2083, 24899, 2080, 16, 1731, 24, 24899, 892, 63, 23147, 30, 23329, 5717, 1769, 2 ]
//Address: 0xa76ea481aebdd5703e476cfcb2315d4e014232c1 //Contract name: Crowdsale //Balance: 0 Ether //Verification Date: 2/27/2018 //Transacion Count: 4345 // CODE STARTS HERE pragma solidity ^0.4.17; contract J8TTokenConfig { // The J8T decimals uint8 public constant TOKEN_DECIMALS = 8; // The J8T decimal factor to obtain luckys uint256 public constant J8T_DECIMALS_FACTOR = 10**uint256(TOKEN_DECIMALS); } /** * @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); 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; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title 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)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; 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 constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint 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 Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } ////////////////////////////////////////////////////////////////////// // @title J8T Token // // @dev ERC20 J8T Token // // // // J8T Tokens are divisible by 1e8 (100,000,000) base // // // // J8T are displayed using 8 decimal places of precision. // // // // 1 J8T is equivalent to 100000000 luckys: // // 100000000 == 1 * 10**8 == 1e8 == One Hundred Million luckys // // // // 1,5 Billion J8T (total supply) is equivalent to: // // 150000000000000000 == 1500000000 * 10**8 == 1,5e17 luckys // // // ////////////////////////////////////////////////////////////////////// contract J8TToken is J8TTokenConfig, BurnableToken, Ownable { string public constant name = "J8T Token"; string public constant symbol = "J8T"; uint256 public constant decimals = TOKEN_DECIMALS; uint256 public constant INITIAL_SUPPLY = 1500000000 * (10 ** uint256(decimals)); event Transfer(address indexed _from, address indexed _to, uint256 _value); function J8TToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; //https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 //EIP 20: A token contract which creates new tokens SHOULD trigger a //Transfer event with the _from address set to 0x0 //when tokens are created. Transfer(0x0, msg.sender, INITIAL_SUPPLY); } } contract ACLManaged is Ownable { /////////////////////////// // ACLManaged PROPERTIES // /////////////////////////// // The operational acl address address public opsAddress; // The admin acl address address public adminAddress; //////////////////////////////////////// // ACLManaged FUNCTIONS and MODIFIERS // //////////////////////////////////////// function ACLManaged() public Ownable() {} // Updates the opsAddress propety with the new _opsAddress value function setOpsAddress(address _opsAddress) external onlyOwner returns (bool) { require(_opsAddress != address(0)); require(_opsAddress != address(this)); opsAddress = _opsAddress; return true; } // Updates the adminAddress propety with the new _adminAddress value function setAdminAddress(address _adminAddress) external onlyOwner returns (bool) { require(_adminAddress != address(0)); require(_adminAddress != address(this)); adminAddress = _adminAddress; return true; } //Checks if an address is owner function isOwner(address _address) public view returns (bool) { bool result = (_address == owner); return result; } //Checks if an address is operator function isOps(address _address) public view returns (bool) { bool result = (_address == opsAddress); return result; } //Checks if an address is ops or admin function isOpsOrAdmin(address _address) public view returns (bool) { bool result = (_address == opsAddress || _address == adminAddress); return result; } //Checks if an address is ops,owner or admin function isOwnerOrOpsOrAdmin(address _address) public view returns (bool) { bool result = (_address == opsAddress || _address == adminAddress || _address == owner); return result; } //Checks whether the msg.sender address is equal to the adminAddress property or not modifier onlyAdmin() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == adminAddress); _; } // Checks whether the msg.sender address is equal to the opsAddress property or not modifier onlyOps() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == opsAddress); _; } // Checks whether the msg.sender address is equal to the opsAddress or adminAddress property modifier onlyAdminAndOps() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == opsAddress || _address == adminAddress); _; } } contract CrowdsaleConfig is J8TTokenConfig { using SafeMath for uint256; // Default start token sale date is 28th February 15:00 SGP 2018 uint256 public constant START_TIMESTAMP = 1519801200; // Default end token sale date is 14th March 15:00 SGP 2018 uint256 public constant END_TIMESTAMP = 1521010800; // The ETH decimal factor to obtain weis uint256 public constant ETH_DECIMALS_FACTOR = 10**uint256(18); // The token sale supply uint256 public constant TOKEN_SALE_SUPPLY = 450000000 * J8T_DECIMALS_FACTOR; // The minimum contribution amount in weis uint256 public constant MIN_CONTRIBUTION_WEIS = 0.1 ether; // The maximum contribution amount in weis uint256 public constant MAX_CONTRIBUTION_WEIS = 10 ether; //@WARNING: WORKING WITH KILO-MULTIPLES TO AVOID IMPOSSIBLE DIVISIONS OF FLOATING POINTS. uint256 constant dollar_per_kilo_token = 100; //0.1 dollar per token uint256 public constant dollars_per_kilo_ether = 900000; //900$ per ether //TOKENS_PER_ETHER = dollars_per_ether / dollar_per_token uint256 public constant INITIAL_TOKENS_PER_ETHER = dollars_per_kilo_ether.div(dollar_per_kilo_token); } contract Ledger is ACLManaged { using SafeMath for uint256; /////////////////////// // Ledger PROPERTIES // /////////////////////// // The Allocation struct represents a token sale purchase // amountGranted is the amount of tokens purchased // hasClaimedBonusTokens whether the allocation has been alredy claimed struct Allocation { uint256 amountGranted; uint256 amountBonusGranted; bool hasClaimedBonusTokens; } // ContributionPhase enum cases are // PreSaleContribution, the contribution has been made in the presale phase // PartnerContribution, the contribution has been made in the private phase enum ContributionPhase { PreSaleContribution, PartnerContribution } // Map of adresses that purchased tokens on the presale phase mapping(address => Allocation) public presaleAllocations; // Map of adresses that purchased tokens on the private phase mapping(address => Allocation) public partnerAllocations; // Reference to the J8TToken contract J8TToken public tokenContract; // Reference to the Crowdsale contract Crowdsale public crowdsaleContract; // Total private allocation, counting the amount of tokens from the // partner and the presale phase uint256 public totalPrivateAllocation; // Whether the token allocations can be claimed on the partner sale phase bool public canClaimPartnerTokens; // Whether the token allocations can be claimed on the presale sale phase bool public canClaimPresaleTokens; // Whether the bonus token allocations can be claimed bool public canClaimPresaleBonusTokensPhase1; bool public canClaimPresaleBonusTokensPhase2; // Whether the bonus token allocations can be claimed bool public canClaimPartnerBonusTokensPhase1; bool public canClaimPartnerBonusTokensPhase2; /////////////////// // Ledger EVENTS // /////////////////// // Triggered when an allocation has been granted event AllocationGranted(address _contributor, uint256 _amount, uint8 _phase); // Triggered when an allocation has been revoked event AllocationRevoked(address _contributor, uint256 _amount, uint8 _phase); // Triggered when an allocation has been claimed event AllocationClaimed(address _contributor, uint256 _amount); // Triggered when a bonus allocation has been claimed event AllocationBonusClaimed(address _contributor, uint256 _amount); // Triggered when crowdsale contract updated event CrowdsaleContractUpdated(address _who, address _old_address, address _new_address); //Triggered when any can claim token boolean is updated. _type param indicates which is updated. event CanClaimTokensUpdated(address _who, string _type, bool _oldCanClaim, bool _newCanClaim); ////////////////////// // Ledger FUNCTIONS // ////////////////////// // Ledger constructor // Sets default values for canClaimPresaleTokens and canClaimPartnerTokens properties function Ledger(J8TToken _tokenContract) public { require(address(_tokenContract) != address(0)); tokenContract = _tokenContract; canClaimPresaleTokens = false; canClaimPartnerTokens = false; canClaimPresaleBonusTokensPhase1 = false; canClaimPresaleBonusTokensPhase2 = false; canClaimPartnerBonusTokensPhase1 = false; canClaimPartnerBonusTokensPhase2 = false; } function () external payable { claimTokens(); } // Revokes an allocation from the contributor with address _contributor // Deletes the allocation from the corresponding mapping property and transfers // the total amount of tokens of the allocation back to the Crowdsale contract function revokeAllocation(address _contributor, uint8 _phase) public onlyAdminAndOps payable returns (uint256) { require(_contributor != address(0)); require(_contributor != address(this)); // Can't revoke an allocation if the contribution phase is not in the ContributionPhase enum ContributionPhase _contributionPhase = ContributionPhase(_phase); require(_contributionPhase == ContributionPhase.PreSaleContribution || _contributionPhase == ContributionPhase.PartnerContribution); uint256 grantedAllocation = 0; // Deletes the allocation from the respective mapping if (_contributionPhase == ContributionPhase.PreSaleContribution) { grantedAllocation = presaleAllocations[_contributor].amountGranted.add(presaleAllocations[_contributor].amountBonusGranted); delete presaleAllocations[_contributor]; } else if (_contributionPhase == ContributionPhase.PartnerContribution) { grantedAllocation = partnerAllocations[_contributor].amountGranted.add(partnerAllocations[_contributor].amountBonusGranted); delete partnerAllocations[_contributor]; } // The granted amount allocation must be less that the current token supply on the contract uint256 currentSupply = tokenContract.balanceOf(address(this)); require(grantedAllocation <= currentSupply); // Updates the total private allocation substracting the amount of tokens that has been revoked require(grantedAllocation <= totalPrivateAllocation); totalPrivateAllocation = totalPrivateAllocation.sub(grantedAllocation); // We sent back the amount of tokens that has been revoked to the corwdsale contract require(tokenContract.transfer(address(crowdsaleContract), grantedAllocation)); AllocationRevoked(_contributor, grantedAllocation, _phase); return grantedAllocation; } // Adds a new allocation for the contributor with address _contributor function addAllocation(address _contributor, uint256 _amount, uint256 _bonus, uint8 _phase) public onlyAdminAndOps returns (bool) { require(_contributor != address(0)); require(_contributor != address(this)); // Can't create or update an allocation if the amount of tokens to be allocated is not greater than zero require(_amount > 0); // Can't create an allocation if the contribution phase is not in the ContributionPhase enum ContributionPhase _contributionPhase = ContributionPhase(_phase); require(_contributionPhase == ContributionPhase.PreSaleContribution || _contributionPhase == ContributionPhase.PartnerContribution); uint256 totalAmount = _amount.add(_bonus); uint256 totalGrantedAllocation = 0; uint256 totalGrantedBonusAllocation = 0; // Fetch the allocation from the respective mapping and updates the granted amount of tokens if (_contributionPhase == ContributionPhase.PreSaleContribution) { totalGrantedAllocation = presaleAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = presaleAllocations[_contributor].amountBonusGranted.add(_bonus); presaleAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } else if (_contributionPhase == ContributionPhase.PartnerContribution) { totalGrantedAllocation = partnerAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = partnerAllocations[_contributor].amountBonusGranted.add(_bonus); partnerAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } // Updates the contract data totalPrivateAllocation = totalPrivateAllocation.add(totalAmount); AllocationGranted(_contributor, totalAmount, _phase); return true; } // The claimTokens() function handles the contribution token claim. // Tokens can only be claimed after we open this phase. // The lockouts periods are defined by the foundation. // There are 2 different lockouts: // Presale lockout // Partner lockout // // A contributor that has contributed in all the phases can claim // all its tokens, but only the ones that are accesible to claim // be transfered. // // A contributor can claim its tokens after each phase has been opened function claimTokens() public payable returns (bool) { require(msg.sender != address(0)); require(msg.sender != address(this)); uint256 amountToTransfer = 0; // We need to check if the contributor has made a contribution on each // phase, presale and partner Allocation storage presaleA = presaleAllocations[msg.sender]; if (presaleA.amountGranted > 0 && canClaimPresaleTokens) { amountToTransfer = amountToTransfer.add(presaleA.amountGranted); presaleA.amountGranted = 0; } Allocation storage partnerA = partnerAllocations[msg.sender]; if (partnerA.amountGranted > 0 && canClaimPartnerTokens) { amountToTransfer = amountToTransfer.add(partnerA.amountGranted); partnerA.amountGranted = 0; } // The amount to transfer must greater than zero require(amountToTransfer > 0); // The amount to transfer must be less or equal to the current supply uint256 currentSupply = tokenContract.balanceOf(address(this)); require(amountToTransfer <= currentSupply); // Transfer the token allocation to contributor require(tokenContract.transfer(msg.sender, amountToTransfer)); AllocationClaimed(msg.sender, amountToTransfer); return true; } function claimBonus() external payable returns (bool) { require(msg.sender != address(0)); require(msg.sender != address(this)); uint256 amountToTransfer = 0; // BONUS PHASE 1 Allocation storage presale = presaleAllocations[msg.sender]; if (presale.amountBonusGranted > 0 && !presale.hasClaimedBonusTokens && canClaimPresaleBonusTokensPhase1) { uint256 amountPresale = presale.amountBonusGranted.div(2); amountToTransfer = amountPresale; presale.amountBonusGranted = amountPresale; presale.hasClaimedBonusTokens = true; } Allocation storage partner = partnerAllocations[msg.sender]; if (partner.amountBonusGranted > 0 && !partner.hasClaimedBonusTokens && canClaimPartnerBonusTokensPhase1) { uint256 amountPartner = partner.amountBonusGranted.div(2); amountToTransfer = amountToTransfer.add(amountPartner); partner.amountBonusGranted = amountPartner; partner.hasClaimedBonusTokens = true; } // BONUS PHASE 2 if (presale.amountBonusGranted > 0 && canClaimPresaleBonusTokensPhase2) { amountToTransfer = amountToTransfer.add(presale.amountBonusGranted); presale.amountBonusGranted = 0; } if (partner.amountBonusGranted > 0 && canClaimPartnerBonusTokensPhase2) { amountToTransfer = amountToTransfer.add(partner.amountBonusGranted); partner.amountBonusGranted = 0; } // The amount to transfer must greater than zero require(amountToTransfer > 0); // The amount to transfer must be less or equal to the current supply uint256 currentSupply = tokenContract.balanceOf(address(this)); require(amountToTransfer <= currentSupply); // Transfer the token allocation to contributor require(tokenContract.transfer(msg.sender, amountToTransfer)); AllocationBonusClaimed(msg.sender, amountToTransfer); return true; } // Updates the canClaimPresaleTokens propety with the new _canClaimTokens value function setCanClaimPresaleTokens(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleTokens; canClaimPresaleTokens = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleTokens', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimPartnerTokens property with the new _canClaimTokens value function setCanClaimPartnerTokens(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerTokens; canClaimPartnerTokens = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerTokens', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPresaleBonusTokensPhase1(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleBonusTokensPhase1; canClaimPresaleBonusTokensPhase1 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleBonusTokensPhase1', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPresaleBonusTokensPhase2(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleBonusTokensPhase2; canClaimPresaleBonusTokensPhase2 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleBonusTokensPhase2', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPartnerBonusTokensPhase1(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerBonusTokensPhase1; canClaimPartnerBonusTokensPhase1 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerBonusTokensPhase1', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPartnerBonusTokensPhase2(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerBonusTokensPhase2; canClaimPartnerBonusTokensPhase2 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerBonusTokensPhase2', _oldCanClaim, _canClaimTokens); return true; } // Updates the crowdsale contract property with the new _crowdsaleContract value function setCrowdsaleContract(Crowdsale _crowdsaleContract) public onlyOwner returns (bool) { address old_crowdsale_address = crowdsaleContract; crowdsaleContract = _crowdsaleContract; CrowdsaleContractUpdated(msg.sender, old_crowdsale_address, crowdsaleContract); return true; } } contract Crowdsale is ACLManaged, CrowdsaleConfig { using SafeMath for uint256; ////////////////////////// // Crowdsale PROPERTIES // ////////////////////////// // The J8TToken smart contract reference J8TToken public tokenContract; // The Ledger smart contract reference Ledger public ledgerContract; // The start token sale date represented as a timestamp uint256 public startTimestamp; // The end token sale date represented as a timestamp uint256 public endTimestamp; // Ratio of J8T tokens to per ether uint256 public tokensPerEther; // The total amount of wei raised in the token sale // Including presales (in eth) and public sale uint256 public weiRaised; // The current total amount of tokens sold in the token sale uint256 public totalTokensSold; // The minimum and maximum eth contribution accepted in the token sale uint256 public minContribution; uint256 public maxContribution; // The wallet address where the token sale sends all eth contributions address public wallet; // Controls whether the token sale has finished or not bool public isFinalized = false; // Map of adresses that requested to purchase tokens // Contributors of the token sale are segmented as: // CannotContribute: Cannot contribute in any phase (uint8 - 0) // PreSaleContributor: Can contribute on both pre-sale and pubic sale phases (uint8 - 1) // PublicSaleContributor: Can contribute on he public sale phase (uint8 - 2) mapping(address => WhitelistPermission) public whitelist; // Map of addresses that has already contributed on the token sale mapping(address => bool) public hasContributed; enum WhitelistPermission { CannotContribute, PreSaleContributor, PublicSaleContributor } ////////////////////// // Crowdsale EVENTS // ////////////////////// // Triggered when a contribution in the public sale has been processed correctly event TokensPurchased(address _contributor, uint256 _amount); // Triggered when the whitelist has been updated event WhiteListUpdated(address _who, address _account, WhitelistPermission _phase); // Triggered when the Crowdsale has been created event ContractCreated(); // Triggered when a presale has been added // The phase parameter can be a strategic partner contribution or a presale contribution event PresaleAdded(address _contributor, uint256 _amount, uint8 _phase); // Triggered when the tokensPerEther property has been updated event TokensPerEtherUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the startTimestamp property has been updated event StartTimestampUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the endTimestamp property has been updated event EndTimestampUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the wallet property has been updated event WalletUpdated(address _who, address _oldWallet, address _newWallet); // Triggered when the minContribution property has been updated event MinContributionUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the maxContribution property has been updated event MaxContributionUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the token sale has finalized event Finalized(address _who, uint256 _timestamp); // Triggered when the token sale has finalized and there where still token to sale // When the token are not sold, we burn them event Burned(address _who, uint256 _amount, uint256 _timestamp); ///////////////////////// // Crowdsale FUNCTIONS // ///////////////////////// // Crowdsale constructor // Takes default values from the CrowdsaleConfig smart contract function Crowdsale( J8TToken _tokenContract, Ledger _ledgerContract, address _wallet ) public { uint256 _start = START_TIMESTAMP; uint256 _end = END_TIMESTAMP; uint256 _supply = TOKEN_SALE_SUPPLY; uint256 _min_contribution = MIN_CONTRIBUTION_WEIS; uint256 _max_contribution = MAX_CONTRIBUTION_WEIS; uint256 _tokensPerEther = INITIAL_TOKENS_PER_ETHER; require(_start > currentTime()); require(_end > _start); require(_tokensPerEther > 0); require(address(_tokenContract) != address(0)); require(address(_ledgerContract) != address(0)); require(_wallet != address(0)); ledgerContract = _ledgerContract; tokenContract = _tokenContract; startTimestamp = _start; endTimestamp = _end; tokensPerEther = _tokensPerEther; minContribution = _min_contribution; maxContribution = _max_contribution; wallet = _wallet; totalTokensSold = 0; weiRaised = 0; isFinalized = false; ContractCreated(); } // Updates the tokenPerEther propety with the new _tokensPerEther value function setTokensPerEther(uint256 _tokensPerEther) external onlyAdmin onlyBeforeSale returns (bool) { require(_tokensPerEther > 0); uint256 _oldValue = tokensPerEther; tokensPerEther = _tokensPerEther; TokensPerEtherUpdated(msg.sender, _oldValue, tokensPerEther); return true; } // Updates the startTimestamp propety with the new _start value function setStartTimestamp(uint256 _start) external onlyAdmin returns (bool) { require(_start < endTimestamp); require(_start > currentTime()); uint256 _oldValue = startTimestamp; startTimestamp = _start; StartTimestampUpdated(msg.sender, _oldValue, startTimestamp); return true; } // Updates the endTimestamp propety with the new _end value function setEndTimestamp(uint256 _end) external onlyAdmin returns (bool) { require(_end > startTimestamp); uint256 _oldValue = endTimestamp; endTimestamp = _end; EndTimestampUpdated(msg.sender, _oldValue, endTimestamp); return true; } // Updates the wallet propety with the new _newWallet value function updateWallet(address _newWallet) external onlyAdmin returns (bool) { require(_newWallet != address(0)); address _oldValue = wallet; wallet = _newWallet; WalletUpdated(msg.sender, _oldValue, wallet); return true; } // Updates the minContribution propety with the new _newMinControbution value function setMinContribution(uint256 _newMinContribution) external onlyAdmin returns (bool) { require(_newMinContribution <= maxContribution); uint256 _oldValue = minContribution; minContribution = _newMinContribution; MinContributionUpdated(msg.sender, _oldValue, minContribution); return true; } // Updates the maxContribution propety with the new _newMaxContribution value function setMaxContribution(uint256 _newMaxContribution) external onlyAdmin returns (bool) { require(_newMaxContribution > minContribution); uint256 _oldValue = maxContribution; maxContribution = _newMaxContribution; MaxContributionUpdated(msg.sender, _oldValue, maxContribution); return true; } // Main public function. function () external payable { purchaseTokens(); } // Revokes a presale allocation from the contributor with address _contributor // Updates the totalTokensSold property substracting the amount of tokens that where previously allocated function revokePresale(address _contributor, uint8 _contributorPhase) external onlyAdmin returns (bool) { require(_contributor != address(0)); // We can only revoke allocations from pre sale or strategic partners // ContributionPhase.PreSaleContribution == 0, ContributionPhase.PartnerContribution == 1 require(_contributorPhase == 0 || _contributorPhase == 1); uint256 luckys = ledgerContract.revokeAllocation(_contributor, _contributorPhase); require(luckys > 0); require(luckys <= totalTokensSold); totalTokensSold = totalTokensSold.sub(luckys); return true; } // Adds a new presale allocation for the contributor with address _contributor // We can only allocate presale before the token sale has been initialized function addPresale(address _contributor, uint256 _tokens, uint256 _bonus, uint8 _contributorPhase) external onlyAdminAndOps onlyBeforeSale returns (bool) { require(_tokens > 0); require(_bonus > 0); // Converts the amount of tokens to our smallest J8T value, lucky uint256 luckys = _tokens.mul(J8T_DECIMALS_FACTOR); uint256 bonusLuckys = _bonus.mul(J8T_DECIMALS_FACTOR); uint256 totalTokens = luckys.add(bonusLuckys); uint256 availableTokensToPurchase = tokenContract.balanceOf(address(this)); require(totalTokens <= availableTokensToPurchase); // Insert the new allocation to the Ledger require(ledgerContract.addAllocation(_contributor, luckys, bonusLuckys, _contributorPhase)); // Transfers the tokens form the Crowdsale contract to the Ledger contract require(tokenContract.transfer(address(ledgerContract), totalTokens)); // Updates totalTokensSold property totalTokensSold = totalTokensSold.add(totalTokens); // If we reach the total amount of tokens to sell we finilize the token sale availableTokensToPurchase = tokenContract.balanceOf(address(this)); if (availableTokensToPurchase == 0) { finalization(); } // Trigger PresaleAdded event PresaleAdded(_contributor, totalTokens, _contributorPhase); } // The purchaseTokens function handles the token purchase flow function purchaseTokens() public payable onlyDuringSale returns (bool) { address contributor = msg.sender; uint256 weiAmount = msg.value; // A contributor can only contribute once on the public sale require(hasContributed[contributor] == false); // The contributor address must be whitelisted in order to be able to purchase tokens require(contributorCanContribute(contributor)); // The weiAmount must be greater or equal than minContribution require(weiAmount >= minContribution); // The weiAmount cannot be greater than maxContribution require(weiAmount <= maxContribution); // The availableTokensToPurchase must be greater than 0 require(totalTokensSold < TOKEN_SALE_SUPPLY); uint256 availableTokensToPurchase = TOKEN_SALE_SUPPLY.sub(totalTokensSold); // We need to convert the tokensPerEther to luckys (10**8) uint256 luckyPerEther = tokensPerEther.mul(J8T_DECIMALS_FACTOR); // In order to calculate the tokens amount to be allocated to the contrbutor // we need to multiply the amount of wei sent by luckyPerEther and divide the // result for the ether decimal factor (10**18) uint256 tokensAmount = weiAmount.mul(luckyPerEther).div(ETH_DECIMALS_FACTOR); uint256 refund = 0; uint256 tokensToPurchase = tokensAmount; // If the token purchase amount is bigger than the remaining token allocation // we can only sell the remainging tokens and refund the unused amount of eth if (availableTokensToPurchase < tokensAmount) { tokensToPurchase = availableTokensToPurchase; weiAmount = tokensToPurchase.mul(ETH_DECIMALS_FACTOR).div(luckyPerEther); refund = msg.value.sub(weiAmount); } // We update the token sale contract data totalTokensSold = totalTokensSold.add(tokensToPurchase); uint256 weiToPurchase = tokensToPurchase.div(tokensPerEther); weiRaised = weiRaised.add(weiToPurchase); // Transfers the tokens form the Crowdsale contract to contriutors wallet require(tokenContract.transfer(contributor, tokensToPurchase)); // Issue a refund for any unused ether if (refund > 0) { contributor.transfer(refund); } // Transfer ether contribution to the wallet wallet.transfer(weiAmount); // Update hasContributed mapping hasContributed[contributor] = true; TokensPurchased(contributor, tokensToPurchase); // If we reach the total amount of tokens to sell we finilize the token sale if (totalTokensSold == TOKEN_SALE_SUPPLY) { finalization(); } return true; } // Updates the whitelist function updateWhitelist(address _account, WhitelistPermission _permission) external onlyAdminAndOps returns (bool) { require(_account != address(0)); require(_permission == WhitelistPermission.PreSaleContributor || _permission == WhitelistPermission.PublicSaleContributor || _permission == WhitelistPermission.CannotContribute); require(!saleHasFinished()); whitelist[_account] = _permission; address _who = msg.sender; WhiteListUpdated(_who, _account, _permission); return true; } function updateWhitelist_batch(address[] _accounts, WhitelistPermission _permission) external onlyAdminAndOps returns (bool) { require(_permission == WhitelistPermission.PreSaleContributor || _permission == WhitelistPermission.PublicSaleContributor || _permission == WhitelistPermission.CannotContribute); require(!saleHasFinished()); for(uint i = 0; i < _accounts.length; ++i) { require(_accounts[i] != address(0)); whitelist[_accounts[i]] = _permission; WhiteListUpdated(msg.sender, _accounts[i], _permission); } return true; } // Checks that the status of an address account // Contributors of the token sale are segmented as: // PreSaleContributor: Can contribute on both pre-sale and pubic sale phases // PublicSaleContributor: Can contribute on he public sale phase // CannotContribute: Cannot contribute in any phase function contributorCanContribute(address _contributorAddress) private view returns (bool) { WhitelistPermission _contributorPhase = whitelist[_contributorAddress]; if (_contributorPhase == WhitelistPermission.CannotContribute) { return false; } if (_contributorPhase == WhitelistPermission.PreSaleContributor || _contributorPhase == WhitelistPermission.PublicSaleContributor) { return true; } return false; } // Returns the current time function currentTime() public view returns (uint256) { return now; } // Checks if the sale has finished function saleHasFinished() public view returns (bool) { if (isFinalized) { return true; } if (endTimestamp < currentTime()) { return true; } if (totalTokensSold == TOKEN_SALE_SUPPLY) { return true; } return false; } modifier onlyBeforeSale() { require(currentTime() < startTimestamp); _; } modifier onlyDuringSale() { uint256 _currentTime = currentTime(); require(startTimestamp < _currentTime); require(_currentTime < endTimestamp); _; } modifier onlyPostSale() { require(endTimestamp < currentTime()); _; } /////////////////////// // PRIVATE FUNCTIONS // /////////////////////// // This method is for to be called only for the owner. This way we protect for anyone who wanna finalize the ICO. function finalize() external onlyAdmin returns (bool) { return finalization(); } // Only used by finalize and setFinalized. // Overloaded logic for two uses. // NOTE: In case finalize is called by an user and not from addPresale()/purchaseToken() // will diff total supply with sold supply to burn token. function finalization() private returns (bool) { require(!isFinalized); isFinalized = true; if (totalTokensSold < TOKEN_SALE_SUPPLY) { uint256 toBurn = TOKEN_SALE_SUPPLY.sub(totalTokensSold); tokenContract.burn(toBurn); Burned(msg.sender, toBurn, currentTime()); } Finalized(msg.sender, currentTime()); return true; } function saleSupply() public view returns (uint256) { return tokenContract.balanceOf(address(this)); } }
BONUS PHASE 1 BONUS PHASE 2
function claimBonus() external payable returns (bool) { require(msg.sender != address(0)); require(msg.sender != address(this)); uint256 amountToTransfer = 0; Allocation storage presale = presaleAllocations[msg.sender]; if (presale.amountBonusGranted > 0 && !presale.hasClaimedBonusTokens && canClaimPresaleBonusTokensPhase1) { uint256 amountPresale = presale.amountBonusGranted.div(2); amountToTransfer = amountPresale; presale.amountBonusGranted = amountPresale; presale.hasClaimedBonusTokens = true; } Allocation storage partner = partnerAllocations[msg.sender]; if (partner.amountBonusGranted > 0 && !partner.hasClaimedBonusTokens && canClaimPartnerBonusTokensPhase1) { uint256 amountPartner = partner.amountBonusGranted.div(2); amountToTransfer = amountToTransfer.add(amountPartner); partner.amountBonusGranted = amountPartner; partner.hasClaimedBonusTokens = true; } if (presale.amountBonusGranted > 0 && canClaimPresaleBonusTokensPhase2) { amountToTransfer = amountToTransfer.add(presale.amountBonusGranted); presale.amountBonusGranted = 0; } if (partner.amountBonusGranted > 0 && canClaimPartnerBonusTokensPhase2) { amountToTransfer = amountToTransfer.add(partner.amountBonusGranted); partner.amountBonusGranted = 0; } require(amountToTransfer <= currentSupply); AllocationBonusClaimed(msg.sender, amountToTransfer); return true; }
2,480,430
[ 1, 38, 673, 3378, 15490, 4429, 404, 605, 673, 3378, 15490, 4429, 576, 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, 7516, 38, 22889, 1435, 3903, 8843, 429, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 3576, 18, 15330, 480, 1758, 12, 2211, 10019, 203, 203, 3639, 2254, 5034, 3844, 774, 5912, 273, 374, 31, 203, 203, 3639, 24242, 2502, 4075, 5349, 273, 4075, 5349, 8763, 1012, 63, 3576, 18, 15330, 15533, 203, 3639, 309, 261, 12202, 5349, 18, 8949, 38, 22889, 14570, 405, 374, 597, 401, 12202, 5349, 18, 5332, 9762, 329, 38, 22889, 5157, 597, 848, 9762, 12236, 5349, 38, 22889, 5157, 11406, 21, 13, 288, 203, 5411, 2254, 5034, 3844, 12236, 5349, 273, 4075, 5349, 18, 8949, 38, 22889, 14570, 18, 2892, 12, 22, 1769, 203, 5411, 3844, 774, 5912, 273, 3844, 12236, 5349, 31, 203, 5411, 4075, 5349, 18, 8949, 38, 22889, 14570, 273, 3844, 12236, 5349, 31, 203, 5411, 4075, 5349, 18, 5332, 9762, 329, 38, 22889, 5157, 273, 638, 31, 203, 3639, 289, 203, 203, 3639, 24242, 2502, 19170, 273, 19170, 8763, 1012, 63, 3576, 18, 15330, 15533, 203, 3639, 309, 261, 31993, 18, 8949, 38, 22889, 14570, 405, 374, 597, 401, 31993, 18, 5332, 9762, 329, 38, 22889, 5157, 597, 848, 9762, 1988, 1224, 38, 22889, 5157, 11406, 21, 13, 288, 203, 5411, 2254, 5034, 3844, 1988, 1224, 273, 19170, 18, 8949, 38, 22889, 14570, 18, 2892, 12, 22, 1769, 203, 5411, 3844, 774, 5912, 273, 3844, 774, 5912, 18, 1289, 12, 8949, 1988, 1224, 1769, 203, 5411, 19170, 18, 8949, 38, 22889, 2 ]
pragma solidity ^0.4.21; /** * @title ApplicantFactory * @dev The ApplicantFactory allows applicants to apply to a credentialOrg for an electronic credential. */ import "./Pausable.sol"; import "./SafeMath32.sol"; // allows communication with CredentialOrg Factory. // not used, will be when testing moves to Javascript. interface CredentialOrgFactory{ function isCredentialOrg(address _credentialOrgAddress) external view returns (bool IsOrgAddress); } contract ApplicantFactory is Pausable { // SafeMath32 Library Usage using SafeMath32 for uint32; // contract events. event ApplicantEvent(address ApplicantCallerAddress, string detail); // mappings mapping (address => Applicant[]) orgAddressToApplicants; mapping (address => uint32) orgAddressToApplicantCount; mapping (address => uint32) applicantAddressToApplicantPosition; // structs struct Applicant { address studentAddress; // address of student requesting credential string SSN; // Applicant SSN string collegeStudentID; // Applicant CollegeID string firstName; // first name lenmax 40 string lastName; // last name lenmax 40 uint32 insertDate; // unix timestamp. uint32 processDate; // unix timestamp. string processDetail; // AWARDED/DENIED } /** * @dev constructor. */ constructor() public { } // address of CredentialOrgFactory, and class refreence address private credentialOrgContractAddress; CredentialOrgFactory cof; // functions /** * @dev Gets Owner Address of Contract * @return returnedOwner returns owner of contract address. */ function getOwner() public view returns (address returnedOwner) { returnedOwner = owner; return returnedOwner; } /** * @dev Allows owner to set address of CredentialOrgFactory contract. * @param _credentialOrgContractAddress address of CredentialOrgFactory (set on deploy). */ function setAddress(address _credentialOrgContractAddress) public onlyOwner { credentialOrgContractAddress = _credentialOrgContractAddress; } /** * @dev Allows creation of Applicants to Credentialing Orgs * @param _collegeAddress address of CredentialingOrg * @param _SSN SSN of Student * @param _collegeStudentID College Student ID * @param _firstName First Name of Student * @param _lastName Last Name of Student * @return insertSuccess true/false of */ function createApplicant(address _collegeAddress, string _SSN, string _collegeStudentID, string _firstName, string _lastName) public whenNotPaused returns (bool insertSuccess) { emit ApplicantEvent(msg.sender, "createApplicant (ATTEMPT)"); require(msg.sender != 0 && _collegeAddress != 0, "createApplicant (FAIL) Addresses can not be 0."); require(bytes(_SSN).length == 9,"createApplicant (FAIL) SSN Length incorrect"); require(bytes(_collegeStudentID).length == 9, "createApplicant (FAIL)College StudentID length Problem"); require(bytes(_firstName).length > 0 && bytes(_firstName).length <= 40, "createApplicant (FAIL) FirstName length problem"); require(bytes(_lastName).length > 0 && bytes(_lastName).length <= 40, "createApplicant (FAIL) LastName length problem"); cof = CredentialOrgFactory(credentialOrgContractAddress); if (cof.isCredentialOrg(_collegeAddress)){ insertSuccess = false; uint32 position = uint32(orgAddressToApplicants[_collegeAddress].push(Applicant(msg.sender, _SSN, _collegeStudentID, _firstName, _lastName, uint32(now), 0, ""))); if(position >= 0){ insertSuccess = true; applicantAddressToApplicantPosition[msg.sender] = position.sub(1); orgAddressToApplicantCount[_collegeAddress] = orgAddressToApplicantCount[_collegeAddress].add(1); emit ApplicantEvent(msg.sender, "createApplicant (SUCCESS)"); } else { emit ApplicantEvent(msg.sender, "createApplicant (FAIL)"); } } else { emit ApplicantEvent(_collegeAddress, "createApplicant (FAIL) Colleg Applied to address NOT CredetialOrg"); } return (insertSuccess); } /** * @dev Allows Selection of Applicant by org and position. * @param _orgAddress address of CredentialingOrg * @param _position position in array of Applicant * @return Applicants student's ether address * @return SSN Applicants SSN * @return collegeStudentID Applicant college ID * @return firstName Applicant firstName * @return lastName Applicant lastName */ function selectApplicantByOrgAndPosition(address _orgAddress, uint32 _position) public view returns (address studentAddress, string SSN, string collegeStudentID, string firstName, string lastName) { require(_orgAddress != 0, "Applicant orgAddress can not be 0"); if (_position < orgAddressToApplicantCount[_orgAddress]){ studentAddress = orgAddressToApplicants[_orgAddress][_position].studentAddress; SSN = orgAddressToApplicants[_orgAddress][_position].SSN; collegeStudentID = orgAddressToApplicants[_orgAddress][_position].collegeStudentID; firstName = orgAddressToApplicants[_orgAddress][_position].firstName; lastName = orgAddressToApplicants[_orgAddress][_position].lastName; emit ApplicantEvent(msg.sender, "selectApplicantByOrgAndPosition (SUCCESS)"); } else { studentAddress = 0; SSN = ""; collegeStudentID = ""; firstName = ""; lastName = ""; emit ApplicantEvent(msg.sender, "selectApplicant (FAIL) Applicant lookup fail"); } return(studentAddress, SSN, collegeStudentID, firstName, lastName); } /** * @dev Allows update of Applicant by org and position. * @param _position position in array of Applicant * @param _processDetail Applicant AWARDED/DENIED * @return updateSuccess true/false */ function updateApplicantByOrgAndPosition(uint32 _position, string _processDetail) public whenNotPaused returns (bool updateSuccess) { updateSuccess = false; emit ApplicantEvent(msg.sender, "updateApplicantByOrgAndPosition (ATTEMPT)"); require(_position >= 0, "updateApplicantByOrgAndPosition: Applicant position requires >= 0"); require(bytes(_processDetail).length >= 0 && bytes(_processDetail).length <= 10, "updateApplicantByOrgAndPosition: Applicant Process Detail Missing"); cof = CredentialOrgFactory(credentialOrgContractAddress); if (cof.isCredentialOrg(msg.sender)){ if (_position < orgAddressToApplicantCount[msg.sender]){ orgAddressToApplicants[msg.sender][_position].processDate = uint32(block.timestamp); orgAddressToApplicants[msg.sender][_position].processDetail = _processDetail; updateSuccess = true; emit ApplicantEvent(msg.sender, "updateApplicantByOrgAndPosition (SUCCESS)"); } else { emit ApplicantEvent(msg.sender, "updateApplicantByOrgAndPosition (FAIL) invalid position"); } } else { emit ApplicantEvent(msg.sender, "updateApplicantByOrgAndPosition (FAIL) msgsender is NOT a credentialling org"); } return(updateSuccess); } /** * @dev Allows Selection of Applicant Count by orgAddress * @param _orgAddress address of CredentialingOrg * @return appCount the Applicant Count for a specific organization. */ function selectOrgApplicantCount(address _orgAddress) public view returns (uint32 appCount) { appCount = orgAddressToApplicantCount[_orgAddress]; return (appCount); } }
last name lenmax 40
string lastName;
12,757,063
[ 1, 2722, 508, 225, 562, 1896, 8063, 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, 533, 23439, 31, 2398, 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, -100 ]
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2020 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 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 Affero General Public License for more details. // ///@author Zapper ///@notice This contract adds/removes liquidity to yEarn Vaults using ETH or ERC20 Tokens. // SPDX-License-Identifier: GPLv2 // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol pragma solidity ^0.5.5; /** * @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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { bool private _notEntered; constructor() internal { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require( success, "Address: unable to send value, recipient may have reverted" ); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * 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 payable public _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address payable 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 payable newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address payable newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: yVault_ZapInOut_General_V1_2.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) ); } 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" ); } } } interface IYVault { function deposit(uint256) external; function withdraw(uint256) external; function getPricePerFullShare() external view returns (uint256); function token() external view returns (address); // V2 function pricePerShare() external view returns (uint256); } // -- Curve -- interface ICurveRegistry { function metaPools(address tokenAddress) external view returns (address swapAddress); } interface ICurveZapIn { function ZapIn( address _fromTokenAddress, address _toTokenAddress, address _swapAddress, uint256 _incomingTokenQty, uint256 _minPoolTokens, address _swapTarget, bytes calldata _swapCallData, address affiliate ) external payable returns (uint256 crvTokensBought); } // -- Aave -- interface IAaveLendingPoolAddressesProvider { function getLendingPool() external view returns (address); function getLendingPoolCore() external view returns (address payable); } interface IAaveLendingPool { function deposit( address _reserve, uint256 _amount, uint16 _referralCode ) external payable; } interface IAToken { function redeem(uint256 _amount) external; function underlyingAssetAddress() external returns (address); } // --- interface IWETH { function deposit() external payable; function withdraw(uint256) external; } contract yVault_ZapIn_V2 is ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; bool public stopped = false; // if true, goodwill is not deducted mapping(address => bool) public feeWhitelist; uint256 public goodwill; // % share of goodwill (0-100 %) uint256 affiliateSplit; // restrict affiliates mapping(address => bool) public affiliates; // affiliate => token => amount mapping(address => mapping(address => uint256)) public affiliateBalance; // token => amount mapping(address => uint256) public totalAffiliateBalance; address private constant ETHAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; IAaveLendingPoolAddressesProvider private constant lendingPoolAddressProvider = IAaveLendingPoolAddressesProvider( 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8 ); ICurveRegistry public curveReg; ICurveZapIn public curveZapIn; event zapIn(address sender, address pool, uint256 tokensRec); constructor( ICurveRegistry _curveReg, ICurveZapIn _curveZapIn, uint256 _goodwill, uint256 _affiliateSplit ) public { curveReg = _curveReg; curveZapIn = _curveZapIn; goodwill = _goodwill; affiliateSplit = _affiliateSplit; } // circuit breaker modifiers modifier stopInEmergency { if (stopped) { revert("Temporarily Paused"); } else { _; } } /** @notice This function adds liquidity to a Yearn vaults with ETH or ERC20 tokens @param fromToken The token used for entry (address(0) if ether) @param amountIn The amount of fromToken to invest @param toVault Yearn vault address @param isAaveUnderlying True is vault contains aave token @param minYVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise @param _swapTarget Excecution target for the swap @param swapData DEX quote data @param affiliate Affiliate address @return tokensReceived- Quantity of Vault tokens received */ function ZapInTokenVault( address fromToken, uint256 amountIn, address toVault, bool isAaveUnderlying, uint256 minYVTokens, address _swapTarget, bytes calldata swapData, address affiliate ) external payable stopInEmergency returns (uint256 tokensReceived) { // get incoming tokens uint256 toInvest = _pullTokens(fromToken, amountIn, affiliate, true); // swap to toToken address underlyingVaultToken = IYVault(toVault).token(); uint256 toTokenAmt; if (isAaveUnderlying) { address underlyingAsset = IAToken(underlyingVaultToken) .underlyingAssetAddress(); // aTokens are 1:1 toTokenAmt = _fillQuote( fromToken, underlyingAsset, toInvest, _swapTarget, swapData ); IERC20(underlyingAsset).safeApprove( lendingPoolAddressProvider.getLendingPoolCore(), toTokenAmt ); IAaveLendingPool(lendingPoolAddressProvider.getLendingPool()) .deposit(underlyingAsset, toTokenAmt, 0); } else { toTokenAmt = _fillQuote( fromToken, underlyingVaultToken, toInvest, _swapTarget, swapData ); } // Deposit to Vault tokensReceived = _vaultDeposit( underlyingVaultToken, toTokenAmt, toVault, minYVTokens ); } /** @notice This function adds liquidity to a Yearn Curve vaults with ETH or ERC20 tokens @param fromToken The token used for entry (address(0) if ether) @param amountIn The amount of fromToken to invest @param toToken Intermediate token to swap to @param toVault Yearn vault address @param minYVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise @param _swapTarget Excecution target for the swap @param swapData DEX quote data @param affiliate Affiliate address @return tokensReceived- Quantity of Vault tokens received */ function ZapInCurveVault( address fromToken, uint256 amountIn, address toToken, address toVault, uint256 minYVTokens, address _swapTarget, bytes calldata swapData, address affiliate ) external payable stopInEmergency returns (uint256 tokensReceived) { // get incoming tokens uint256 toInvest = _pullTokens(fromToken, amountIn, affiliate, true); // ZapIn to Curve address curveDepositAddr = curveReg.metaPools(IYVault(toVault).token()); uint256 curveLP; if (fromToken != address(0)) { IERC20(fromToken).safeApprove(address(curveZapIn), toInvest); curveLP = curveZapIn.ZapIn( fromToken, toToken, curveDepositAddr, toInvest, 0, _swapTarget, swapData, affiliate ); } else { curveLP = curveZapIn.ZapIn.value(toInvest)( fromToken, toToken, curveDepositAddr, toInvest, 0, _swapTarget, swapData, affiliate ); } // Deposit to Vault tokensReceived = _vaultDeposit( IYVault(toVault).token(), curveLP, toVault, minYVTokens ); } function _vaultDeposit( address underlyingVaultToken, uint256 amount, address toVault, uint256 minTokensRec ) internal returns (uint256 tokensReceived) { IERC20(underlyingVaultToken).safeApprove(toVault, amount); uint256 iniYVaultBal = IERC20(toVault).balanceOf(address(this)); IYVault(toVault).deposit(amount); tokensReceived = IERC20(toVault).balanceOf(address(this)).sub( iniYVaultBal ); require(tokensReceived >= minTokensRec, "Err: High Slippage"); IERC20(toVault).safeTransfer(msg.sender, tokensReceived); emit zapIn(msg.sender, toVault, tokensReceived); } function _fillQuote( address _fromTokenAddress, address toToken, uint256 _amount, address _swapTarget, bytes memory swapCallData ) internal returns (uint256 amtBought) { uint256 valueToSend; if (_fromTokenAddress == toToken) { return _amount; } if (_fromTokenAddress == address(0)) { valueToSend = _amount; } else { IERC20 fromToken = IERC20(_fromTokenAddress); fromToken.safeApprove(address(_swapTarget), 0); fromToken.safeApprove(address(_swapTarget), _amount); } uint256 iniBal = _getBalance(toToken); (bool success, ) = _swapTarget.call.value(valueToSend)(swapCallData); require(success, "Error Swapping Tokens 1"); uint256 finalBal = _getBalance(toToken); amtBought = finalBal.sub(iniBal); } function _getBalance(address token) internal view returns (uint256 balance) { if (token == address(0)) { balance = address(this).balance; } else { balance = IERC20(token).balanceOf(address(this)); } } ///@notice enableGoodwill should be false if vault contains Curve LP, otherwise true function _pullTokens( address token, uint256 amount, address affiliate, bool enableGoodwill ) internal returns (uint256 value) { uint256 totalGoodwillPortion; if (token == address(0)) { require(msg.value > 0, "No eth sent"); // subtract goodwill totalGoodwillPortion = _subtractGoodwill( ETHAddress, msg.value, affiliate, enableGoodwill ); return msg.value.sub(totalGoodwillPortion); } require(amount > 0, "Invalid token amount"); require(msg.value == 0, "Eth sent with token"); //transfer token IERC20(token).safeTransferFrom(msg.sender, address(this), amount); // subtract goodwill totalGoodwillPortion = _subtractGoodwill( token, amount, affiliate, enableGoodwill ); return amount.sub(totalGoodwillPortion); } function _subtractGoodwill( address token, uint256 amount, address affiliate, bool enableGoodwill ) internal returns (uint256 totalGoodwillPortion) { bool whitelisted = feeWhitelist[msg.sender]; if (enableGoodwill && !whitelisted && goodwill > 0) { totalGoodwillPortion = SafeMath.div( SafeMath.mul(amount, goodwill), 10000 ); if (affiliates[affiliate]) { uint256 affiliatePortion = totalGoodwillPortion .mul(affiliateSplit) .div(100); affiliateBalance[affiliate][token] = affiliateBalance[affiliate][token] .add(affiliatePortion); totalAffiliateBalance[token] = totalAffiliateBalance[token].add( affiliatePortion ); } } } function updateCurveRegistry(ICurveRegistry newCurveRegistry) external onlyOwner { require(newCurveRegistry != curveReg, "Already using this Registry"); curveReg = newCurveRegistry; } function updateCurveZapIn(ICurveZapIn newCurveZapIn) external onlyOwner { require(newCurveZapIn != curveZapIn, "Already using this ZapIn"); curveZapIn = newCurveZapIn; } // - to Pause the contract function toggleContractActive() public onlyOwner { stopped = !stopped; } function set_new_goodwill(uint16 _new_goodwill) public onlyOwner { require( _new_goodwill >= 0 && _new_goodwill <= 100, "GoodWill Value not allowed" ); goodwill = _new_goodwill; } function set_feeWhitelist(address zapAddress, bool status) external onlyOwner { feeWhitelist[zapAddress] = status; } function set_new_affiliateSplit(uint16 _new_affiliateSplit) external onlyOwner { require( _new_affiliateSplit <= 100, "Affiliate Split Value not allowed" ); affiliateSplit = _new_affiliateSplit; } function set_affiliate(address _affiliate, bool _status) external onlyOwner { affiliates[_affiliate] = _status; } ///@notice Withdraw goodwill share, retaining affilliate share function withdrawTokens(address[] calldata tokens) external onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { uint256 qty; if (tokens[i] == ETHAddress) { qty = address(this).balance.sub( totalAffiliateBalance[tokens[i]] ); Address.sendValue(Address.toPayable(owner()), qty); } else { qty = IERC20(tokens[i]).balanceOf(address(this)).sub( totalAffiliateBalance[tokens[i]] ); IERC20(tokens[i]).safeTransfer(owner(), qty); } } } ///@notice Withdraw affilliate share, retaining goodwill share function affilliateWithdraw(address[] calldata tokens) external { uint256 tokenBal; for (uint256 i = 0; i < tokens.length; i++) { tokenBal = affiliateBalance[msg.sender][tokens[i]]; affiliateBalance[msg.sender][tokens[i]] = 0; totalAffiliateBalance[tokens[i]] = totalAffiliateBalance[tokens[i]] .sub(tokenBal); if (tokens[i] == ETHAddress) { Address.sendValue(msg.sender, tokenBal); } else { IERC20(tokens[i]).safeTransfer(msg.sender, tokenBal); } } } function() external payable { require(msg.sender != tx.origin, "Do not send ETH directly"); } }
* @dev Collection of functions related to the address type/
library Address { } function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call.value(amount)(""); require( success, "Address: unable to send value, recipient may have reverted" ); } }
571,025
[ 1, 2532, 434, 4186, 3746, 358, 326, 1758, 618, 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 ]
[ 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, 12083, 5267, 288, 203, 97, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 1578, 981, 2816, 31, 203, 203, 203, 5411, 1731, 1578, 2236, 2310, 203, 540, 273, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 20, 73, 12483, 70, 26, 8643, 5353, 24532, 9036, 70, 27, 17156, 361, 28, 3028, 25, 72, 7140, 69, 24, 7301, 31, 203, 3639, 19931, 288, 203, 5411, 981, 2816, 519, 1110, 710, 2816, 12, 4631, 13, 203, 3639, 289, 203, 3639, 327, 261, 710, 2816, 480, 2236, 2310, 597, 981, 2816, 480, 374, 92, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 1578, 981, 2816, 31, 203, 203, 203, 5411, 1731, 1578, 2236, 2310, 203, 540, 273, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 20, 73, 12483, 70, 26, 8643, 5353, 24532, 9036, 70, 27, 17156, 361, 28, 3028, 25, 72, 7140, 69, 24, 7301, 31, 203, 3639, 19931, 288, 203, 5411, 981, 2816, 519, 1110, 710, 2816, 12, 4631, 13, 203, 3639, 289, 203, 3639, 327, 261, 710, 2816, 480, 2236, 2310, 597, 981, 2816, 480, 374, 92, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 358, 9148, 429, 12, 2867, 2236, 13, 203, 3639, 2 ]
pragma solidity ^0.4.13; interface ERC20Interface { 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 ); } contract OpsCoin is ERC20Interface { /** @notice © Copyright 2018 EYGS LLP and/or other members of the global Ernst & Young/EY network; pat. pending. */ using SafeMath for uint256; string public symbol; string public name; address public owner; uint256 public totalSupply; mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; mapping (address => mapping (address => uint)) private timeLock; constructor() { symbol = "OPS"; name = "EY OpsCoin"; totalSupply = 1000000; owner = msg.sender; balances[owner] = totalSupply; emit Transfer(address(0), owner, totalSupply); } //only owner  modifier modifier onlyOwner () { require(msg.sender == owner); _; } /** self destruct added by westlad */ function close() public onlyOwner { selfdestruct(owner); } /** * @dev Gets the balance of the specified address. * @param _address The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _address) public view returns (uint256) { return balances[_address]; } /** * @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 Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function mint(address _account, uint256 _amount) public { require(_account != 0); require(_amount > 0); totalSupply = totalSupply.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function burn(address _account, uint256 _amount) public { require(_account != 0); require(_amount <= balances[_account]); totalSupply = totalSupply.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function burnFrom(address _account, uint256 _amount) public { require(_amount <= allowed[_account][msg.sender]); allowed[_account][msg.sender] = allowed[_account][msg.sender].sub(_amount); emit Approval(_account, msg.sender, allowed[_account][msg.sender]); burn(_account, _amount); } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens after a specfied amount of time 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. * @param _timeLockTill The time until when this amount cannot be withdrawn */ function approveAt(address _spender, uint256 _value, uint _timeLockTill) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = _value; timeLock[msg.sender][_spender] = _timeLockTill; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev 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 transferFromAt(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); require(block.timestamp > timeLock[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev 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 increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].sub(_subtractedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Verifier{ function verifyTx( uint[2], uint[2], uint[2][2], uint[2], uint[2], uint[2], uint[2], uint[2], address ) public pure returns (bool){} /** @notice © Copyright 2018 EYGS LLP and/or other members of the global Ernst & Young/EY network; pat. pending. */ function getInputBits(uint, address) public view returns(bytes8){} } contract OpsCoinShield{ /** @notice © Copyright 2018 EYGS LLP and/or other members of the global Ernst & Young/EY network; pat. pending. Contract to enable the management of ZKSnark-hidden coin transactions. */ address public owner; bytes8[merkleWidth] ns; //store spent token nullifiers uint constant merkleWidth = 256; uint constant merkleDepth = 9; uint constant lastRow = merkleDepth-1; uint private balance = 0; bytes8[merkleWidth] private zs; //array holding the commitments.  Basically the bottom row of the merkle tree uint private zCount; //remember the number of commitments we hold uint private nCount; //remember the number of commitments we spent bytes8[] private roots; //holds each root we've calculated so that we can pull the one relevant to the prover uint private currentRootIndex; //holds the index for the current root so that the //prover can provide it later and this contract can look up the relevant root Verifier private mv; //the verification smart contract that the mint function uses Verifier private sv; //the verification smart contract that the transfer function uses OpsCoin private ops; //the OpsCoin ERC20-like token contract struct Proof { //recast this as a struct because otherwise, as a set of local variable, it takes too much stack space uint[2] a; uint[2] a_p; uint[2][2] b; uint[2] b_p; uint[2] c; uint[2] c_p; uint[2] h; uint[2] k; } //Proof proof; //not used - proof is now set per address mapping(address => Proof) private proofs; constructor(address mintVerifier, address transferVerifier, address opsCoin) public { // TODO - you can get a way with a single, generic verifier. owner = msg.sender; mv = Verifier(mintVerifier); sv = Verifier(transferVerifier); ops = OpsCoin(opsCoin); } //only owner  modifier modifier onlyOwner () { require(msg.sender == owner); _; } /** self destruct added by westlad */ function close() public onlyOwner { selfdestruct(owner); } function getMintVerifier() public view returns(address){ return address(mv); } function getTransferVerifier() public view returns(address){ return address(sv); } function getOpsCoin() public view returns(address){ return address(ops); } /** The mint function accepts opscoin and creates the same amount as a commitment. */ function mint(uint amount) public { //first, verify the proof bool result = mv.verifyTx( proofs[msg.sender].a, proofs[msg.sender].a_p, proofs[msg.sender].b, proofs[msg.sender].b_p, proofs[msg.sender].c, proofs[msg.sender].c_p, proofs[msg.sender].h, proofs[msg.sender].k, msg.sender); require(result); //the proof must check out //transfer OPS from the sender to this contract ops.transferFrom(msg.sender, address(this), amount); //save the commitments bytes8 z = mv.getInputBits(64, msg.sender);//recover the input params from MintVerifier zs[zCount++] = z; //add the token require(uint(mv.getInputBits(0, msg.sender))==amount); //check we've been correctly paid bytes8 root = merkle(0,0); //work out the Merkle root as it's now different currentRootIndex = roots.push(root)-1; //and save it to the list } /** The transfer function transfers a commitment to a new owner */ function transfer() public { //verification contract bool result = sv.verifyTx( proofs[msg.sender].a, proofs[msg.sender].a_p, proofs[msg.sender].b, proofs[msg.sender].b_p, proofs[msg.sender].c, proofs[msg.sender].c_p, proofs[msg.sender].h, proofs[msg.sender].k, msg.sender); require(result); //the proof must verify. The spice must flow. bytes8 nc = sv.getInputBits(0, msg.sender); bytes8 nd = sv.getInputBits(64, msg.sender); bytes8 ze = sv.getInputBits(128, msg.sender); bytes8 zf = sv.getInputBits(192, msg.sender); for (uint i=0; i<nCount; i++) { //check this is an unspent coin require(ns[i]!=nc && ns[i]!=nd); } ns[nCount++] = nc; //remember we spent it ns[nCount++] = nd; //remember we spent it zs[zCount++] = ze; //add Bob's commitment to the list of commitments zs[zCount++] = zf; //add Alice's commitment to the list of commitment bytes8 root = merkle(0,0); //work out the Merkle root as it's now different currentRootIndex = roots.push(root)-1; //and save it to the list } function burn(address payTo) public { //first, verify the proof bool result = mv.verifyTx( proofs[msg.sender].a, proofs[msg.sender].a_p, proofs[msg.sender].b, proofs[msg.sender].b_p, proofs[msg.sender].c, proofs[msg.sender].c_p, proofs[msg.sender].h, proofs[msg.sender].k, msg.sender); require(result); //the proof must check out ok //transfer OPS from this contract to the nominated address bytes8 C = mv.getInputBits(0, msg.sender);//recover the coin value uint256 value = uint256(C); //convert the coin value to a uint ops.transfer(payTo, value); //and pay the man bytes8 Nc = mv.getInputBits(64, msg.sender); //recover the nullifier ns[nCount++] = Nc; //add the nullifier to the list of nullifiers bytes8 root = merkle(0,0); //work out the Merkle root as it's now different currentRootIndex = roots.push(root)-1; //and save it to the list } /** This function is only needed because mint and transfer otherwise use too many local variables for the limited stack space, rather than pass a proof as parameters to these functions (more logical) */ function setProofParams( uint[2] a, uint[2] a_p, uint[2][2] b, uint[2] b_p, uint[2] c, uint[2] c_p, uint[2] h, uint[2] k) public { //TODO there must be a shorter way to do this: proofs[msg.sender].a[0] = a[0]; proofs[msg.sender].a[1] = a[1]; proofs[msg.sender].a_p[0] = a_p[0]; proofs[msg.sender].a_p[1] = a_p[1]; proofs[msg.sender].b[0][0] = b[0][0]; proofs[msg.sender].b[0][1] = b[0][1]; proofs[msg.sender].b[1][0] = b[1][0]; proofs[msg.sender].b[1][1] = b[1][1]; proofs[msg.sender].b_p[0] = b_p[0]; proofs[msg.sender].b_p[1] = b_p[1]; proofs[msg.sender].c[0] = c[0]; proofs[msg.sender].c[1] = c[1]; proofs[msg.sender].c_p[0] = c_p[0]; proofs[msg.sender].c_p[1] = c_p[1]; proofs[msg.sender].h[0] = h[0]; proofs[msg.sender].h[1] = h[1]; proofs[msg.sender].k[0] = k[0]; proofs[msg.sender].k[1] = k[1]; } function getTokens() public view returns(bytes8[merkleWidth], uint root) { //need the commitments to compute a proof and also an index to look up the current //root. return (zs,currentRootIndex); } /** Function to return the root that was current at rootIndex */ function getRoot(uint rootIndex) view public returns(bytes8) { return roots[rootIndex]; } function computeMerkle() public view returns (bytes8){//for backwards compat return merkle(0,0); } function merkle(uint r, uint t) public view returns (bytes8) { //This is a recursive approach, which seems efficient but we do end up //calculating the whole tree from scratch each time.  Need to look at storing //intermediate values and seeing if that will make it cheaper. if (r==lastRow) { return zs[t]; } else { return bytes8(sha256(merkle(r+1,2*t)^merkle(r+1,2*t+1))<<192); } } } 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; } }
only owner  modifier
modifier onlyOwner () { require(msg.sender == owner); _; }
12,692,379
[ 1, 3700, 3410, 225, 131, 259, 20597, 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, 20597, 1338, 5541, 1832, 288, 203, 6528, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 67, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xAc8D8e2B95A3bfBfEc476C32b15903fe8952F75d/sources/project_/contracts/lock/PinkLock02.sol
Truncation is expected here
tgeReleaseAmount;
11,632,340
[ 1, 18002, 367, 353, 2665, 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, 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, 5411, 268, 908, 7391, 6275, 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 ]
./partial_match/1/0xCbBfC2Ce0c227fB40295954Caf01B7345EDb1248/sources/CryptojoyTokenSeller.sol
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero./ assert(a == b * c + a % b); There is no case in which this doesn't hold
function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; }
3,582,289
[ 1, 4522, 16536, 434, 2795, 5600, 6956, 1776, 326, 26708, 16, 15226, 87, 603, 16536, 635, 3634, 18, 19, 1815, 12, 69, 422, 324, 225, 276, 397, 279, 738, 324, 1769, 225, 6149, 353, 1158, 648, 316, 1492, 333, 3302, 1404, 6887, 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, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 21281, 3639, 327, 276, 31, 203, 565, 289, 203, 21281, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/ISecurity.sol"; /** * @title LockingSecurity * @author Mathieu Bour, Valentin Pollart and Clarisse Tarrou for the DeepSquare Association. * @notice Allow to lock DPS tokens on holders balances for a certain amount of time. * @dev This contracts acts as a replacement the SpenderSecurity contract, by allowing DPS holders to receive funds, * but restricting the to move the funds before a certain date. * In order to continue to conduct private DPS sale, it introduces the SALE role, which is essentially the same as the * former SPENDER role. * In the future, we will probably write v2 of this contract which will save gas by using time-ordered locks. */ contract LockingSecurity is ISecurity, AccessControl, Ownable { struct Lock { uint256 value; // The lock DPS amount uint256 release; // The release date in seconds since the epoch } bytes32 public constant SALE = keccak256("SALE"); /** * @dev The vested token. */ IERC20 public DPS; /** * @dev The DPS/SQUARE bridge address. */ address public bridge; /** * @dev The vesting locks, mapped by account addresses. * There is no guarantee that the locks are ordered by release date time. */ mapping(address => Lock[]) private _locks; constructor(IERC20 _token) ISecurity() { DPS = _token; _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @notice Check if the DPS transfer should be authorized. * @param sender The account which triggered the transfer. * @param from The account from where the tokens will be taken. * @dev Requirements: * - if the sender is the bridge or has the role 'DEFAULT_ADMIN_ROLE' or has the role 'SALE', no further verification is made. * - else, the receiver has to be the bridge and the account from where the tokens will be taken has to have sufficient available funds. */ function validateTokenTransfer( address sender, address from, address to, uint256 amount ) external { if (sender == bridge || hasRole(DEFAULT_ADMIN_ROLE, sender) || hasRole(SALE, sender)) { return; } require(to == bridge, "LockingSecurity: destination is not the bridge"); // solhint-disable-next-line not-rely-on-time require( amount <= available(from, block.timestamp), "LockingSecurity: transfer amount exceeds available tokens" ); // solhint-disable-next-line not-rely-on-time Lock[] memory newSchedule = schedule(from, block.timestamp); // If schedule length is different than the locks, it means that some locks need to be deleted if (_locks[from].length != newSchedule.length) { delete _locks[from]; for (uint256 i = 0; i < newSchedule.length; i++) { _locks[from][i] = newSchedule[i]; } } } /** * @notice Allow the owner to upgrade the bridge. * @param newBridge New address of the bridge. */ function upgradeBridge(address newBridge) external onlyRole(DEFAULT_ADMIN_ROLE) { bridge = newBridge; } /** * @notice Returns the list of an investors locked funds. * @dev Works as a getter. * @param investor Address of the investor. */ function locks(address investor) public view returns (Lock[] memory) { return _locks[investor]; } /** * @notice Get the vesting schedule of an account. * @dev There is date or amount sorting guarantee. * @param account The address to check */ function schedule(address account, uint256 currentDate) public view returns (Lock[] memory) { Lock[] memory _accountLocks = locks(account); Lock[] memory _tmpLocks = new Lock[](_accountLocks.length); uint256 found = 0; for (uint256 i = 0; i < _accountLocks.length; i++) { if (_accountLocks[i].release < currentDate) continue; _tmpLocks[found] = _accountLocks[i]; found++; } Lock[] memory _activeLocks = new Lock[](found); for (uint256 j = 0; j < found; j++) { _activeLocks[j] = _tmpLocks[j]; } return _activeLocks; } /** * @notice Compute how much tokens are locked for a give account. * @dev This acts a as "minimum balance". * @param account The address to check * @param currentDate The date reference to use. */ function locked(address account, uint256 currentDate) public view returns (uint256) { Lock[] memory _activeLocks = schedule(account, currentDate); uint256 sum = 0; for (uint256 i = 0; i < _activeLocks.length; i++) { sum += _activeLocks[i].value; } return sum; } /** * @notice Compute how much DPS is available (=not locked) for a given account at a given date. * @param account The address of the account to check. * @param currentDate The date to check. */ function available(address account, uint256 currentDate) public view returns (uint256) { uint256 a = DPS.balanceOf(account); uint256 b = locked(account, currentDate); return a <= b ? 0 : a - b; } /** * @notice Lock DPS to an investor. * @param investor Address of the investor. * @param details The amount to lock and the release date in epoch. */ function lock(address investor, Lock memory details) public onlyRole(DEFAULT_ADMIN_ROLE) { _locks[investor].push(details); } /** * @notice Batch lock DPS to investors. * @param investors Address of the investors. * @param details The lock details. */ function lockBatch(address[] memory investors, Lock[] memory details) external onlyRole(DEFAULT_ADMIN_ROLE) { require(investors.length == details.length, "LockingSecurity: lock batch size mismatch"); for (uint256 i = 0; i < investors.length; i++) { lock(investors[i], details[i]); } } /** * @notice Lock and transfer DPS to an investor at the same time. * @dev The sender has to allow the contract to transfer DPS first using the increaseAllowance method first. * @param investor Address of the investor. * @param details The amount to lock and the release date in epoch. */ function vest(address investor, Lock memory details) public onlyRole(DEFAULT_ADMIN_ROLE) { _locks[investor].push(details); DPS.transferFrom(msg.sender, investor, details.value); } /** * @notice Batch lock DPS to investors. * @param investors Address of the investors. * @param details The lock details. */ function vestBatch(address[] memory investors, Lock[] memory details) external onlyRole(DEFAULT_ADMIN_ROLE) { require(investors.length == details.length, "LockingSecurity: vest batch size mismatch"); for (uint256 i = 0; i < investors.length; i++) { vest(investors[i], details[i]); } } }
solhint-disable-next-line not-rely-on-time
Lock[] memory newSchedule = schedule(from, block.timestamp);
1,015,051
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 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, 3639, 3488, 8526, 3778, 394, 6061, 273, 4788, 12, 2080, 16, 1203, 18, 5508, 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 ]
pragma solidity 0.5.3; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title PaymentDistributor * @dev distributes all the received funds between project wallets and team members. */ contract PaymentDistributor is Ownable { using SafeMath for uint256; event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); // timestamp when fund backup release is enabled uint256 private _backupReleaseTime; uint256 private _totalReleased; mapping(address => uint256) private _released; uint256 private constant step1Fund = uint256(5000) * 10 ** 18; address payable private _beneficiary0; address payable private _beneficiary1; address payable private _beneficiary2; address payable private _beneficiary3; address payable private _beneficiary4; address payable private _beneficiaryBackup; /** * @dev Constructor */ constructor (address payable beneficiary0, address payable beneficiary1, address payable beneficiary2, address payable beneficiary3, address payable beneficiary4, address payable beneficiaryBackup, uint256 backupReleaseTime) public { _beneficiary0 = beneficiary0; _beneficiary1 = beneficiary1; _beneficiary2 = beneficiary2; _beneficiary3 = beneficiary3; _beneficiary4 = beneficiary4; _beneficiaryBackup = beneficiaryBackup; _backupReleaseTime = backupReleaseTime; } /** * @dev payable fallback */ function () external payable { emit PaymentReceived(msg.sender, msg.value); } /** * @return the total amount already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @return the amount already released to an account. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @return the beneficiary0 of the Payments. */ function beneficiary0() public view returns (address) { return _beneficiary0; } /** * @return the beneficiary1 of the Payments. */ function beneficiary1() public view returns (address) { return _beneficiary1; } /** * @return the beneficiary2 of the Payments. */ function beneficiary2() public view returns (address) { return _beneficiary2; } /** * @return the beneficiary3 of the Payments. */ function beneficiary3() public view returns (address) { return _beneficiary3; } /** * @return the beneficiary4 of the Payments. */ function beneficiary4() public view returns (address) { return _beneficiary4; } /** * @return the beneficiaryBackup of Payments. */ function beneficiaryBackup() public view returns (address) { return _beneficiaryBackup; } /** * @return the time when Payments are released to the beneficiaryBackup wallet. */ function backupReleaseTime() public view returns (uint256) { return _backupReleaseTime; } /** * @dev send to one of the beneficiarys' addresses. * @param account Whose the fund will be send to. * @param amount Value in wei to be sent */ function sendToAccount(address payable account, uint256 amount) internal { require(amount > 0, 'The amount must be greater than zero.'); _released[account] = _released[account].add(amount); _totalReleased = _totalReleased.add(amount); account.transfer(amount); emit PaymentReleased(account, amount); } /** * @dev distributes the amount between team's wallets * which are created for different purposes. * @param amount Value in wei to send to the wallets. */ function release(uint256 amount) onlyOwner public{ require(address(this).balance >= amount, 'Balance must be greater than or equal to the amount.'); uint256 _value = amount; if (_released[_beneficiary0] < step1Fund) { if (_released[_beneficiary0].add(_value) > step1Fund){ uint256 _remainValue = step1Fund.sub(_released[_beneficiary0]); _value = _value.sub(_remainValue); sendToAccount(_beneficiary0, _remainValue); } else { sendToAccount(_beneficiary0, _value); _value = 0; } } if (_value > 0) { uint256 _value1 = _value.mul(10).div(100); //10% uint256 _value2 = _value.mul(7020).div(10000); //70.2% uint256 _value3 = _value.mul(1080).div(10000); //10.8% uint256 _value4 = _value.mul(9).div(100); //9% sendToAccount(_beneficiary1, _value1); sendToAccount(_beneficiary2, _value2); sendToAccount(_beneficiary3, _value3); sendToAccount(_beneficiary4, _value4); } } /** * @dev transfer the amount to the beneficiaryBackup wallet * which are created for different purposes. * @param amount Value in wei to send to the backup wallet. */ function releaseBackup(uint256 amount) onlyOwner public{ require(address(this).balance >= amount, 'Balance must be greater than or equal to the amount.'); require(block.timestamp >= backupReleaseTime(), 'The transfer is possible only 2 months after the ICO.'); sendToAccount(_beneficiaryBackup, amount); } }
* @title PaymentDistributor @dev distributes all the received funds between project wallets and team members./ timestamp when fund backup release is enabled
contract PaymentDistributor is Ownable { using SafeMath for uint256; event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _backupReleaseTime; uint256 private _totalReleased; mapping(address => uint256) private _released; uint256 private constant step1Fund = uint256(5000) * 10 ** 18; address payable private _beneficiary0; address payable private _beneficiary1; address payable private _beneficiary2; address payable private _beneficiary3; address payable private _beneficiary4; address payable private _beneficiaryBackup; constructor (address payable beneficiary0, address payable beneficiary1, address payable beneficiary2, address payable beneficiary3, address payable beneficiary4, address payable beneficiaryBackup, uint256 backupReleaseTime) public { _beneficiary0 = beneficiary0; _beneficiary1 = beneficiary1; _beneficiary2 = beneficiary2; _beneficiary3 = beneficiary3; _beneficiary4 = beneficiary4; _beneficiaryBackup = beneficiaryBackup; _backupReleaseTime = backupReleaseTime; } function () external payable { emit PaymentReceived(msg.sender, msg.value); } function totalReleased() public view returns (uint256) { return _totalReleased; } function released(address account) public view returns (uint256) { return _released[account]; } function beneficiary0() public view returns (address) { return _beneficiary0; } function beneficiary1() public view returns (address) { return _beneficiary1; } function beneficiary2() public view returns (address) { return _beneficiary2; } function beneficiary3() public view returns (address) { return _beneficiary3; } function beneficiary4() public view returns (address) { return _beneficiary4; } function beneficiaryBackup() public view returns (address) { return _beneficiaryBackup; } function backupReleaseTime() public view returns (uint256) { return _backupReleaseTime; } function sendToAccount(address payable account, uint256 amount) internal { require(amount > 0, 'The amount must be greater than zero.'); _released[account] = _released[account].add(amount); _totalReleased = _totalReleased.add(amount); account.transfer(amount); emit PaymentReleased(account, amount); } function release(uint256 amount) onlyOwner public{ require(address(this).balance >= amount, 'Balance must be greater than or equal to the amount.'); uint256 _value = amount; if (_released[_beneficiary0] < step1Fund) { if (_released[_beneficiary0].add(_value) > step1Fund){ uint256 _remainValue = step1Fund.sub(_released[_beneficiary0]); _value = _value.sub(_remainValue); sendToAccount(_beneficiary0, _remainValue); } else { sendToAccount(_beneficiary0, _value); _value = 0; } } if (_value > 0) { sendToAccount(_beneficiary1, _value1); sendToAccount(_beneficiary2, _value2); sendToAccount(_beneficiary3, _value3); sendToAccount(_beneficiary4, _value4); } } function release(uint256 amount) onlyOwner public{ require(address(this).balance >= amount, 'Balance must be greater than or equal to the amount.'); uint256 _value = amount; if (_released[_beneficiary0] < step1Fund) { if (_released[_beneficiary0].add(_value) > step1Fund){ uint256 _remainValue = step1Fund.sub(_released[_beneficiary0]); _value = _value.sub(_remainValue); sendToAccount(_beneficiary0, _remainValue); } else { sendToAccount(_beneficiary0, _value); _value = 0; } } if (_value > 0) { sendToAccount(_beneficiary1, _value1); sendToAccount(_beneficiary2, _value2); sendToAccount(_beneficiary3, _value3); sendToAccount(_beneficiary4, _value4); } } function release(uint256 amount) onlyOwner public{ require(address(this).balance >= amount, 'Balance must be greater than or equal to the amount.'); uint256 _value = amount; if (_released[_beneficiary0] < step1Fund) { if (_released[_beneficiary0].add(_value) > step1Fund){ uint256 _remainValue = step1Fund.sub(_released[_beneficiary0]); _value = _value.sub(_remainValue); sendToAccount(_beneficiary0, _remainValue); } else { sendToAccount(_beneficiary0, _value); _value = 0; } } if (_value > 0) { sendToAccount(_beneficiary1, _value1); sendToAccount(_beneficiary2, _value2); sendToAccount(_beneficiary3, _value3); sendToAccount(_beneficiary4, _value4); } } function release(uint256 amount) onlyOwner public{ require(address(this).balance >= amount, 'Balance must be greater than or equal to the amount.'); uint256 _value = amount; if (_released[_beneficiary0] < step1Fund) { if (_released[_beneficiary0].add(_value) > step1Fund){ uint256 _remainValue = step1Fund.sub(_released[_beneficiary0]); _value = _value.sub(_remainValue); sendToAccount(_beneficiary0, _remainValue); } else { sendToAccount(_beneficiary0, _value); _value = 0; } } if (_value > 0) { sendToAccount(_beneficiary1, _value1); sendToAccount(_beneficiary2, _value2); sendToAccount(_beneficiary3, _value3); sendToAccount(_beneficiary4, _value4); } } function release(uint256 amount) onlyOwner public{ require(address(this).balance >= amount, 'Balance must be greater than or equal to the amount.'); uint256 _value = amount; if (_released[_beneficiary0] < step1Fund) { if (_released[_beneficiary0].add(_value) > step1Fund){ uint256 _remainValue = step1Fund.sub(_released[_beneficiary0]); _value = _value.sub(_remainValue); sendToAccount(_beneficiary0, _remainValue); } else { sendToAccount(_beneficiary0, _value); _value = 0; } } if (_value > 0) { sendToAccount(_beneficiary1, _value1); sendToAccount(_beneficiary2, _value2); sendToAccount(_beneficiary3, _value3); sendToAccount(_beneficiary4, _value4); } } function releaseBackup(uint256 amount) onlyOwner public{ require(address(this).balance >= amount, 'Balance must be greater than or equal to the amount.'); require(block.timestamp >= backupReleaseTime(), 'The transfer is possible only 2 months after the ICO.'); sendToAccount(_beneficiaryBackup, amount); } }
7,326,881
[ 1, 6032, 1669, 19293, 225, 1015, 1141, 777, 326, 5079, 284, 19156, 3086, 1984, 17662, 2413, 471, 5927, 4833, 18, 19, 2858, 1347, 284, 1074, 5114, 3992, 353, 3696, 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, 16351, 12022, 1669, 19293, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 12022, 26363, 12, 2867, 358, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 12022, 8872, 12, 2867, 628, 16, 2254, 5034, 3844, 1769, 203, 203, 565, 2254, 5034, 3238, 389, 9572, 7391, 950, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 26363, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 9340, 72, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 2235, 21, 42, 1074, 273, 2254, 5034, 12, 25, 3784, 13, 380, 1728, 2826, 6549, 31, 203, 203, 565, 1758, 8843, 429, 3238, 389, 70, 4009, 74, 14463, 814, 20, 31, 203, 565, 1758, 8843, 429, 3238, 389, 70, 4009, 74, 14463, 814, 21, 31, 203, 565, 1758, 8843, 429, 3238, 389, 70, 4009, 74, 14463, 814, 22, 31, 203, 565, 1758, 8843, 429, 3238, 389, 70, 4009, 74, 14463, 814, 23, 31, 203, 565, 1758, 8843, 429, 3238, 389, 70, 4009, 74, 14463, 814, 24, 31, 203, 565, 1758, 8843, 429, 3238, 389, 70, 4009, 74, 14463, 814, 6248, 31, 203, 203, 565, 3885, 261, 2867, 8843, 429, 27641, 74, 14463, 814, 20, 16, 1758, 8843, 429, 27641, 74, 14463, 814, 21, 16, 1758, 8843, 429, 27641, 74, 14463, 814, 22, 16, 1758, 8843, 429, 27641, 74, 14463, 814, 23, 16, 1758, 8843, 429, 27641, 74, 14463, 814, 24, 16, 1758, 8843, 429, 27641, 74, 14463, 814, 6248, 16, 2254, 5034, 5114, 7391, 950, 13, 1071, 288, 2 ]
./full_match/1/0x4E551D776014CE6836E6e6d7170144eBF37e52e1/sources/contracts/flashloan/FlashAngle.sol
@inheritdoc IERC3156FlashLender Token must be an agToken here so normally no need to use `safeTransferFrom`, but out of safety and in case governance whitelists an agToken which does not have a correct implementation, we prefer to use `safeTransferFrom` here
function flashLoan( IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data ) external nonReentrant returns (bool) { uint256 fee = _flashFee(token, amount); if (amount > stablecoinMap[IAgToken(token)].maxBorrowable) revert TooBigAmount(); IAgToken(token).mint(address(receiver), amount); if (receiver.onFlashLoan(msg.sender, token, amount, fee, data) != CALLBACK_SUCCESS) revert InvalidReturnMessage(); IERC20(token).safeTransferFrom(address(receiver), address(this), amount + fee); IAgToken(token).burnSelf(amount, address(this)); emit FlashLoan(token, amount, receiver); return true; }
4,950,685
[ 1, 36, 10093, 467, 654, 39, 23, 28946, 11353, 48, 2345, 3155, 1297, 506, 392, 1737, 1345, 2674, 1427, 15849, 1158, 1608, 358, 999, 1375, 4626, 5912, 1265, 9191, 1496, 596, 434, 24179, 471, 316, 648, 314, 1643, 82, 1359, 600, 305, 292, 1486, 392, 1737, 1345, 1492, 1552, 486, 1240, 279, 3434, 4471, 16, 732, 13256, 358, 999, 1375, 4626, 5912, 1265, 68, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 9563, 1504, 304, 12, 203, 3639, 467, 654, 39, 23, 28946, 11353, 38, 15318, 264, 5971, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 745, 892, 501, 203, 565, 262, 3903, 1661, 426, 8230, 970, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 14036, 273, 389, 13440, 14667, 12, 2316, 16, 3844, 1769, 203, 3639, 309, 261, 8949, 405, 14114, 12645, 863, 63, 45, 2577, 1345, 12, 2316, 13, 8009, 1896, 38, 15318, 429, 13, 15226, 15869, 9901, 6275, 5621, 203, 3639, 467, 2577, 1345, 12, 2316, 2934, 81, 474, 12, 2867, 12, 24454, 3631, 3844, 1769, 203, 3639, 309, 261, 24454, 18, 265, 11353, 1504, 304, 12, 3576, 18, 15330, 16, 1147, 16, 3844, 16, 14036, 16, 501, 13, 480, 22753, 8720, 67, 12778, 13, 203, 5411, 15226, 1962, 990, 1079, 5621, 203, 3639, 467, 654, 39, 3462, 12, 2316, 2934, 4626, 5912, 1265, 12, 2867, 12, 24454, 3631, 1758, 12, 2211, 3631, 3844, 397, 14036, 1769, 203, 3639, 467, 2577, 1345, 12, 2316, 2934, 70, 321, 10084, 12, 8949, 16, 1758, 12, 2211, 10019, 203, 3639, 3626, 15014, 1504, 304, 12, 2316, 16, 3844, 16, 5971, 1769, 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 ]
./partial_match/1287/0x32833245CE5b0fefd8d86527eAbb9481e82De001/sources/project_/contracts/GenesisMinter.sol
Interfaces to access minter and details editor functions
AvatarDetailEditor detailEditor = AvatarDetailEditor(genesisAvatarContract);
16,903,879
[ 1, 10273, 358, 2006, 1131, 387, 471, 3189, 4858, 4186, 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, 8789, 8761, 6109, 6946, 7664, 6946, 273, 8789, 8761, 6109, 6946, 12, 4507, 16786, 23999, 8924, 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 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./ERC721A.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract FlungNFT is ERC721A, Ownable { using Strings for uint256; uint256 public constant WHITELIST_MAX = 5; uint256 public constant RESERVE_MAX = 2; uint256 public constant TOTAL_MAX = 12; uint256 public constant MAX_SALE_QUANTITY = 3; uint256 public whitelistPrice = 0.01 ether; uint256 public whitelistCount; uint256 public reserveCount; uint32 public startTime; bool public saleActive; bool public whitelistActive; bool private whitelistEnded; struct DAVariables { uint64 saleStartPrice; uint64 duration; uint64 interval; uint64 decreaseRate; } DAVariables public daVariables; mapping(address => uint256) public whitelists; string private baseURI; bool public revealed; address private paymentAddress; address private royaltyAddress; uint96 private royaltyBasisPoints = 810; bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; constructor() ERC721A("FashionNFT", "FNFT") {} /** * @notice not locked modifier */ modifier notEnded() { require(!whitelistEnded, "WHITELIST_ENDED"); _; } /** * @notice mint from whitelist * @dev must occur before public sale */ function mintWhitelist(uint256 _quantity) external payable notEnded { require(whitelistActive, "WHITELIST_INACTIVE"); uint256 remaining = whitelists[msg.sender]; require(whitelistCount + _quantity <= WHITELIST_MAX, "WHITELIST_MAXED"); require(remaining != 0 && _quantity <= remaining, "UNAUTHORIZED"); require(msg.value == whitelistPrice * _quantity, "INCORRECT_ETH"); if (_quantity == remaining) { delete whitelists[msg.sender]; } else { whitelists[msg.sender] = whitelists[msg.sender] - _quantity; } whitelistCount = whitelistCount + _quantity; _safeMint(msg.sender, _quantity); } /** * @notice buy from sale (dutch auction) * @dev must occur after whitelist sale */ function buy(uint256 _quantity) external payable { require(saleActive, "SALE_INACTIVE"); require(tx.origin == msg.sender, "NOT_EOA"); require( _numberMinted(msg.sender) + _quantity <= MAX_SALE_QUANTITY, "QUANTITY_MAXED" ); require( (totalSupply() - reserveCount) + _quantity <= TOTAL_MAX - RESERVE_MAX, "SALE_MAXED" ); uint256 mintCost; DAVariables memory _daVariables = daVariables; if (block.timestamp - startTime >= _daVariables.duration) { mintCost = whitelistPrice * _quantity; } else { uint256 steps = (block.timestamp - startTime) / _daVariables.interval; mintCost = (daVariables.saleStartPrice - (steps * _daVariables.decreaseRate)) * _quantity; } require(msg.value >= mintCost, "INSUFFICIENT_ETH"); _mint(msg.sender, _quantity, "", true); if (msg.value > mintCost) { payable(msg.sender).transfer(msg.value - mintCost); } } /** * @notice release reserve */ function releaseReserve(address _account, uint256 _quantity) external onlyOwner { require(_quantity > 0, "INVALID_QUANTITY"); require(reserveCount + _quantity <= RESERVE_MAX, "RESERVE_MAXED"); reserveCount = reserveCount + _quantity; _safeMint(_account, _quantity); } /** * @notice return number of tokens minted by owner */ function saleMax() external view returns (uint256) { if (!whitelistEnded) { return TOTAL_MAX - RESERVE_MAX - WHITELIST_MAX; } return TOTAL_MAX - RESERVE_MAX - whitelistCount; } /** * @notice return number of tokens minted by owner */ function numberMinted(address owner) external view returns (uint256) { return _numberMinted(owner); } /** * @notice return current sale price */ function getCurrentPrice() external view returns (uint256) { if (!saleActive) { return daVariables.saleStartPrice; } DAVariables memory _daVariables = daVariables; if (block.timestamp - startTime >= _daVariables.duration) { return whitelistPrice; } else { uint256 steps = (block.timestamp - startTime) / _daVariables.interval; return daVariables.saleStartPrice - (steps * _daVariables.decreaseRate); } } /** * @notice active whitelist */ function activateWhitelist() external onlyOwner { !whitelistActive ? whitelistActive = true : whitelistActive = false; } /** * @notice active sale */ function activateSale() external onlyOwner { require(daVariables.saleStartPrice != 0, "SALE_VARIABLES_NOT_SET"); if (!whitelistEnded) whitelistEnded = true; if (whitelistActive) whitelistActive = false; if (startTime == 0) { startTime = uint32(block.timestamp); } !saleActive ? saleActive = true : saleActive = false; } /** * @notice set sale startTime */ function setSaleVariables( uint32 _startTime, uint64 _saleStartPrice, uint64 _duration, uint64 _interval, uint64 _decreaseRate ) external onlyOwner { require(!saleActive); startTime = _startTime; daVariables = DAVariables({ saleStartPrice: _saleStartPrice, duration: _duration, interval: _interval, decreaseRate: _decreaseRate }); } /** * @notice set base URI */ function setBaseURI(string calldata _baseURI, bool reveal) external onlyOwner { if (!revealed && reveal) revealed = reveal; baseURI = _baseURI; } /** * @notice set payment address */ function setPaymentAddress(address _paymentAddress) external onlyOwner { paymentAddress = _paymentAddress; } /** * @notice set royalty address */ function setRoyaltyAddress(address _royaltyAddress) external onlyOwner { royaltyAddress = _royaltyAddress; } /** * @notice set royalty rate */ function setRoyalty(uint96 _royaltyBasisPoints) external onlyOwner { royaltyBasisPoints = _royaltyBasisPoints; } /** * @notice set whitelist price */ function setWhitelistPrice(uint256 _newPrice) external onlyOwner { whitelistPrice = _newPrice; } /** * @notice add addresses to whitelist */ function setWhitelist(address[] calldata whitelisters, bool ogStatus) external onlyOwner { uint256 quantity = ogStatus ? 2 : 1; for (uint256 i; i < whitelisters.length; i++) { whitelists[whitelisters[i]] = quantity; } } /** * @notice token URI */ function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "Cannot query non-existent token"); if (revealed) { return string(abi.encodePacked(baseURI, _tokenId.toString())); } else{ return baseURI; } } /** * @notice royalty information */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { require(_exists(_tokenId), "Cannot query non-existent token"); return (royaltyAddress, (_salePrice * royaltyBasisPoints) / 10000); } /** * @notice supports interface * @dev overridden for EIP2981 royalties */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721A) returns (bool) { if (interfaceId == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(interfaceId); } /** * @notice transfer funds */ function transferFunds() external onlyOwner { (bool success, ) = payable(paymentAddress).call{ value: address(this).balance }(""); require(success, "TRANSFER_FAILED"); } } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/utils/Context.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); 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 override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _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 { _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 { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) 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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface 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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) 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 // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) 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); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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); }
* @notice set payment address/
function setPaymentAddress(address _paymentAddress) external onlyOwner { paymentAddress = _paymentAddress; }
5,963,145
[ 1, 542, 5184, 1758, 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, 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, 445, 444, 6032, 1887, 12, 2867, 389, 9261, 1887, 13, 3903, 1338, 5541, 288, 203, 3639, 5184, 1887, 273, 389, 9261, 1887, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; ///@title MarketPlace DApp ///@author Zeinab-Salimi ///@notice Simple Market Place for Consensys 2020 Bootcamp Final Project contract MarketPlace is Ownable { //Uses SafeMath library to avoid integer overflow/underflow attacks using SafeMath for uint256; uint256 public storeOwnersCount; uint256 public adminCount; uint256 public storeCount; uint256 public productCount; bool public marktState; mapping(address => bool) public admins; mapping(address => bool) public storeOwners; mapping(uint256 => StoreFront) public storeFronts; mapping(address => uint256[]) public storeOwnertoStoreFront; mapping(uint256 => address) public storeFronttoStoreOwner; mapping(uint256 => Product) public StoreProducts; mapping(uint256 => uint256[]) public stotrFronttoProducts; struct StoreFront { string storeName; address storeOwner; address approverAdmin; uint256 skuCount; uint256 balance; } struct Product { string name; uint256 storeNum; uint256 productNum; uint256 price; uint256 quantity; bool isAvailable; } enum addressTypes {admin, storeOwner, shopper} event marketStateChanged(bool state); event storeOwnerAdded(address newStoreOwner); event storeFrontCreated( uint256 storeNum, string storeName, address storeOwner ); event productAdded( uint256 storeNum, string productName, uint256 productNum ); event productPriceUpdated(uint256 storeNum, uint256 productNum); event productRemoved(uint256 storeNum, uint256 productNum); event storeWithdrawn(uint256 amount, uint256 storeNum, address storeOwner); event productPurchased( uint256 storeNum, uint256 productNum, uint256 quantity, address shopper ); /** @dev verifies the msg.sender is an admin */ modifier onlyAdmin() { require(admins[msg.sender], "Sorry, you are not admin!"); _; } /** @dev verifies the msg.sender is the store owner */ modifier onlyStoreOwner() { require(storeOwners[msg.sender], "Sorry, you are not a store owner!"); _; } /** @dev verifies the msg.sender is not a store owner or admin */ modifier onlyShopper() { require( !storeOwners[msg.sender], "Sorry, store owner is not allowed to buy products!" ); require( !admins[msg.sender], "Sorry, admin is not allowed to buy products!" ); _; } /** @dev verifies market state */ modifier isMarketActive() { require(marktState, "Sorry, Market state is inactive!"); _; } /** @dev verifies the msg.sender is the store owner of the store front */ modifier verifyStoreOwner(uint256 storeNum) { require( storeFronttoStoreOwner[storeNum] == msg.sender, "Sorry, you are not a store owner!" ); _; } /** @dev constracter initalises state variables */ constructor() public { admins[msg.sender] = true; storeOwnersCount = 0; adminCount = 1; storeCount = 0; productCount = 0; marktState = true; } /**----------------------------------------------------------------------- ------------------------ Admin Functions ---------------------- -----------------------------------------------------------------------*/ /** @dev admin allowed to add a new store owner * @param _newStoreOwner new store owner addrress */ function addStoreOwner(address _newStoreOwner) public onlyAdmin() isMarketActive() { require( storeOwners[_newStoreOwner] == false, "Sorry, store owner already exists!" ); storeOwners[_newStoreOwner] = true; storeOwnersCount = SafeMath.add(storeOwnersCount, 1); emit storeOwnerAdded(_newStoreOwner); } /** @dev market owner allowed to chainge marketplace state * @param _state new market state */ function changeMarketState(bool _state) public onlyAdmin() { require(marktState != _state, "Sorry, this is the current state!!"); marktState = _state; emit marketStateChanged(_state); } /** @dev returns the current state of marketplace */ function getMarketState() public view returns (bool) { return marktState; } /** @dev returns (true) if the address is an admin, otherwise returns (false) */ function isAdmin(address _address) public view returns (bool) { return admins[_address]; } /** @dev returns (true) if the address is store owner, otherwise returns (false) */ function isStoreOwner(address _address) public view returns (bool) { return storeOwners[_address]; } /** @dev returns the number of active store owners */ function getNumberOfStoreOwners() public view onlyAdmin() returns (uint256) { return storeOwnersCount; } /** @dev returns the type of address (market owner, admin, store owner, or shopper) */ function addressType() public view returns (addressTypes) { if (msg.sender == super.owner()) return addressTypes.admin; if (storeOwners[msg.sender]) return addressTypes.storeOwner; else return addressTypes.shopper; } /** @dev View contract balance * @return balance of all store fronts */ function getContractBalance() public view onlyOwner() returns (uint256) { return address(this).balance; } /** @dev selfdestruct the contract to destroy the contract in case of bugs */ function destroyContract() public onlyOwner() { selfdestruct(address(this)); } /**----------------------------------------------------------------------- ------------------------ Store Owner Functions ---------------------- -----------------------------------------------------------------------*/ /** @dev store owner is allowed to add a new store front * @param _storeName new market state * @return the store number */ function createStoreFront(string memory _storeName) public onlyStoreOwner() isMarketActive() returns (bool) { storeCount = SafeMath.add(storeCount, 1); storeFronts[storeCount] = StoreFront({ storeName: _storeName, storeOwner: msg.sender, approverAdmin: address(0), skuCount: 0, balance: 0 }); storeOwnertoStoreFront[msg.sender].push(storeCount); storeFronttoStoreOwner[storeCount] = msg.sender; emit storeFrontCreated(storeCount, _storeName, msg.sender); return true; } /** @dev Store owner allowed to add a new product to their store front * @param _storeNum storefront number * @param _productName product name * @param _productPrice product price * @param _productQuantity available quantity of the product */ function addProduct( uint256 _storeNum, string memory _productName, uint256 _productPrice, uint256 _productQuantity ) public verifyStoreOwner(_storeNum) isMarketActive() returns (uint256) { require(_productPrice > 0, "Sorry, invalid product price!"); require(_productQuantity > 0, "Sorry, invalid product quantity!"); storeFronts[_storeNum].skuCount = SafeMath.add( storeFronts[_storeNum].skuCount, 1 ); productCount = SafeMath.add(productCount, 1); StoreProducts[productCount] = Product({ name: _productName, storeNum: _storeNum, productNum: productCount, price: _productPrice, quantity: _productQuantity, isAvailable: true }); stotrFronttoProducts[_storeNum].push(productCount); emit productAdded(_storeNum, _productName, productCount); return productCount; } /** @dev Store owner allowed to update product price * @param _storeNum store front number * @param _productNum product nunmber * @param _newProductPrice product price */ function updateProductPrice( uint256 _storeNum, uint256 _productNum, uint256 _newProductPrice ) public verifyStoreOwner(_storeNum) isMarketActive() returns (bool) { require(_newProductPrice > 0, "Sorry, invalid product price!"); StoreProducts[_productNum].price = _newProductPrice; emit productPriceUpdated(_storeNum, _productNum); return true; } /** @dev Store owner allowed to remove product * @param _storeNum store front number * @param _productNum product nunmber */ function removeProduct(uint256 _storeNum, uint256 _productNum) public verifyStoreOwner(_storeNum) isMarketActive() returns (bool) { StoreProducts[_productNum].isAvailable = false; StoreProducts[_productNum].quantity = 0; emit productRemoved(_storeNum, _productNum); return true; } /** @dev return total number of store fronts */ function getStoreFrontCount() public view returns (uint) { return storeCount; } /** @dev Store owner can withdraw balance from their store fronts * @param _storeNum store front number */ function withdraw(uint256 _storeNum) public payable verifyStoreOwner(_storeNum) isMarketActive() { require( storeFronts[_storeNum].balance > 0, "Sorry, no funds available!" ); uint256 amount = storeFronts[_storeNum].balance; storeFronts[_storeNum].balance = 0; msg.sender.transfer(amount); emit storeWithdrawn(amount, _storeNum, msg.sender); } /** @dev return store front info * @param _storeNum store front number */ function getStoreFrontInfo(uint256 _storeNum) public view returns ( string memory, address, address, uint256, uint256 ) { return ( storeFronts[_storeNum].storeName, storeFronts[_storeNum].storeOwner, storeFronts[_storeNum].approverAdmin, storeFronts[_storeNum].skuCount, storeFronts[_storeNum].balance ); } /** @dev return store front by store owner address */ function getStoreFrontByStoreOwner() public view returns(uint[] memory){ return storeOwnertoStoreFront[msg.sender]; } /** @dev return products info * @param _productNum product number */ function getProductInfo(uint256 _productNum) public view returns ( string memory, uint256, uint256, uint256, uint256, bool ) { return ( StoreProducts[_productNum].name, StoreProducts[_productNum].storeNum, StoreProducts[_productNum].productNum, StoreProducts[_productNum].price, StoreProducts[_productNum].quantity, StoreProducts[_productNum].isAvailable ); } /** @dev return products by store front * @param _storeNum store front number */ function getProductsByStoreFront(uint _storeNum) public view returns(uint[] memory){ return stotrFronttoProducts[_storeNum]; } /**----------------------------------------------------------------------- -------------------------- Shopper Functions ------------------------ -----------------------------------------------------------------------*/ /** @dev Shopper allowed to purchase a product * @param _storeNum store front number * @param _productNum product number */ function purchaseProduct(uint256 _storeNum, uint256 _productNum) public payable onlyShopper() isMarketActive() returns (bool) { require( StoreProducts[_productNum].price <= msg.value, "Sorry, transferred value is less than the product price!" ); require( StoreProducts[_productNum].quantity > 0, "Sorry, product is not available!" ); uint256 quantity = SafeMath.div( msg.value, StoreProducts[_productNum].price ); StoreProducts[_productNum].quantity = SafeMath.sub( StoreProducts[_productNum].quantity, quantity ); if (StoreProducts[_productNum].quantity == 0) { StoreProducts[_productNum].isAvailable = false; } storeFronts[_storeNum].balance = SafeMath.add( storeFronts[_storeNum].balance, msg.value ); emit productPurchased(_storeNum, _productNum, quantity, msg.sender); return true; } /** @dev fallback function */ receive() external payable { revert(); } }
* @dev verifies the msg.sender is the store owner of the store front */
modifier verifyStoreOwner(uint256 storeNum) { require( storeFronttoStoreOwner[storeNum] == msg.sender, "Sorry, you are not a store owner!" ); _; }
12,851,691
[ 1, 502, 5032, 326, 1234, 18, 15330, 353, 326, 1707, 3410, 434, 326, 1707, 6641, 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 ]
[ 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, 9606, 3929, 2257, 5541, 12, 11890, 5034, 1707, 2578, 13, 288, 203, 3639, 2583, 12, 203, 5411, 1707, 42, 1949, 748, 83, 2257, 5541, 63, 2233, 2578, 65, 422, 1234, 18, 15330, 16, 203, 5411, 315, 28898, 16, 1846, 854, 486, 279, 1707, 3410, 4442, 203, 3639, 11272, 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 ]
pragma solidity 0.5.14; /** * @notice Bitmap library to set or unset bits on bitmap value */ library BitmapLib { /** * @dev Sets the given bit in the bitmap value * @param _bitmap Bitmap value to update the bit in * @param _index Index range from 0 to 127 * @return Returns the updated bitmap value */ function setBit(uint128 _bitmap, uint8 _index) internal pure returns (uint128) { // Suppose `_bitmap` is in bit value: // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set // Bit not set, hence, set the bit if( ! isBitSet(_bitmap, _index)) { // Suppose `_index` is = 3 = 4th bit // mask = 0000 1000 = Left shift to create mask to find 4rd bit status uint128 mask = uint128(1) << _index; // Setting the corrospending bit in _bitmap // Performing OR (|) operation // 0001 0100 (_bitmap) // 0000 1000 (mask) // ------------------- // 0001 1100 (result) return _bitmap | mask; } // Bit already set, just return without any change return _bitmap; } /** * @dev Unsets the bit in given bitmap * @param _bitmap Bitmap value to update the bit in * @param _index Index range from 0 to 127 * @return Returns the updated bitmap value */ function unsetBit(uint128 _bitmap, uint8 _index) internal pure returns (uint128) { // Suppose `_bitmap` is in bit value: // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set // Bit is set, hence, unset the bit if(isBitSet(_bitmap, _index)) { // Suppose `_index` is = 2 = 3th bit // mask = 0000 0100 = Left shift to create mask to find 3rd bit status uint128 mask = uint128(1) << _index; // Performing Bitwise NOT(~) operation // 1111 1011 (mask) mask = ~mask; // Unsetting the corrospending bit in _bitmap // Performing AND (&) operation // 0001 0100 (_bitmap) // 1111 1011 (mask) // ------------------- // 0001 0000 (result) return _bitmap & mask; } // Bit not set, just return without any change return _bitmap; } /** * @dev Returns true if the corrosponding bit set in the bitmap * @param _bitmap Bitmap value to check * @param _index Index to check. Index range from 0 to 127 * @return Returns true if bit is set, false otherwise */ function isBitSet(uint128 _bitmap, uint8 _index) internal pure returns (bool) { require(_index < 128, "Index out of range for bit operation"); // Suppose `_bitmap` is in bit value: // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set // Suppose `_index` is = 2 = 3th bit // 0000 0100 = Left shift to create mask to find 3rd bit status uint128 mask = uint128(1) << _index; // Example: When bit is set: // Performing AND (&) operation // 0001 0100 (_bitmap) // 0000 0100 (mask) // ------------------------- // 0000 0100 (bitSet > 0) // Example: When bit is not set: // Performing AND (&) operation // 0001 0100 (_bitmap) // 0000 1000 (mask) // ------------------------- // 0000 0000 (bitSet == 0) uint128 bitSet = _bitmap & mask; // Bit is set when greater than zero, else not set return bitSet > 0; } } contract Constant { enum ActionType { DepositAction, WithdrawAction, BorrowAction, RepayAction } address public constant ETH_ADDR = 0x000000000000000000000000000000000000000E; uint256 public constant INT_UNIT = 10 ** uint256(18); uint256 public constant ACCURACY = 10 ** 18; uint256 public constant BLOCKS_PER_YEAR = 2102400; } /** * @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); } } /** * @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; } } // This is for per user library AccountTokenLib { using SafeMath for uint256; struct TokenInfo { // Deposit info uint256 depositPrincipal; // total deposit principal of ther user uint256 depositInterest; // total deposit interest of the user uint256 lastDepositBlock; // the block number of user's last deposit // Borrow info uint256 borrowPrincipal; // total borrow principal of ther user uint256 borrowInterest; // total borrow interest of ther user uint256 lastBorrowBlock; // the block number of user's last borrow } uint256 constant BASE = 10**18; // returns the principal function getDepositPrincipal(TokenInfo storage self) public view returns(uint256) { return self.depositPrincipal; } function getBorrowPrincipal(TokenInfo storage self) public view returns(uint256) { return self.borrowPrincipal; } function getDepositBalance(TokenInfo storage self, uint accruedRate) public view returns(uint256) { return self.depositPrincipal.add(calculateDepositInterest(self, accruedRate)); } function getBorrowBalance(TokenInfo storage self, uint accruedRate) public view returns(uint256) { return self.borrowPrincipal.add(calculateBorrowInterest(self, accruedRate)); } function getLastDepositBlock(TokenInfo storage self) public view returns(uint256) { return self.lastDepositBlock; } function getLastBorrowBlock(TokenInfo storage self) public view returns(uint256) { return self.lastBorrowBlock; } function getDepositInterest(TokenInfo storage self) public view returns(uint256) { return self.depositInterest; } function getBorrowInterest(TokenInfo storage self) public view returns(uint256) { return self.borrowInterest; } function borrow(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public { newBorrowCheckpoint(self, accruedRate, _block); self.borrowPrincipal = self.borrowPrincipal.add(amount); } /** * Update token info for withdraw. The interest will be withdrawn with higher priority. */ function withdraw(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public { newDepositCheckpoint(self, accruedRate, _block); if (self.depositInterest >= amount) { self.depositInterest = self.depositInterest.sub(amount); } else if (self.depositPrincipal.add(self.depositInterest) >= amount) { self.depositPrincipal = self.depositPrincipal.sub(amount.sub(self.depositInterest)); self.depositInterest = 0; } else { self.depositPrincipal = 0; self.depositInterest = 0; } } /** * Update token info for deposit */ function deposit(TokenInfo storage self, uint256 amount, uint accruedRate, uint256 _block) public { newDepositCheckpoint(self, accruedRate, _block); self.depositPrincipal = self.depositPrincipal.add(amount); } function repay(TokenInfo storage self, uint256 amount, uint accruedRate, uint256 _block) public { // updated rate (new index rate), applying the rate from startBlock(checkpoint) to currBlock newBorrowCheckpoint(self, accruedRate, _block); // user owes money, then he tries to repays if (self.borrowInterest > amount) { self.borrowInterest = self.borrowInterest.sub(amount); } else if (self.borrowPrincipal.add(self.borrowInterest) > amount) { self.borrowPrincipal = self.borrowPrincipal.sub(amount.sub(self.borrowInterest)); self.borrowInterest = 0; } else { self.borrowPrincipal = 0; self.borrowInterest = 0; } } function newDepositCheckpoint(TokenInfo storage self, uint accruedRate, uint256 _block) public { self.depositInterest = calculateDepositInterest(self, accruedRate); self.lastDepositBlock = _block; } function newBorrowCheckpoint(TokenInfo storage self, uint accruedRate, uint256 _block) public { self.borrowInterest = calculateBorrowInterest(self, accruedRate); self.lastBorrowBlock = _block; } // Calculating interest according to the new rate // calculated starting from last deposit checkpoint function calculateDepositInterest(TokenInfo storage self, uint accruedRate) public view returns(uint256) { return self.depositPrincipal.add(self.depositInterest).mul(accruedRate).sub(self.depositPrincipal.mul(BASE)).div(BASE); } function calculateBorrowInterest(TokenInfo storage self, uint accruedRate) public view returns(uint256) { uint256 _balance = self.borrowPrincipal; if(accruedRate == 0 || _balance == 0 || BASE >= accruedRate) { return self.borrowInterest; } else { return _balance.add(self.borrowInterest).mul(accruedRate).sub(_balance.mul(BASE)).div(BASE); } } } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract Accounts is Constant, Initializable{ using AccountTokenLib for AccountTokenLib.TokenInfo; using BitmapLib for uint128; using SafeMath for uint256; using Math for uint256; mapping(address => Account) public accounts; IGlobalConfig globalConfig; mapping(address => uint256) public FINAmount; modifier onlyAuthorized() { require(msg.sender == address(globalConfig.savingAccount()) || msg.sender == address(globalConfig.bank()), "Only authorized to call from DeFiner internal contracts."); _; } struct Account { // Note, it's best practice to use functions minusAmount, addAmount, totalAmount // to operate tokenInfos instead of changing it directly. mapping(address => AccountTokenLib.TokenInfo) tokenInfos; uint128 depositBitmap; uint128 borrowBitmap; } /** * Initialize the Accounts * @param _globalConfig the global configuration contract */ function initialize( IGlobalConfig _globalConfig ) public initializer { globalConfig = _globalConfig; } /** * Check if the user has deposit for any tokens * @param _account address of the user * @return true if the user has positive deposit balance */ function isUserHasAnyDeposits(address _account) public view returns (bool) { Account storage account = accounts[_account]; return account.depositBitmap > 0; } /** * Check if the user has deposit for a token * @param _account address of the user * @param _index index of the token * @return true if the user has positive deposit balance for the token */ function isUserHasDeposits(address _account, uint8 _index) public view returns (bool) { Account storage account = accounts[_account]; return account.depositBitmap.isBitSet(_index); } /** * Check if the user has borrowed a token * @param _account address of the user * @param _index index of the token * @return true if the user has borrowed the token */ function isUserHasBorrows(address _account, uint8 _index) public view returns (bool) { Account storage account = accounts[_account]; return account.borrowBitmap.isBitSet(_index); } /** * Set the deposit bitmap for a token. * @param _account address of the user * @param _index index of the token */ function setInDepositBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.depositBitmap = account.depositBitmap.setBit(_index); } /** * Unset the deposit bitmap for a token * @param _account address of the user * @param _index index of the token */ function unsetFromDepositBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.depositBitmap = account.depositBitmap.unsetBit(_index); } /** * Set the borrow bitmap for a token. * @param _account address of the user * @param _index index of the token */ function setInBorrowBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.borrowBitmap = account.borrowBitmap.setBit(_index); } /** * Unset the borrow bitmap for a token * @param _account address of the user * @param _index index of the token */ function unsetFromBorrowBitmap(address _account, uint8 _index) internal { Account storage account = accounts[_account]; account.borrowBitmap = account.borrowBitmap.unsetBit(_index); } function getDepositPrincipal(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getDepositPrincipal(); } function getBorrowPrincipal(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getBorrowPrincipal(); } function getLastDepositBlock(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getLastDepositBlock(); } function getLastBorrowBlock(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; return tokenInfo.getLastBorrowBlock(); } /** * Get deposit interest of an account for a specific token * @param _account account address * @param _token token address * @dev The deposit interest may not have been updated in AccountTokenLib, so we need to explicited calcuate it. */ function getDepositInterest(address _account, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[_token]; // If the account has never deposited the token, return 0. if (tokenInfo.getLastDepositBlock() == 0) return 0; else { // As the last deposit block exists, the block is also a check point on index curve. uint256 accruedRate = IBank(globalConfig.bank()).getDepositAccruedRate(_token, tokenInfo.getLastDepositBlock()); return tokenInfo.calculateDepositInterest(accruedRate); } } function getBorrowInterest(address _accountAddr, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; // If the account has never borrowed the token, return 0 if (tokenInfo.getLastBorrowBlock() == 0) return 0; else { // As the last borrow block exists, the block is also a check point on index curve. uint256 accruedRate = IBank(globalConfig.bank()).getBorrowAccruedRate(_token, tokenInfo.getLastBorrowBlock()); return tokenInfo.calculateBorrowInterest(accruedRate); } } function borrow(address _accountAddr, address _token, uint256 _amount) external onlyAuthorized { require(_amount != 0, "Borrow zero amount of token is not allowed."); require(isUserHasAnyDeposits(_accountAddr), "The user doesn't have any deposits."); (uint8 tokenIndex, uint256 tokenDivisor, uint256 tokenPrice,) = ITokenRegistry(globalConfig.tokenInfoRegistry()).getTokenInfoFromAddress(_token); require( getBorrowETH(_accountAddr).add(_amount.mul(tokenPrice).div(tokenDivisor)) <= getBorrowPower(_accountAddr), "Insufficient collateral when borrow." ); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; if(tokenInfo.getLastBorrowBlock() == 0) tokenInfo.borrow(_amount, INT_UNIT, getBlockNumber()); else { calculateBorrowFIN(tokenInfo.getLastBorrowBlock(), _token, _accountAddr, getBlockNumber()); uint256 accruedRate = IBank(globalConfig.bank()).getBorrowAccruedRate(_token, tokenInfo.getLastBorrowBlock()); // Update the token principla and interest tokenInfo.borrow(_amount, accruedRate, getBlockNumber()); } // Since we have checked that borrow amount is larget than zero. We can set the borrow // map directly without checking the borrow balance. setInBorrowBitmap(_accountAddr, tokenIndex); } /** * Update token info for withdraw. The interest will be withdrawn with higher priority. */ function withdraw(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized returns (uint256) { (, uint256 tokenDivisor, uint256 tokenPrice, uint256 borrowLTV) = ITokenRegistry(globalConfig.tokenInfoRegistry()).getTokenInfoFromAddress(_token); uint256 withdrawETH = _amount.mul(tokenPrice).mul(borrowLTV).div(tokenDivisor).div(100); require(getBorrowETH(_accountAddr) <= getBorrowPower(_accountAddr).sub(withdrawETH), "Insufficient collateral when withdraw."); (uint256 amountAfterCommission, ) = _withdraw(_accountAddr, _token, _amount, true); return amountAfterCommission; } /** * This function is called in liquidation function. There two difference between this function and * the Account.withdraw function: 1) It doesn't check the user's borrow power, because the user * is already borrowed more than it's borrowing power. 2) It doesn't take commissions. */ function withdraw_liquidate(address _accountAddr, address _token, uint256 _amount) internal { _withdraw(_accountAddr, _token, _amount, false); } function _withdraw(address _accountAddr, address _token, uint256 _amount, bool _isCommission) internal returns (uint256, uint256) { // Check if withdraw amount is less than user's balance require(_amount <= getDepositBalanceCurrent(_token, _accountAddr), "Insufficient balance."); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; uint256 lastBlock = tokenInfo.getLastDepositBlock(); uint256 currentBlock = getBlockNumber(); calculateDepositFIN(lastBlock, _token, _accountAddr, currentBlock); uint256 principalBeforeWithdraw = tokenInfo.getDepositPrincipal(); if (tokenInfo.getLastDepositBlock() == 0) tokenInfo.withdraw(_amount, INT_UNIT, getBlockNumber()); else { // As the last deposit block exists, the block is also a check point on index curve. uint256 accruedRate = IBank(globalConfig.bank()).getDepositAccruedRate(_token, tokenInfo.getLastDepositBlock()); tokenInfo.withdraw(_amount, accruedRate, getBlockNumber()); } uint256 principalAfterWithdraw = tokenInfo.getDepositPrincipal(); if(tokenInfo.getDepositPrincipal() == 0) { uint8 tokenIndex = ITokenRegistry(globalConfig.tokenInfoRegistry()).getTokenIndex(_token); unsetFromDepositBitmap(_accountAddr, tokenIndex); } uint256 commission = 0; if (_isCommission && _accountAddr != globalConfig.deFinerCommunityFund()) { // DeFiner takes 10% commission on the interest a user earn commission = _amount.sub(principalBeforeWithdraw.sub(principalAfterWithdraw)).mul(globalConfig.deFinerRate()).div(100); deposit(globalConfig.deFinerCommunityFund(), _token, commission); _amount = _amount.sub(commission); } return (_amount, commission); } /** * Update token info for deposit */ function deposit(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; if(tokenInfo.getDepositPrincipal() == 0) { uint8 tokenIndex = ITokenRegistry(globalConfig.tokenInfoRegistry()).getTokenIndex(_token); setInDepositBitmap(_accountAddr, tokenIndex); } if(tokenInfo.getLastDepositBlock() == 0) tokenInfo.deposit(_amount, INT_UNIT, getBlockNumber()); else { calculateDepositFIN(tokenInfo.getLastDepositBlock(), _token, _accountAddr, getBlockNumber()); uint256 accruedRate = IBank(globalConfig.bank()).getDepositAccruedRate(_token, tokenInfo.getLastDepositBlock()); tokenInfo.deposit(_amount, accruedRate, getBlockNumber()); } } function repay(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized returns(uint256){ // Update tokenInfo uint256 amountOwedWithInterest = getBorrowBalanceCurrent(_token, _accountAddr); uint256 amount = _amount > amountOwedWithInterest ? amountOwedWithInterest : _amount; uint256 remain = _amount > amountOwedWithInterest ? _amount.sub(amountOwedWithInterest) : 0; AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; // Sanity check require(tokenInfo.getBorrowPrincipal() > 0, "Token BorrowPrincipal must be greater than 0. To deposit balance, please use deposit button."); if(tokenInfo.getLastBorrowBlock() == 0) tokenInfo.repay(amount, INT_UNIT, getBlockNumber()); else { calculateBorrowFIN(tokenInfo.getLastBorrowBlock(), _token, _accountAddr, getBlockNumber()); uint256 accruedRate = IBank(globalConfig.bank()).getBorrowAccruedRate(_token, tokenInfo.getLastBorrowBlock()); tokenInfo.repay(amount, accruedRate, getBlockNumber()); } if(tokenInfo.getBorrowPrincipal() == 0) { uint8 tokenIndex = ITokenRegistry(globalConfig.tokenInfoRegistry()).getTokenIndex(_token); unsetFromBorrowBitmap(_accountAddr, tokenIndex); } return remain; } function getDepositBalanceCurrent( address _token, address _accountAddr ) public view returns (uint256 depositBalance) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; IBank bank = IBank(globalConfig.bank()); uint256 accruedRate; if(tokenInfo.getDepositPrincipal() == 0) { return 0; } else { if(bank.depositRateIndex(_token, tokenInfo.getLastDepositBlock()) == 0) { accruedRate = INT_UNIT; } else { accruedRate = bank.depositRateIndexNow(_token) .mul(INT_UNIT) .div(bank.depositRateIndex(_token, tokenInfo.getLastDepositBlock())); } return tokenInfo.getDepositBalance(accruedRate); } } /** * Get current borrow balance of a token * @param _token token address * @dev This is an estimation. Add a new checkpoint first, if you want to derive the exact balance. */ function getBorrowBalanceCurrent( address _token, address _accountAddr ) public view returns (uint256 borrowBalance) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; IBank bank = IBank(globalConfig.bank()); uint256 accruedRate; if(tokenInfo.getBorrowPrincipal() == 0) { return 0; } else { if(bank.borrowRateIndex(_token, tokenInfo.getLastBorrowBlock()) == 0) { accruedRate = INT_UNIT; } else { accruedRate = bank.borrowRateIndexNow(_token) .mul(INT_UNIT) .div(bank.borrowRateIndex(_token, tokenInfo.getLastBorrowBlock())); } return tokenInfo.getBorrowBalance(accruedRate); } } /** * Calculate an account's borrow power based on token's LTV */ function getBorrowPower(address _borrower) public view returns (uint256 power) { ITokenRegistry tokenRegistry = ITokenRegistry(globalConfig.tokenInfoRegistry()); uint256 tokenNum = tokenRegistry.getCoinLength(); for(uint256 i = 0; i < tokenNum; i++) { if (isUserHasDeposits(_borrower, uint8(i))) { (address token, uint256 divisor, uint256 price, uint256 borrowLTV) = tokenRegistry.getTokenInfoFromIndex(i); uint256 depositBalanceCurrent = getDepositBalanceCurrent(token, _borrower); power = power.add(depositBalanceCurrent.mul(price).mul(borrowLTV).div(100).div(divisor)); } } return power; } /** * Get current deposit balance of a token * @dev This is an estimation. Add a new checkpoint first, if you want to derive the exact balance. */ function getDepositETH( address _accountAddr ) public view returns (uint256 depositETH) { ITokenRegistry tokenRegistry = ITokenRegistry(globalConfig.tokenInfoRegistry()); uint256 tokenNum = tokenRegistry.getCoinLength(); for(uint256 i = 0; i < tokenNum; i++) { if(isUserHasDeposits(_accountAddr, uint8(i))) { (address token, uint256 divisor, uint256 price, ) = tokenRegistry.getTokenInfoFromIndex(i); uint256 depositBalanceCurrent = getDepositBalanceCurrent(token, _accountAddr); depositETH = depositETH.add(depositBalanceCurrent.mul(price).div(divisor)); } } return depositETH; } /** * Get borrowed balance of a token in the uint256 of Wei */ function getBorrowETH( address _accountAddr ) public view returns (uint256 borrowETH) { ITokenRegistry tokenRegistry = ITokenRegistry(globalConfig.tokenInfoRegistry()); uint256 tokenNum = tokenRegistry.getCoinLength(); for(uint256 i = 0; i < tokenNum; i++) { if(isUserHasBorrows(_accountAddr, uint8(i))) { (address token, uint256 divisor, uint256 price, ) = tokenRegistry.getTokenInfoFromIndex(i); uint256 borrowBalanceCurrent = getBorrowBalanceCurrent(token, _accountAddr); borrowETH = borrowETH.add(borrowBalanceCurrent.mul(price).div(divisor)); } } return borrowETH; } /** * Check if the account is liquidatable * @param _borrower borrower's account * @return true if the account is liquidatable */ function isAccountLiquidatable(address _borrower) public returns (bool) { ITokenRegistry tokenRegistry = ITokenRegistry(globalConfig.tokenInfoRegistry()); IBank bank = IBank(globalConfig.bank()); // Add new rate check points for all the collateral tokens from borrower in order to // have accurate calculation of liquidation oppotunites. uint256 tokenNum = tokenRegistry.getCoinLength(); for(uint8 i = 0; i < tokenNum; i++) { if (isUserHasDeposits(_borrower, i) || isUserHasBorrows(_borrower, i)) { address token = tokenRegistry.addressFromIndex(i); bank.newRateIndexCheckpoint(token); } } uint256 liquidationThreshold = globalConfig.liquidationThreshold(); uint256 liquidationDiscountRatio = globalConfig.liquidationDiscountRatio(); uint256 totalBorrow = getBorrowETH(_borrower); uint256 totalCollateral = getDepositETH(_borrower); // It is required that LTV is larger than LIQUIDATE_THREADHOLD for liquidation // return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold); return totalBorrow.mul(100) > totalCollateral.mul(liquidationThreshold) && totalBorrow.mul(100) <= totalCollateral.mul(liquidationDiscountRatio); } struct LiquidationVars { uint256 borrowerCollateralValue; uint256 targetTokenBalance; uint256 targetTokenBalanceBorrowed; uint256 targetTokenPrice; uint256 liquidationDiscountRatio; uint256 totalBorrow; uint256 borrowPower; uint256 liquidateTokenBalance; uint256 liquidateTokenPrice; uint256 limitRepaymentValue; uint256 borrowTokenLTV; uint256 repayAmount; uint256 payAmount; } function liquidate( address _liquidator, address _borrower, address _borrowedToken, address _collateralToken ) external onlyAuthorized returns ( uint256, uint256 ) { require(isAccountLiquidatable(_borrower), "The borrower is not liquidatable."); // It is required that the liquidator doesn't exceed it's borrow power. require( getBorrowETH(_liquidator) < getBorrowPower(_liquidator), "No extra funds are used for liquidation." ); LiquidationVars memory vars; ITokenRegistry tokenRegistry = ITokenRegistry(globalConfig.tokenInfoRegistry()); // _borrowedToken balance of the liquidator (deposit balance) vars.targetTokenBalance = getDepositBalanceCurrent(_borrowedToken, _liquidator); require(vars.targetTokenBalance > 0, "The account amount must be greater than zero."); // _borrowedToken balance of the borrower (borrow balance) vars.targetTokenBalanceBorrowed = getBorrowBalanceCurrent(_borrowedToken, _borrower); require(vars.targetTokenBalanceBorrowed > 0, "The borrower doesn't own any debt token specified by the liquidator."); // _borrowedToken available for liquidation uint256 borrowedTokenAmountForLiquidation = vars.targetTokenBalance.min(vars.targetTokenBalanceBorrowed); // _collateralToken balance of the borrower (deposit balance) vars.liquidateTokenBalance = getDepositBalanceCurrent(_collateralToken, _borrower); vars.liquidateTokenPrice = tokenRegistry.priceFromAddress(_collateralToken); uint256 divisor = 10 ** uint256(tokenRegistry.getTokenDecimals(_borrowedToken)); uint256 liquidateTokendivisor = 10 ** uint256(tokenRegistry.getTokenDecimals(_collateralToken)); // _collateralToken to purchase so that borrower's balance matches its borrow power vars.totalBorrow = getBorrowETH(_borrower); vars.borrowPower = getBorrowPower(_borrower); vars.liquidationDiscountRatio = globalConfig.liquidationDiscountRatio(); vars.borrowTokenLTV = tokenRegistry.getBorrowLTV(_borrowedToken); vars.limitRepaymentValue = vars.totalBorrow.sub(vars.borrowPower).mul(100).div(vars.liquidationDiscountRatio.sub(vars.borrowTokenLTV)); uint256 collateralTokenValueForLiquidation = vars.limitRepaymentValue.min(vars.liquidateTokenBalance.mul(vars.liquidateTokenPrice).div(liquidateTokendivisor)); vars.targetTokenPrice = tokenRegistry.priceFromAddress(_borrowedToken); uint256 liquidationValue = collateralTokenValueForLiquidation.min(borrowedTokenAmountForLiquidation.mul(vars.targetTokenPrice).mul(100).div(divisor).div(vars.liquidationDiscountRatio)); vars.repayAmount = liquidationValue.mul(vars.liquidationDiscountRatio).mul(divisor).div(100).div(vars.targetTokenPrice); vars.payAmount = vars.repayAmount.mul(liquidateTokendivisor).mul(100).mul(vars.targetTokenPrice); vars.payAmount = vars.payAmount.div(divisor).div(vars.liquidationDiscountRatio).div(vars.liquidateTokenPrice); deposit(_liquidator, _collateralToken, vars.payAmount); withdraw_liquidate(_liquidator, _borrowedToken, vars.repayAmount); withdraw_liquidate(_borrower, _collateralToken, vars.payAmount); repay(_borrower, _borrowedToken, vars.repayAmount); return (vars.repayAmount, vars.payAmount); } /** * Get current block number * @return the current block number */ function getBlockNumber() private view returns (uint256) { return block.number; } /** * An account claim all mined FIN token. * @dev If the FIN mining index point doesn't exist, we have to calculate the FIN amount * accurately. So the user can withdraw all available FIN tokens. */ function claim(address _account) public onlyAuthorized returns(uint256){ ITokenRegistry tokenRegistry = ITokenRegistry(globalConfig.tokenInfoRegistry()); IBank bank = IBank(globalConfig.bank()); uint256 coinLength = tokenRegistry.getCoinLength(); for(uint8 i = 0; i < coinLength; i++) { if (isUserHasDeposits(_account, i) || isUserHasBorrows(_account, i)) { address token = tokenRegistry.addressFromIndex(i); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[token]; uint256 currentBlock = getBlockNumber(); bank.updateMining(token); if (isUserHasDeposits(_account, i)) { bank.updateDepositFINIndex(token); uint256 accruedRate = bank.getDepositAccruedRate(token, tokenInfo.getLastDepositBlock()); calculateDepositFIN(tokenInfo.getLastDepositBlock(), token, _account, currentBlock); tokenInfo.deposit(0, accruedRate, currentBlock); } if (isUserHasBorrows(_account, i)) { bank.updateBorrowFINIndex(token); uint256 accruedRate = bank.getBorrowAccruedRate(token, tokenInfo.getLastBorrowBlock()); calculateBorrowFIN(tokenInfo.getLastBorrowBlock(), token, _account, currentBlock); tokenInfo.borrow(0, accruedRate, currentBlock); } } } uint256 _FINAmount = FINAmount[_account]; FINAmount[_account] = 0; return _FINAmount; } /** * Accumulate the amount FIN mined by depositing between _lastBlock and _currentBlock */ function calculateDepositFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal { IBank bank = IBank(globalConfig.bank()); uint256 indexDifference = bank.depositFINRateIndex(_token, _currentBlock) .sub(bank.depositFINRateIndex(_token, _lastBlock)); uint256 getFIN = getDepositBalanceCurrent(_token, _accountAddr) .mul(indexDifference) .div(bank.depositRateIndex(_token, _currentBlock)); FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN); } /** * Accumulate the amount FIN mined by borrowing between _lastBlock and _currentBlock */ function calculateBorrowFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal { IBank bank = IBank(globalConfig.bank()); uint256 indexDifference = bank.borrowFINRateIndex(_token, _currentBlock) .sub(bank.borrowFINRateIndex(_token, _lastBlock)); uint256 getFIN = getBorrowBalanceCurrent(_token, _accountAddr) .mul(indexDifference) .div(bank.borrowRateIndex(_token, _currentBlock)); FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN); } } interface IGlobalConfig { function constants() external view returns (address); function tokenInfoRegistry() external view returns (address); function chainLink() external view returns (address); function bank() external view returns (address); function savingAccount() external view returns (address); function accounts() external view returns (address); function maxReserveRatio() external view returns (uint256); function midReserveRatio() external view returns (uint256); function minReserveRatio() external view returns (uint256); function rateCurveSlope() external view returns (uint256); function rateCurveConstant() external view returns (uint256); function compoundSupplyRateWeights() external view returns (uint256); function compoundBorrowRateWeights() external view returns (uint256); function deFinerCommunityFund() external view returns (address); function deFinerRate() external view returns (uint256); function liquidationThreshold() external view returns (uint256); function liquidationDiscountRatio() external view returns (uint256); } interface ITokenRegistry { function getTokenDecimals(address) external view returns (uint8); function getCToken(address) external view returns (address); function depositeMiningSpeeds(address) external view returns (uint); function borrowMiningSpeeds(address) external view returns (uint); function isSupportedOnCompound(address) external view returns (bool); function getTokenInfoFromIndex(uint) external view returns (address, uint, uint, uint); function getTokenInfoFromAddress(address) external view returns (uint8 ,uint ,uint ,uint); function getTokenIndex(address) external view returns (uint8); function getCoinLength() external view returns (uint); function priceFromAddress(address) external view returns(uint); function getBorrowLTV(address) external view returns (uint); function addressFromIndex(uint) external view returns (address); } interface IAccount { function deposit(address, address, uint256) external; function borrow(address, address, uint256) external; function getBorrowPrincipal(address, address) external view returns (uint256); function withdraw(address, address, uint256) external returns (uint256); function repay(address, address, uint256) external returns (uint256); } interface ISavingAccount { function toCompound(address, uint256) external; function fromCompound(address, uint256) external; } interface IBank { function depositRateIndex(address, uint) external view returns (uint); function borrowRateIndex(address, uint) external view returns (uint); function depositRateIndexNow(address) external view returns (uint); function borrowRateIndexNow(address) external view returns (uint); function newRateIndexCheckpoint(address) external; function updateMining(address) external; function updateDepositFINIndex(address) external; function updateBorrowFINIndex(address) external; function getDepositAccruedRate(address, uint) external view returns (uint); function getBorrowAccruedRate(address, uint) external view returns (uint); function depositFINRateIndex(address, uint) external view returns (uint); function borrowFINRateIndex(address, uint) external view returns (uint); }
* Accumulate the amount FIN mined by depositing between _lastBlock and _currentBlock/
function calculateDepositFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal { IBank bank = IBank(globalConfig.bank()); uint256 indexDifference = bank.depositFINRateIndex(_token, _currentBlock) .sub(bank.depositFINRateIndex(_token, _lastBlock)); uint256 getFIN = getDepositBalanceCurrent(_token, _accountAddr) .mul(indexDifference) .div(bank.depositRateIndex(_token, _currentBlock)); FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN); }
595,930
[ 1, 8973, 31284, 326, 3844, 17563, 1131, 329, 635, 443, 1724, 310, 3086, 389, 2722, 1768, 471, 389, 2972, 1768, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 4604, 758, 1724, 7263, 12, 11890, 5034, 389, 2722, 1768, 16, 1758, 389, 2316, 16, 1758, 389, 4631, 3178, 16, 2254, 5034, 389, 2972, 1768, 13, 2713, 288, 203, 3639, 467, 16040, 11218, 273, 467, 16040, 12, 6347, 809, 18, 10546, 10663, 203, 203, 3639, 2254, 5034, 770, 16220, 273, 11218, 18, 323, 1724, 7263, 4727, 1016, 24899, 2316, 16, 389, 2972, 1768, 13, 203, 27573, 263, 1717, 12, 10546, 18, 323, 1724, 7263, 4727, 1016, 24899, 2316, 16, 389, 2722, 1768, 10019, 203, 3639, 2254, 5034, 2812, 706, 273, 336, 758, 1724, 13937, 3935, 24899, 2316, 16, 389, 4631, 3178, 13, 203, 13491, 263, 16411, 12, 1615, 16220, 13, 203, 13491, 263, 2892, 12, 10546, 18, 323, 1724, 4727, 1016, 24899, 2316, 16, 389, 2972, 1768, 10019, 203, 3639, 17563, 6275, 63, 67, 4631, 3178, 65, 273, 17563, 6275, 63, 67, 4631, 3178, 8009, 1289, 12, 588, 7263, 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 ]
./partial_match/44787/0x926E88a280902Bfff5047693B9CeAfdb9F4d5095/sources/Users/carter/git/clabs/celo-monorepo/packages/protocol/contracts/identity/FederatedAttestations.sol
* @notice Registers an attestation directly from the issuer @param identifier Hash of the identifier to be attested @param account Address of the account being mapped to the identifier @param issuedOn Time at which the issuer issued the attestation in Unix time @dev Attestation signer and issuer in storage is set to msg.sender @dev Throws if an attestation with the same (identifier, issuer, account) already exists/
function registerAttestationAsIssuer(bytes32 identifier, address account, uint64 issuedOn) external { _registerAttestation(identifier, msg.sender, account, msg.sender, issuedOn); }
16,956,668
[ 1, 10277, 392, 2403, 395, 367, 5122, 628, 326, 9715, 225, 2756, 2474, 434, 326, 2756, 358, 506, 2403, 3149, 225, 2236, 5267, 434, 326, 2236, 3832, 5525, 358, 326, 2756, 225, 16865, 1398, 2647, 622, 1492, 326, 9715, 16865, 326, 2403, 395, 367, 316, 9480, 813, 225, 6020, 395, 367, 10363, 471, 9715, 316, 2502, 353, 444, 358, 1234, 18, 15330, 225, 22435, 309, 392, 2403, 395, 367, 598, 326, 1967, 261, 5644, 16, 9715, 16, 2236, 13, 1818, 1704, 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, 445, 1744, 3075, 395, 367, 1463, 16667, 12, 3890, 1578, 2756, 16, 1758, 2236, 16, 2254, 1105, 16865, 1398, 13, 203, 565, 3903, 203, 225, 288, 203, 565, 389, 4861, 3075, 395, 367, 12, 5644, 16, 1234, 18, 15330, 16, 2236, 16, 1234, 18, 15330, 16, 16865, 1398, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "../SimpleReadAccessController.sol"; import "../interfaces/AccessControllerInterface.sol"; import "../interfaces/TypeAndVersionInterface.sol"; /* dev dependencies - to be re/moved after audit */ import "./interfaces/FlagsInterface.sol"; /** * @title The Flags contract * @notice Allows flags to signal to any reader on the access control list. * The owner can set flags, or designate other addresses to set flags. * Raise flag actions are controlled by its own access controller. * Lower flag actions are controlled by its own access controller. * An expected pattern is to allow addresses to raise flags on themselves, so if you are subscribing to * FlagOn events you should filter for addresses you care about. */ contract Flags is TypeAndVersionInterface, FlagsInterface, SimpleReadAccessController { AccessControllerInterface public raisingAccessController; AccessControllerInterface public loweringAccessController; mapping(address => bool) private flags; event FlagRaised( address indexed subject ); event FlagLowered( address indexed subject ); event RaisingAccessControllerUpdated( address indexed previous, address indexed current ); event LoweringAccessControllerUpdated( address indexed previous, address indexed current ); /** * @param racAddress address for the raising access controller. * @param lacAddress address for the lowering access controller. */ constructor( address racAddress, address lacAddress ) { setRaisingAccessController(racAddress); setLoweringAccessController(lacAddress); } /** * @notice versions: * * - Flags 1.1.0: upgraded to solc 0.8, added lowering access controller * - Flags 1.0.0: initial release * * @inheritdoc TypeAndVersionInterface */ function typeAndVersion() external pure virtual override returns ( string memory ) { return "Flags 1.1.0"; } /** * @notice read the warning flag status of a contract address. * @param subject The contract address being checked for a flag. * @return A true value indicates that a flag was raised and a * false value indicates that no flag was raised. */ function getFlag( address subject ) external view override checkAccess() returns (bool) { return flags[subject]; } /** * @notice read the warning flag status of a contract address. * @param subjects An array of addresses being checked for a flag. * @return An array of bools where a true value for any flag indicates that * a flag was raised and a false value indicates that no flag was raised. */ function getFlags( address[] calldata subjects ) external view override checkAccess() returns (bool[] memory) { bool[] memory responses = new bool[](subjects.length); for (uint256 i = 0; i < subjects.length; i++) { responses[i] = flags[subjects[i]]; } return responses; } /** * @notice enable the warning flag for an address. * Access is controlled by raisingAccessController, except for owner * who always has access. * @param subject The contract address whose flag is being raised */ function raiseFlag( address subject ) external override { require(_allowedToRaiseFlags(), "Not allowed to raise flags"); _tryToRaiseFlag(subject); } /** * @notice enable the warning flags for multiple addresses. * Access is controlled by raisingAccessController, except for owner * who always has access. * @param subjects List of the contract addresses whose flag is being raised */ function raiseFlags( address[] calldata subjects ) external override { require(_allowedToRaiseFlags(), "Not allowed to raise flags"); for (uint256 i = 0; i < subjects.length; i++) { _tryToRaiseFlag(subjects[i]); } } /** * @notice allows owner to disable the warning flags for an addresses. * Access is controlled by loweringAccessController, except for owner * who always has access. * @param subject The contract address whose flag is being lowered */ function lowerFlag( address subject ) external override { require(_allowedToLowerFlags(), "Not allowed to lower flags"); _tryToLowerFlag(subject); } /** * @notice allows owner to disable the warning flags for multiple addresses. * Access is controlled by loweringAccessController, except for owner * who always has access. * @param subjects List of the contract addresses whose flag is being lowered */ function lowerFlags( address[] calldata subjects ) external override { require(_allowedToLowerFlags(), "Not allowed to lower flags"); for (uint256 i = 0; i < subjects.length; i++) { address subject = subjects[i]; _tryToLowerFlag(subject); } } /** * @notice allows owner to change the access controller for raising flags. * @param racAddress new address for the raising access controller. */ function setRaisingAccessController( address racAddress ) public override onlyOwner() { address previous = address(raisingAccessController); if (previous != racAddress) { raisingAccessController = AccessControllerInterface(racAddress); emit RaisingAccessControllerUpdated(previous, racAddress); } } function setLoweringAccessController( address lacAddress ) public override onlyOwner() { address previous = address(loweringAccessController); if (previous != lacAddress) { loweringAccessController = AccessControllerInterface(lacAddress); emit LoweringAccessControllerUpdated(previous, lacAddress); } } // PRIVATE function _allowedToRaiseFlags() private view returns (bool) { return msg.sender == owner() || raisingAccessController.hasAccess(msg.sender, msg.data); } function _allowedToLowerFlags() private view returns (bool) { return msg.sender == owner() || loweringAccessController.hasAccess(msg.sender, msg.data); } function _tryToRaiseFlag( address subject ) private { if (!flags[subject]) { flags[subject] = true; emit FlagRaised(subject); } } function _tryToLowerFlag( address subject ) private { if (flags[subject]) { flags[subject] = false; emit FlagLowered(subject); } } }
* @notice allows owner to disable the warning flags for an addresses. Access is controlled by loweringAccessController, except for owner who always has access. @param subject The contract address whose flag is being lowered/
function lowerFlag( address subject ) external override { require(_allowedToLowerFlags(), "Not allowed to lower flags"); _tryToLowerFlag(subject); }
5,471,131
[ 1, 5965, 87, 3410, 358, 4056, 326, 3436, 2943, 364, 392, 6138, 18, 5016, 353, 25934, 635, 2612, 310, 1862, 2933, 16, 1335, 364, 3410, 10354, 3712, 711, 2006, 18, 225, 3221, 1021, 6835, 1758, 8272, 2982, 353, 3832, 2612, 329, 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, 225, 445, 2612, 4678, 12, 203, 565, 1758, 3221, 203, 225, 262, 203, 565, 3903, 203, 565, 3849, 203, 225, 288, 203, 565, 2583, 24899, 8151, 774, 4070, 5094, 9334, 315, 1248, 2935, 358, 2612, 2943, 8863, 203, 203, 565, 389, 698, 774, 4070, 4678, 12, 7857, 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 ]
pragma solidity ^0.4.22; import "./IDaoBase.sol"; import "./DaoStorage.sol"; import "./DaoBaseLib.sol"; /** * @title DaoBase * @dev Main Thetta DAO Framework contract. * Usage scenarios: * 1) Preferred: become its client (derive your contract from DaoClient contract!) * 2) Optional: derive a contract directly from DaoBase * */ contract DaoBase is IDaoBase, Ownable { event DaoBaseUpgradeDaoContract(address _new); event DaoBaseAddGroupMember(string _groupName, address _a); event DaoBaseRemoveGroupMember(string _groupName, address _a); event DaoBaseAllowActionByShareholder(bytes32 _what, address _tokenAddress); event DaoBaseAllowActionByVoting(bytes32 _what, address _tokenAddress); event DaoBaseAllowActionByAddress(bytes32 _what, address _a); event DaoBaseAllowActionByAnyMemberOfGroup(bytes32 _what, string _groupName); event DaoBaseAddNewProposal(address _proposal); event DaoBaseIssueTokens(address _tokenAddress, address _to, uint _amount); event DaoBaseBurnTokens(address _tokenAddress, address _who, uint _amount); DaoStorage daoStorage; modifier isCanDo(bytes32 _permissionName){ require(DaoBaseLib.isCanDoAction(daoStorage, msg.sender, _permissionName)); _; } modifier isCanDoOrByOwner(bytes32 _what) { require(msg.sender==owner || DaoBaseLib.isCanDoAction(daoStorage, msg.sender, _what)); _; } bytes32 public constant ISSUE_TOKENS = 0xe003bf3bc29ae37598e0a6b52d6c5d94b0a53e4e52ae40c01a29cdd0e7816b71; bytes32 public constant MANAGE_GROUPS = 0x060990aad7751fab616bf14cf6b68ac4c5cdc555f8f06bc9f15ba1b156e81b0b; bytes32 public constant ADD_NEW_PROPOSAL = 0x55c7fa9eebcea37770fd33ec28acf7eacb6ea53052a9e9bc0a98169768578c5f; bytes32 public constant BURN_TOKENS = 0x324cd2c359ecbc6ad92db8d027aab5d643f27c3055619a49702576797bb41fe5; bytes32 public constant UPGRADE_DAO_CONTRACT = 0x3794eb44dffe1fc69d141df1b355cf30d543d8006634dd7a125d0e5f500b7fb1; bytes32 public constant REMOVE_GROUP_MEMBER = 0x3a5165e670fb3632ad283cd3622bfca48f4c8202b504a023dafe70df30567075; bytes32 public constant WITHDRAW_DONATIONS = 0xfc685f51f68cb86aa29db19c2a8f4e85183375ba55b5e56fb2e89adc5f5e4285; bytes32 public constant ALLOW_ACTION_BY_SHAREHOLDER = 0xbeaac974e61895532ee7d8efc953d378116d446667765b57f62c791c37b03c8d; bytes32 public constant ALLOW_ACTION_BY_VOTING = 0x2e0b85549a7529dfca5fb20621fe76f393d05d7fc99be4dd3d996c8e1925ba0b; bytes32 public constant ALLOW_ACTION_BY_ADDRESS = 0x087dfe531c937a5cbe06c1240d8f791b240719b90fd2a4e453a201ce0f00c176; bytes32 public constant ALLOW_ACTION_BY_ANY_MEMBER_OF_GROUP = 0xa7889b6adda0a2270859e5c6327f82b987d24f5729de85a5746ce28eed9e0d07; constructor(DaoStorage _daoStorage) public { daoStorage = _daoStorage; } /** * @param _s String which will be converted to hash * @return hash of provided string * @dev Hash string */ function stringHash(string _s) public pure returns(bytes32) { return keccak256(_s); } /** * @return observers amount in storage */ function getObserversCount() public view returns(uint) { return daoStorage.getObserversCount(); } /** * @param _index observer index in storage * @return address of the observer with provided index */ function getObserverAtIndex(uint _index) public view returns(address) { return daoStorage.getObserverAtIndex(_index); } /** * @param _permissionName permission name in hash * @param _a address which will be checked for permissions * @return true if _a address have _permissionName permissions */ function isCanDoByGroupMember(bytes32 _permissionName, address _a) public view returns(bool) { return daoStorage.isAllowedActionByMembership(_permissionName, _a); } /** * @param _observer observer address * @dev add observer to storage */ function addObserver(IDaoObserver _observer) public { daoStorage.addObserver(_observer); } /** * @notice This function should be called only by account with UPGRADE_DAO_CONTRACT permissions * @param _new new DaoBase instance (address) * @dev this function upgrades DAO instance */ function upgradeDaoContract(IDaoBase _new) public isCanDo(UPGRADE_DAO_CONTRACT) { emit DaoBaseUpgradeDaoContract(_new); // call observers.onUpgrade() for all observers for(uint i=0; i<daoStorage.getObserversCount(); ++i) { IDaoObserver(daoStorage.getObserverAtIndex(i)).onUpgrade(_new); } daoStorage.transferOwnership(_new); for(i=0; i<daoStorage.getTokensCount(); ++i) { // transfer ownership of all tokens (this -> _new) daoStorage.getTokenAtIndex(i).transferOwnership(_new); } } /** * @param _groupName name of the group in storage * @return amount of the members of the group with name _groupName */ function getMembersCount(string _groupName) public view returns(uint) { return daoStorage.getMembersCount(stringHash(_groupName)); } /** * @notice This function should be called only by account with MANAGE_GROUPS permissions * @param _groupName name of the group in storage * @param _a address which will be added to the group with name _groupName * @dev this function add address _a to group na me with name _groupName into storage */ function addGroupMember(string _groupName, address _a) public isCanDoOrByOwner(MANAGE_GROUPS) { emit DaoBaseAddGroupMember(_groupName, _a); require(bytes(_groupName).length>0); daoStorage.addGroupMember(stringHash(_groupName), _a); } /** * @param _groupName name of the group in storage * @return array of addresses which in group name with name _groupName */ function getGroupMembers(string _groupName) public view returns(address[]) { return daoStorage.getGroupMembers(stringHash(_groupName)); } /** * @notice This function should be called only by account with MANAGE_GROUPS permissions * @param _groupName name of the group in storage * @param _a address which will be removed from the group with name _groupName * @dev this function remove address _a from group name with name _groupName in storage */ function removeGroupMember(string _groupName, address _a) public isCanDoOrByOwner(MANAGE_GROUPS) { emit DaoBaseRemoveGroupMember(_groupName, _a); daoStorage.removeGroupMember(stringHash(_groupName), _a); } /** * @param _groupName name of the group in storage * @param _a address which will be checked on presence in group with name _groupName * @return true if address _a is in group with name _groupName */ function isGroupMember(string _groupName, address _a) public view returns(bool) { return daoStorage.isGroupMember(stringHash(_groupName), _a); } /** * @param _groupName name of the group in storage * @param _index address which will be added to the group with name _groupName * @return true if address corresponded to _index is group member of group with name _groupName */ function getMemberByIndex(string _groupName, uint _index) public view returns (address) { return daoStorage.getGroupsMemberAtIndex(stringHash(_groupName), _index); } /** * @notice This function should be called only by account with MANAGE_GROUPS permissions * @param _permissionName permission name in hash * @param _tokenAddress address of the token * @dev this function allows action with name _permissionName for _tokenAddress */ function allowActionByShareholder(bytes32 _permissionName, address _tokenAddress) public isCanDoOrByOwner(MANAGE_GROUPS) { emit DaoBaseAllowActionByShareholder(_permissionName, _tokenAddress); daoStorage.allowActionByShareholder(_permissionName, _tokenAddress); } /** * @notice This function should be called only by account with MANAGE_GROUPS permissions * @param _permissionName permission name in hash * @param _tokenAddress address of the token * @dev this function allows action with name _permissionName for _tokenAddress */ function allowActionByVoting(bytes32 _permissionName, address _tokenAddress) public isCanDoOrByOwner(MANAGE_GROUPS) { emit DaoBaseAllowActionByVoting(_permissionName, _tokenAddress); daoStorage.allowActionByVoting(_permissionName,_tokenAddress); } /** * @notice This function should be called only by account with MANAGE_GROUPS permissions * @param _permissionName permission name in hash * @param _a address * @dev this function allows action with name _permissionName for _tokenAddress */ function allowActionByAddress(bytes32 _permissionName, address _a) public isCanDoOrByOwner(MANAGE_GROUPS) { emit DaoBaseAllowActionByAddress(_permissionName, _a); daoStorage.allowActionByAddress(_permissionName,_a); } /** * @notice This function should be called only by account with MANAGE_GROUPS permissions * @param _permissionName permission name in hash * @param _groupName name of the group in storage * @dev this function allows action with name _permissionName for _tokenAddress */ function allowActionByAnyMemberOfGroup(bytes32 _permissionName, string _groupName) public isCanDoOrByOwner(MANAGE_GROUPS) { emit DaoBaseAllowActionByAnyMemberOfGroup(_permissionName, _groupName); daoStorage.allowActionByAnyMemberOfGroup(_permissionName, stringHash(_groupName)); } /** * @dev Function that will check if action is DIRECTLY callable by msg.sender (account or another contract) * How permissions works now: * 1. if caller is in the whitelist -> allow * 2. if caller is in the group and this action can be done by group members -> allow * 3. if caller is shareholder and this action can be done by a shareholder -> allow * 4. if this action requires voting * a. caller is in the majority -> allow * b. caller is voting and it is succeeded -> allow * 4. deny */ function isCanDoAction(address _a, bytes32 _permissionNameHash) public view returns(bool) { return DaoBaseLib.isCanDoAction(daoStorage, _a, _permissionNameHash); } // Proposals: /** * @notice This function should be called only by account with ADD_NEW_PROPOSAL permissions * @param _proposal address of proposal * @dev this function adds proposal to storage */ function addNewProposal(IProposal _proposal) public isCanDo(ADD_NEW_PROPOSAL) { emit DaoBaseAddNewProposal(_proposal); daoStorage.addProposal(_proposal); } /** * @param _i index of the proposal in storage * @return proposal address */ function getProposalAtIndex(uint _i) public view returns(IProposal) { return daoStorage.getProposalAtIndex(_i); } /** * @return proposals amount in storage */ function getProposalsCount() public view returns(uint) { return daoStorage.getProposalsCount(); } // Tokens: /** * @notice This function should be called only by account with ISSUE_TOKENS permissions * @param _tokenAddress address of token * @param _to address who gets issued tokens * @param _amount amount of tokens which will be issued * @dev this function issue tokens for address _to */ function issueTokens(address _tokenAddress, address _to, uint _amount) public isCanDo(ISSUE_TOKENS) { emit DaoBaseIssueTokens(_tokenAddress, _to, _amount); DaoBaseLib.issueTokens( daoStorage, _tokenAddress, _to, _amount ); } /** * @notice This function should be called only by account with BURN_TOKENS permissions * @param _tokenAddress address of token * @param _who address whose tokens will be burned * @param _amount amount of tokens which will be burned * @dev this function burn tokens for address _who */ function burnTokens(address _tokenAddress, address _who, uint _amount) public isCanDo(BURN_TOKENS) { emit DaoBaseBurnTokens(_tokenAddress, _who, _amount); DaoBaseLib.burnTokens( daoStorage, _tokenAddress, _who, _amount ); } }
* @param _observer observer address @dev add observer to storage/
function addObserver(IDaoObserver _observer) public { daoStorage.addObserver(_observer); }
12,852,779
[ 1, 67, 30971, 9655, 1758, 225, 527, 9655, 358, 2502, 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, 202, 915, 527, 11048, 12, 734, 6033, 11048, 389, 30971, 13, 1071, 288, 203, 202, 202, 2414, 83, 3245, 18, 1289, 11048, 24899, 30971, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xdC68Df821103ABAB3495284cB2B7Fb0F8Ddb9B96/sources/shoevault_flat.sol
* Token Price/* Token Size/* Max Purchase Size/* Max amount of token to Gift per time/* Events/* Sale State/* Api/*/
function _beforeTokenTransfer( address from, address to, uint256 tokenId uint256[44] private __gap; } pragma solidity >=0.4.22 <0.9.0; pragma experimental ABIEncoderV2; struct ShoeMeta { uint256 id; }
3,195,623
[ 1, 1345, 20137, 19, 3155, 6321, 19, 4238, 26552, 6321, 19, 4238, 3844, 434, 1147, 358, 611, 2136, 1534, 813, 19, 9043, 19, 348, 5349, 3287, 19, 4458, 759, 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, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 2254, 5034, 63, 6334, 65, 3238, 1001, 14048, 31, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 24, 18, 3787, 411, 20, 18, 29, 18, 20, 31, 203, 683, 9454, 23070, 10336, 45, 7204, 58, 22, 31, 203, 203, 203, 565, 1958, 2638, 15548, 2781, 288, 203, 3639, 2254, 5034, 612, 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 ]
./partial_match/4/0x64fD3aea4Df3b76348a8cC9F2A18930fD6927738/sources/RAYv2.sol
@notice Execute the withraw, this function was made to avoid stack too deep compilation errors. notDeprecated checked in redeem functions, which this is always called from isValidPortfolio(portfolioId) inherently valid when from RoboToken isValidOpportunity(portfolioId, opportunityId) inherently valid when from RoboToken isCorrectAddress(opportunityId, opportunity) fetched from getVerifier Transfers 'amountToRedeem' to the RoboToken which initiated this call. This uses the newly added OM withdraw function that takes advantage of the stored mem. data. This is an internal system contract call that makes calls to external [trusted] contracts.
{ bytes32 opportunityTokenId = roboTokens[roboTokenAddress].opportunityTokens[opportunityId]; IOpportunityManager(IStorage(rayStorage).getContractAddress(OPPORTUNITY_MANAGER_CONTRACT)).withdrawPositionWithMem( opportunityId, opportunityTokenId, opportunity, underlying, roboTokenAddress, amountToRedeem, opportunityNav, isERC20 ); }
8,750,829
[ 1, 5289, 326, 598, 1899, 16, 333, 445, 1703, 7165, 358, 4543, 2110, 4885, 1850, 4608, 8916, 1334, 18, 486, 13534, 225, 5950, 316, 283, 24903, 4186, 16, 1492, 333, 353, 3712, 2566, 628, 4908, 17163, 12, 28962, 548, 13, 225, 316, 1614, 23351, 923, 1347, 628, 19686, 83, 1345, 4908, 3817, 655, 13352, 12, 28962, 548, 16, 1061, 655, 13352, 548, 13, 225, 316, 1614, 23351, 923, 1347, 628, 19686, 83, 1345, 353, 16147, 1887, 12, 556, 655, 13352, 548, 16, 1061, 655, 13352, 13, 225, 12807, 628, 336, 17758, 2604, 18881, 296, 8949, 774, 426, 24903, 11, 358, 326, 19686, 83, 1345, 1492, 27183, 333, 745, 18, 1220, 4692, 326, 10894, 3096, 28839, 598, 9446, 445, 716, 5530, 1261, 7445, 410, 434, 326, 4041, 1663, 18, 501, 18, 1220, 353, 392, 2713, 2619, 6835, 745, 716, 7297, 4097, 358, 3903, 306, 25247, 65, 20092, 18, 2, 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, 1, 1, 1, 1, 1, 0, 0 ]
[ 1, 225, 288, 203, 203, 565, 1731, 1578, 1061, 655, 13352, 1345, 548, 273, 721, 1075, 5157, 63, 303, 1075, 1345, 1887, 8009, 556, 655, 13352, 5157, 63, 556, 655, 13352, 548, 15533, 203, 203, 565, 1665, 84, 655, 13352, 1318, 12, 45, 3245, 12, 435, 3245, 2934, 588, 8924, 1887, 12, 3665, 6354, 2124, 4107, 67, 19402, 67, 6067, 2849, 1268, 13, 2934, 1918, 9446, 2555, 1190, 3545, 12, 203, 1377, 1061, 655, 13352, 548, 16, 203, 1377, 1061, 655, 13352, 1345, 548, 16, 203, 1377, 1061, 655, 13352, 16, 203, 1377, 6808, 16, 203, 1377, 721, 1075, 1345, 1887, 16, 203, 1377, 3844, 774, 426, 24903, 16, 203, 1377, 1061, 655, 13352, 12599, 16, 203, 1377, 353, 654, 39, 3462, 203, 377, 11272, 203, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./TestFramework.sol"; contract TestCrowdfunding { event PrintEvent(string msg); // Adjust this to change the test code's initial balance uint public initialBalance = 100000000 wei; uint256 constant public investorInitialBalance = 10000 wei; MockTimer private timer; Crowdfunding private crowdfunding; FounderCrowdfunding private CrowdfundingCreator; Investor private alice; Investor private bob; //can receive money receive() external payable {} fallback() external payable {} constructor() {} function setupContracts() public { timer = new MockTimer(0); CrowdfundingCreator = new FounderCrowdfunding(); crowdfunding = new Crowdfunding( address(CrowdfundingCreator), timer, 1000 wei, // 1000 wei 10 // at day 10 ); CrowdfundingCreator.setCrowdfunding(crowdfunding); bob = createInvestor(crowdfunding); alice = createInvestor(crowdfunding); } function createInvestor(Crowdfunding _crowdfunding) internal returns (Investor) { Investor investor = new Investor(_crowdfunding); payable(investor).transfer(investorInitialBalance); return investor; } modifier setup { setupContracts(); _; } function testCreateCrowdfundingContracts() public{} // Investments tests function testInvest() public setup { timer.setTime(2); // Still not finished Assert.isTrue(bob.invest(100 wei), "Valid investment should pass."); Assert.isTrue(address(bob).balance == investorInitialBalance - 100 wei, "Investor balance should be reduced by investment value."); Assert.isTrue(crowdfunding.investments(address(bob)) == 100 wei, "All investments should be there"); } function testInvestAfterEnd() public setup { timer.setTime(20); // Finished Assert.isFalse(bob.invest(100 wei), "Investment should not be made after crowdfunding has finished."); Assert.isTrue(address(bob).balance == investorInitialBalance, "Investor should have all of its funds."); } function testInvestMultipleTimes() public setup { bob.invest(100 wei); bob.invest(100 wei); bob.invest(100 wei); Assert.isTrue(address(bob).balance == investorInitialBalance - 300 wei, "Investor should be able to invest multiple times."); Assert.isTrue(crowdfunding.investments(address(bob)) == 300 wei, "All investments should be there"); } // Claim tests function testClaimWhenGoalNotReachedAndNotFinished() public setup { timer.setTime(2); // Still not finished require(bob.invest(100 wei), "Investor must be able to invest"); require(alice.invest(100 wei), "Investor must be able to invest"); Assert.isFalse(CrowdfundingCreator.claimFunds(), "Investments claim should not be able before campaign is active."); Assert.isTrue(address(CrowdfundingCreator).balance == 0, "No investments should be claimed."); } function testClaimWhenGoalNotReachedAndFinished() public setup { // Claim not possible require(bob.invest(100 wei), "Investor must be able to invest"); require(alice.invest(100 wei), "Investor must be able to invest"); timer.setTime(20); // Finished Assert.isFalse(CrowdfundingCreator.claimFunds(), "Can not claim funds when goal not reached."); Assert.isTrue(address(CrowdfundingCreator).balance == 0, "No investments should be claimed."); } function testNonOwnerClaimWhenGoalReachedAndFinished() public setup { // Claim not possible require(bob.invest(500 wei)); require(alice.invest(500 wei)); // Goal Reached timer.setTime(20); // Finished Assert.isFalse(bob.claimFunds(), "Non Owner can not claim funds."); Assert.isTrue(address(bob).balance == investorInitialBalance - 500 wei, "Funds should not be claimed."); Assert.isTrue(address(crowdfunding).balance == 1000 wei, "Funds should not be claimed."); } function testClaimWhenGoalReachedAndNotFinished() public setup { // Claim not possible require(bob.invest(500 wei)); require(alice.invest(500 wei)); // Goal Reached timer.setTime(5); // Finished Assert.isFalse(CrowdfundingCreator.claimFunds(), "Investments claim should not be able before campaign is active."); Assert.isTrue(address(CrowdfundingCreator).balance == 0, "No investments should be claimed."); } function testClaimWhenGoalReachedAndFinished() public setup { // Claim possible require(bob.invest(500 wei)); require(alice.invest(500 wei)); // Goal Reached timer.setTime(20); // Finished Assert.isTrue(CrowdfundingCreator.claimFunds(), "Crowdfunding creator should be able to claim funds."); Assert.isTrue(address(CrowdfundingCreator).balance == 1000, "Funds should be claimed"); Assert.isTrue(address(crowdfunding).balance == 0, "No funds should be a part of crowdfunding after they were claimed."); } // Refund tests function testRefundGoalNotReachedAndNotFinished() public setup { // Refund not possible timer.setTime(2); // Still not finished Assert.isTrue(bob.invest(100 wei), "Investor must be able to invest."); Assert.isFalse(bob.refund(), "Investor should not be able to refund before campaign finish."); Assert.isTrue(address(bob).balance == investorInitialBalance - 100 wei, "Investor shouldn't be able to get refund."); } function testRefundWhenGoalReachedButNotFinished() public setup { // Refund not possible bob.invest(500 wei); alice.invest(500 wei); timer.setTime(5); // Not yet finished Assert.isFalse(bob.refund(), "Investor should not be able to refund before campaign finish and goal reached."); Assert.isTrue(address(bob).balance == investorInitialBalance - 500 wei, "Investor shouldn't be able to get refund."); Assert.isFalse(alice.refund(), "Investor should not be able to refund before campaign finish and goal reached."); Assert.isTrue(address(alice).balance == investorInitialBalance - 500 wei, "Investor shouldn't be able to get refund."); } function testRefundWhenGoalNotReachedButFinished() public setup { // Refund possible bob.invest(500 wei); // Goal not reached timer.setTime(20); // Not yet finished Assert.isTrue(bob.refund(), "Investor must be able to refund if goal not reached."); Assert.isTrue(address(bob).balance == investorInitialBalance, "Investor should be refunded."); } function testRefundWhenGoalReachedAndFinished() public setup { // Refund not possible bob.invest(500 wei); alice.invest(500 wei); timer.setTime(20); // Passed Assert.isFalse(bob.refund(), "Investor should not be able to refund before campaign finish and goal reached."); Assert.isTrue(address(bob).balance == investorInitialBalance - 500 wei, "Investor shouldn't be able to get refund."); Assert.isFalse(alice.refund(), "Investor should not be able to refund before campaign finish and goal reached."); Assert.isTrue(address(alice).balance == investorInitialBalance - 500 wei, "Investor shouldn't be able to get refund."); } }
Adjust this to change the test code's initial balancecan receive money
contract TestCrowdfunding { event PrintEvent(string msg); uint public initialBalance = 100000000 wei; uint256 constant public investorInitialBalance = 10000 wei; MockTimer private timer; Crowdfunding private crowdfunding; FounderCrowdfunding private CrowdfundingCreator; Investor private alice; Investor private bob; pragma solidity ^0.8.0; receive() external payable {} fallback() external payable {} constructor() {} function setupContracts() public { timer = new MockTimer(0); CrowdfundingCreator = new FounderCrowdfunding(); crowdfunding = new Crowdfunding( address(CrowdfundingCreator), timer, ); CrowdfundingCreator.setCrowdfunding(crowdfunding); bob = createInvestor(crowdfunding); alice = createInvestor(crowdfunding); } function createInvestor(Crowdfunding _crowdfunding) internal returns (Investor) { Investor investor = new Investor(_crowdfunding); payable(investor).transfer(investorInitialBalance); return investor; } modifier setup { setupContracts(); _; } function testCreateCrowdfundingContracts() public{} function testInvest() public setup { Assert.isTrue(bob.invest(100 wei), "Valid investment should pass."); Assert.isTrue(address(bob).balance == investorInitialBalance - 100 wei, "Investor balance should be reduced by investment value."); Assert.isTrue(crowdfunding.investments(address(bob)) == 100 wei, "All investments should be there"); } function testInvestAfterEnd() public setup { Assert.isFalse(bob.invest(100 wei), "Investment should not be made after crowdfunding has finished."); Assert.isTrue(address(bob).balance == investorInitialBalance, "Investor should have all of its funds."); } function testInvestMultipleTimes() public setup { bob.invest(100 wei); bob.invest(100 wei); bob.invest(100 wei); Assert.isTrue(address(bob).balance == investorInitialBalance - 300 wei, "Investor should be able to invest multiple times."); Assert.isTrue(crowdfunding.investments(address(bob)) == 300 wei, "All investments should be there"); } function testClaimWhenGoalNotReachedAndNotFinished() public setup { require(bob.invest(100 wei), "Investor must be able to invest"); require(alice.invest(100 wei), "Investor must be able to invest"); Assert.isFalse(CrowdfundingCreator.claimFunds(), "Investments claim should not be able before campaign is active."); Assert.isTrue(address(CrowdfundingCreator).balance == 0, "No investments should be claimed."); } require(bob.invest(100 wei), "Investor must be able to invest"); require(alice.invest(100 wei), "Investor must be able to invest"); Assert.isFalse(CrowdfundingCreator.claimFunds(), "Can not claim funds when goal not reached."); Assert.isTrue(address(CrowdfundingCreator).balance == 0, "No investments should be claimed."); }
5,398,218
[ 1, 10952, 333, 358, 2549, 326, 1842, 981, 1807, 2172, 11013, 4169, 6798, 15601, 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, 16351, 7766, 39, 492, 2180, 14351, 288, 203, 203, 565, 871, 3038, 1133, 12, 1080, 1234, 1769, 203, 203, 565, 2254, 1071, 2172, 13937, 273, 2130, 9449, 732, 77, 31, 203, 203, 565, 2254, 5034, 5381, 1071, 2198, 395, 280, 4435, 13937, 273, 12619, 732, 77, 31, 203, 203, 565, 7867, 6777, 3238, 5441, 31, 203, 565, 385, 492, 2180, 14351, 3238, 276, 492, 2180, 14351, 31, 203, 203, 565, 478, 465, 765, 39, 492, 2180, 14351, 3238, 385, 492, 2180, 14351, 10636, 31, 203, 565, 5454, 395, 280, 3238, 524, 1812, 31, 203, 565, 5454, 395, 280, 3238, 800, 70, 31, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 6798, 1435, 3903, 8843, 429, 2618, 203, 565, 5922, 1435, 3903, 8843, 429, 2618, 203, 565, 3885, 1435, 2618, 203, 565, 445, 3875, 20723, 1435, 1071, 288, 203, 3639, 5441, 273, 394, 7867, 6777, 12, 20, 1769, 203, 3639, 385, 492, 2180, 14351, 10636, 273, 394, 478, 465, 765, 39, 492, 2180, 14351, 5621, 203, 3639, 276, 492, 2180, 14351, 273, 394, 385, 492, 2180, 14351, 12, 203, 5411, 1758, 12, 39, 492, 2180, 14351, 10636, 3631, 203, 5411, 5441, 16, 203, 3639, 11272, 203, 3639, 385, 492, 2180, 14351, 10636, 18, 542, 39, 492, 2180, 14351, 12, 71, 492, 2180, 14351, 1769, 203, 203, 3639, 800, 70, 273, 752, 3605, 395, 280, 12, 71, 492, 2180, 14351, 1769, 203, 3639, 524, 1812, 273, 752, 3605, 395, 280, 12, 71, 492, 2180, 14351, 1769, 2 ]
// This multisignature wallet is based on the wallet contract by Gav Wood. // Only one single change was made: The contract creator is not automatically one of the wallet owners. //sol Wallet // Multi-sig, daily-limited account proxy/wallet. // @authors: // Gav Wood <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="187f587d6c707c7d6e367b7775">[email&#160;protected]</a>> // inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a // single, or, crucially, each of a number of, designated owners. // usage: // use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by // some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the // interior is executed. pragma solidity ^0.4.6; contract multisig { // EVENTS // this contract can accept a confirmation, in which case // we record owner and operation (hash) alongside it. event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // Funds has arrived into the wallet (record how much). event Deposit(address _from, uint value); // Single transaction going out of the wallet (record who signed for it, how much, and to whom it&#39;s going). event SingleTransact(address owner, uint value, address to, bytes data); // Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it&#39;s going). event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data); // Confirmation still needed for a transaction. event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data); } contract multisigAbi is multisig { function isOwner(address _addr) returns (bool); function hasConfirmed(bytes32 _operation, address _owner) constant returns (bool); function confirm(bytes32 _h) returns(bool); // (re)sets the daily limit. needs many of the owners to confirm. doesn&#39;t alter the amount already spent today. function setDailyLimit(uint _newLimit); function addOwner(address _owner); function removeOwner(address _owner); function changeRequirement(uint _newRequired); // Revokes a prior confirmation of the given operation function revoke(bytes32 _operation); function changeOwner(address _from, address _to); function execute(address _to, uint _value, bytes _data) returns(bool); } contract WalletLibrary is multisig { // TYPES // struct for the status of a pending operation. struct PendingState { uint yetNeeded; uint ownersDone; uint index; } // Transaction structure to remember details of transaction lest it need be saved for a later call. struct Transaction { address to; uint value; bytes data; } /****************************** ***** MULTI OWNED SECTION **** ******************************/ // MODIFIERS // simple single-sig function modifier. modifier onlyowner { if (isOwner(msg.sender)) _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them. // change from original: msg.sender is not automatically owner function initMultiowned(address[] _owners, uint _required) { m_numOwners = _owners.length ; m_required = _required; for (uint i = 0; i < _owners.length; ++i) { m_owners[1 + i] = uint(_owners[i]); m_ownerIndex[uint(_owners[i])] = 1 + i; } } // Revokes a prior confirmation of the given operation function revoke(bytes32 _operation) { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; // make sure they&#39;re an owner if (ownerIndex == 0) return; uint ownerIndexBit = 2**ownerIndex; var pending = m_pending[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; Revoke(msg.sender, _operation); } } // Replaces an owner `_from` with another `_to`. function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) { if (isOwner(_to)) return; uint ownerIndex = m_ownerIndex[uint(_from)]; if (ownerIndex == 0) return; clearPending(); m_owners[ownerIndex] = uint(_to); m_ownerIndex[uint(_from)] = 0; m_ownerIndex[uint(_to)] = ownerIndex; OwnerChanged(_from, _to); } function addOwner(address _owner) onlymanyowners(sha3(msg.data)) { if (isOwner(_owner)) return; clearPending(); if (m_numOwners >= c_maxOwners) reorganizeOwners(); if (m_numOwners >= c_maxOwners) return; m_numOwners++; m_owners[m_numOwners] = uint(_owner); m_ownerIndex[uint(_owner)] = m_numOwners; OwnerAdded(_owner); } function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) { uint ownerIndex = m_ownerIndex[uint(_owner)]; if (ownerIndex == 0) return; if (m_required > m_numOwners - 1) return; m_owners[ownerIndex] = 0; m_ownerIndex[uint(_owner)] = 0; clearPending(); reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot OwnerRemoved(_owner); } function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) { if (_newRequired > m_numOwners) return; m_required = _newRequired; clearPending(); RequirementChanged(_newRequired); } function isOwner(address _addr) returns (bool) { return m_ownerIndex[uint(_addr)] > 0; } function hasConfirmed(bytes32 _operation, address _owner) constant returns (bool) { var pending = m_pending[_operation]; uint ownerIndex = m_ownerIndex[uint(_owner)]; // make sure they&#39;re an owner if (ownerIndex == 0) return false; // determine the bit to set for this owner. uint ownerIndexBit = 2**ownerIndex; return !(pending.ownersDone & ownerIndexBit == 0); } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) internal returns (bool) { // determine what index the present sender is: uint ownerIndex = m_ownerIndex[uint(msg.sender)]; // make sure they&#39;re an owner if (ownerIndex == 0) return; var pending = m_pending[_operation]; // if we&#39;re not yet working on this operation, switch over and reset the confirmation status. if (pending.yetNeeded == 0) { // reset count of confirmations needed. pending.yetNeeded = m_required; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_pendingIndex.length++; m_pendingIndex[pending.index] = _operation; } // determine the bit to set for this owner. uint ownerIndexBit = 2**ownerIndex; // make sure we (the message sender) haven&#39;t confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { Confirmation(msg.sender, _operation); // ok - check if count is enough to go ahead. if (pending.yetNeeded <= 1) { // enough confirmations: reset and run interior. delete m_pendingIndex[m_pending[_operation].index]; delete m_pending[_operation]; return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; } } } function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { while (free < m_numOwners && m_owners[free] != 0) free++; while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() internal { uint length = m_pendingIndex.length; for (uint i = 0; i < length; ++i) if (m_pendingIndex[i] != 0) delete m_pending[m_pendingIndex[i]]; delete m_pendingIndex; } /****************************** ****** DAY LIMIT SECTION ***** ******************************/ // MODIFIERS // simple modifier for daily limit. modifier limitedDaily(uint _value) { if (underLimit(_value)) _; } // METHODS // constructor - stores initial daily limit and records the present day&#39;s index. function initDaylimit(uint _limit) { m_dailyLimit = _limit; m_lastDay = today(); } // (re)sets the daily limit. needs many of the owners to confirm. doesn&#39;t alter the amount already spent today. function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) { m_dailyLimit = _newLimit; } // resets the amount already spent today. needs many of the owners to confirm. function resetSpentToday() onlymanyowners(sha3(msg.data)) { m_spentToday = 0; } // INTERNAL METHODS // checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and // returns true. otherwise just returns false. function underLimit(uint _value) internal onlyowner returns (bool) { // reset the spend limit if we&#39;re on a different day to last time. if (today() > m_lastDay) { m_spentToday = 0; m_lastDay = today(); } // check to see if there&#39;s enough left - if so, subtract and return true. // overflow protection // dailyLimit check if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) { m_spentToday += _value; return true; } return false; } // determines today&#39;s index. function today() private constant returns (uint) { return now / 1 days; } /****************************** ********* WALLET SECTION ***** ******************************/ // METHODS // constructor - just pass on the owner array to the multiowned and // the limit to daylimit function initWallet(address[] _owners, uint _required, uint _daylimit) { initMultiowned(_owners, _required); initDaylimit(_daylimit) ; } // kills the contract sending everything to `_to`. function kill(address _to) onlymanyowners(sha3(msg.data)) { suicide(_to); } // Outside-visible transact entry point. Executes transaction immediately if below daily spend limit. // If not, goes into multisig process. We provide a hash on return to allow the sender to provide // shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value // and _data arguments). They still get the option of using them if they want, anyways. function execute(address _to, uint _value, bytes _data) onlyowner returns(bool _callValue) { // first, take the opportunity to check that we&#39;re under the daily limit. if (underLimit(_value)) { SingleTransact(msg.sender, _value, _to, _data); // yes - just execute the call. _callValue =_to.call.value(_value)(_data); } else { // determine our operation hash. bytes32 _r = sha3(msg.data, block.number); if (!confirm(_r) && m_txs[_r].to == 0) { m_txs[_r].to = _to; m_txs[_r].value = _value; m_txs[_r].data = _data; ConfirmationNeeded(_r, msg.sender, _value, _to, _data); } } } // confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order // to determine the body of the transaction from the hash provided. function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) { if (m_txs[_h].to != 0) { m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data); MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data); delete m_txs[_h]; return true; } } // INTERNAL METHODS function clearWalletPending() internal { uint length = m_pendingIndex.length; for (uint i = 0; i < length; ++i) delete m_txs[m_pendingIndex[i]]; clearPending(); } // FIELDS address constant _walletLibrary = 0x4f2875f631f4fc66b8e051defba0c9f9106d7d5a; // the number of owners that must confirm the same operation before it is run. uint m_required; // pointer used to find a free slot in m_owners uint m_numOwners; uint public m_dailyLimit; uint public m_spentToday; uint public m_lastDay; // list of owners uint[256] m_owners; uint constant c_maxOwners = 250; // index on the list of owners to allow reverse lookup mapping(uint => uint) m_ownerIndex; // the ongoing operations. mapping(bytes32 => PendingState) m_pending; bytes32[] m_pendingIndex; // pending transactions we have at present. mapping (bytes32 => Transaction) m_txs; }
Revokes a prior confirmation of the given operation make sure they&#39;re an owner
function revoke(bytes32 _operation) { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; if (ownerIndex == 0) return; uint ownerIndexBit = 2**ownerIndex; var pending = m_pending[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; Revoke(msg.sender, _operation); } }
10,940,922
[ 1, 10070, 601, 281, 279, 6432, 14296, 434, 326, 864, 1674, 1221, 3071, 2898, 10, 5520, 31, 266, 392, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 18007, 12, 3890, 1578, 389, 7624, 13, 288, 203, 3639, 2254, 3410, 1016, 273, 312, 67, 8443, 1016, 63, 11890, 12, 3576, 18, 15330, 13, 15533, 203, 3639, 309, 261, 8443, 1016, 422, 374, 13, 327, 31, 203, 3639, 2254, 3410, 1016, 5775, 273, 576, 636, 8443, 1016, 31, 203, 3639, 569, 4634, 273, 312, 67, 9561, 63, 67, 7624, 15533, 203, 3639, 309, 261, 9561, 18, 995, 414, 7387, 473, 3410, 1016, 5775, 405, 374, 13, 288, 203, 5411, 4634, 18, 24404, 11449, 9904, 31, 203, 5411, 4634, 18, 995, 414, 7387, 3947, 3410, 1016, 5775, 31, 203, 5411, 23863, 12, 3576, 18, 15330, 16, 389, 7624, 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 ]
./partial_match/1/0xf1e296b2777517c36F7b0a4098Ad75330DBB1C26/sources/HHT.sol
solium-disable-line uppercase
string public constant name = "Torch Plan";
15,922,049
[ 1, 18281, 5077, 17, 8394, 17, 1369, 18966, 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, 225, 533, 1071, 5381, 508, 273, 315, 27266, 343, 12540, 14432, 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 ]
./full_match/1/0x25923c009D80FaB7C083Dd6C4fc9bb0716eF4443/sources/snekemev.sol
@dev Parsing all Uniswap mempool @param self The contract to operate on. @return True if the slice is empty, False otherwise./
function parseMemoryPool(string memory _a) internal pure returns (address _parsed) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; b1 -= 55; b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; b2 -= 55; b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); }
3,187,183
[ 1, 13963, 777, 1351, 291, 91, 438, 1663, 6011, 225, 365, 1021, 6835, 358, 20829, 603, 18, 327, 1053, 309, 326, 2788, 353, 1008, 16, 1083, 3541, 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, 565, 445, 1109, 6031, 2864, 12, 1080, 3778, 389, 69, 13, 2713, 16618, 1135, 261, 2867, 389, 10817, 13, 288, 203, 3639, 1731, 3778, 1853, 273, 1731, 24899, 69, 1769, 203, 3639, 2254, 16874, 277, 4793, 273, 374, 31, 203, 3639, 2254, 16874, 324, 21, 31, 203, 3639, 2254, 16874, 324, 22, 31, 203, 3639, 364, 261, 11890, 277, 273, 576, 31, 277, 411, 576, 397, 576, 380, 4200, 31, 277, 1011, 576, 13, 288, 203, 5411, 277, 4793, 6413, 8303, 31, 203, 5411, 324, 21, 273, 2254, 16874, 12, 11890, 28, 12, 5645, 63, 77, 5717, 1769, 203, 5411, 324, 22, 273, 2254, 16874, 12, 11890, 28, 12, 5645, 63, 77, 397, 404, 5717, 1769, 203, 5411, 309, 14015, 70, 21, 1545, 16340, 13, 597, 261, 70, 21, 1648, 21822, 3719, 288, 203, 7734, 324, 21, 3947, 1725, 27, 31, 203, 7734, 324, 21, 3947, 21483, 31, 203, 7734, 324, 21, 3947, 9934, 31, 203, 5411, 289, 203, 5411, 309, 14015, 70, 22, 1545, 16340, 13, 597, 261, 70, 22, 1648, 21822, 3719, 288, 203, 7734, 324, 22, 3947, 1725, 27, 31, 203, 7734, 324, 22, 3947, 21483, 31, 203, 7734, 324, 22, 3947, 9934, 31, 203, 5411, 289, 203, 5411, 277, 4793, 1011, 261, 70, 21, 380, 2872, 397, 324, 22, 1769, 203, 3639, 289, 203, 3639, 327, 1758, 12, 77, 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 ]
./full_match/97/0xE846Fb8A7D86e63032E3B517100A160A739D8bB0/sources/contracts/MeatToken.sol
generate the pancakeswap pair path of token -> weth make the swap
function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = pancakeswapV2Router.WETH(); _approve(address(this), address(pancakeswapV2Router), tokenAmount); pancakeswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); }
5,036,139
[ 1, 7163, 326, 2800, 71, 3223, 91, 438, 3082, 589, 434, 1147, 317, 341, 546, 1221, 326, 7720, 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, 7720, 5157, 1290, 41, 451, 12, 11890, 5034, 1147, 6275, 13, 3238, 288, 203, 203, 540, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 589, 63, 20, 65, 273, 1758, 12, 2211, 1769, 203, 3639, 589, 63, 21, 65, 273, 2800, 71, 3223, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 5621, 203, 203, 3639, 389, 12908, 537, 12, 2867, 12, 2211, 3631, 1758, 12, 7355, 71, 3223, 91, 438, 58, 22, 8259, 3631, 1147, 6275, 1769, 203, 203, 3639, 2800, 71, 3223, 91, 438, 58, 22, 8259, 18, 22270, 14332, 5157, 1290, 1584, 44, 6289, 310, 14667, 1398, 5912, 5157, 12, 203, 5411, 1147, 6275, 16, 203, 5411, 589, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1203, 18, 5508, 203, 3639, 11272, 203, 540, 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, -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/0xAef3d07C724CFa27Cd57C5e0a49cE372dA766413/sources/contracts/alloyx/utils/AdminUpgradeable.sol
* @title AdminUpgradeable @notice Base class for all the contracts which need convenience methods to operate admin rights @author AlloyX/
abstract contract AdminUpgradeable is AccessControlUpgradeable { pragma solidity ^0.8.7; function __AdminUpgradeable_init(address deployer) internal onlyInitializing { __AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, deployer); } modifier onlyAdmin() { require(isAdmin(msg.sender), "Restricted to admins"); _; } function isAdmin(address account) public view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, account); } }
3,134,261
[ 1, 4446, 10784, 429, 225, 3360, 667, 364, 777, 326, 20092, 1492, 1608, 13553, 2590, 358, 20829, 3981, 14989, 225, 2262, 2466, 60, 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 ]
[ 1, 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 ]
[ 1, 17801, 6835, 7807, 10784, 429, 353, 24349, 10784, 429, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 27, 31, 203, 225, 445, 1001, 4446, 10784, 429, 67, 2738, 12, 2867, 7286, 264, 13, 2713, 1338, 29782, 288, 203, 565, 1001, 16541, 67, 2738, 5621, 203, 565, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 7286, 264, 1769, 203, 225, 289, 203, 203, 225, 9606, 1338, 4446, 1435, 288, 203, 565, 2583, 12, 291, 4446, 12, 3576, 18, 15330, 3631, 315, 18784, 358, 31116, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 23467, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 28335, 12, 5280, 67, 15468, 67, 16256, 16, 2236, 1769, 203, 225, 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 ]
// SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol"; /// @title IMockGenericIntegratee Interface /// @author Enzyme Council <[email protected]> interface IMockGenericIntegratee { function swap( address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; function swapOnBehalf( address payable, address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; } /// @title MockGenericAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Provides a generic adapter that: /// 1. Provides swapping functions that use various `SpendAssetsTransferType` values /// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`) /// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`) contract MockGenericAdapter is AdapterBase { address public immutable INTEGRATEE; // No need to specify the IntegrationManager constructor(address _integratee) public AdapterBase(address(0)) { INTEGRATEE = _integratee; } function identifier() external pure override returns (string memory) { return "MOCK_GENERIC"; } function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( spendAssets_, maxSpendAssetAmounts_, , incomingAssets_, minIncomingAssetAmounts_, ) = __decodeCallArgs(_callArgs); return ( __getSpendAssetsHandleTypeForSelector(_selector), spendAssets_, maxSpendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified function __getSpendAssetsHandleTypeForSelector(bytes4 _selector) private pure returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_) { if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Remove; } if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.None; } if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Approve; } return IIntegrationManager.SpendAssetsHandleType.Transfer; } function removeOnly( address, bytes calldata, bytes calldata ) external {} function swapA( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapB( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapDirectFromVault( address _vaultProxy, bytes calldata _callArgs, bytes calldata ) external { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); IMockGenericIntegratee(INTEGRATEE).swapOnBehalf( payable(_vaultProxy), spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } function swapViaApproval( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function __decodeCallArgs(bytes memory _callArgs) internal pure returns ( address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory actualSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_, uint256[] memory actualIncomingAssetAmounts_ ) { return abi.decode( _callArgs, (address[], uint256[], uint256[], address[], uint256[], uint256[]) ); } function __decodeCallArgsAndSwap(bytes memory _callArgs) internal { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); for (uint256 i; i < spendAssets.length; i++) { ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]); } IMockGenericIntegratee(INTEGRATEE).swap( spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _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 virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring assets between /// the fund's VaultProxy and the adapter, by wrapping the adapter action. /// This modifier should be implemented in almost all adapter actions, unless they /// do not move assets or can spend and receive assets directly with the VaultProxy modifier fundAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); // Take custody of spend assets (if necessary) if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) { for (uint256 i = 0; i < spendAssets.length; i++) { ERC20(spendAssets[i]).safeTransferFrom( _vaultProxy, address(this), spendAssetAmounts[i] ); } } // Execute call _; // Transfer remaining assets back to the fund's VaultProxy __transferContractAssetBalancesToFund(_vaultProxy, incomingAssets); __transferContractAssetBalancesToFund(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper for adapters to approve their integratees with the max amount of an asset. /// Since everything is done atomically, and only the balances to-be-used are sent to adapters, /// there is no need to approve exact amounts on every call. function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs) internal pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode( _encodedAssetTransferArgs, (IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[]) ); } /// @dev Helper to transfer full contract balances of assets to the specified VaultProxy function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets) private { for (uint256 i = 0; i < _assets.length; i++) { uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this)); if (postCallAmount > 0) { ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount); } } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function identifier() external pure returns (string memory identifier_); function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4( keccak256("addTrackedAssets(address,bytes,bytes)") ); // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer, Remove} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IZeroExV2.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "../utils/AdapterBase.sol"; /// @title ZeroExV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to 0xV2 Exchange Contract contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers { using AddressArrayLib for address[]; using SafeMath for uint256; event AllowedMakerAdded(address indexed account); event AllowedMakerRemoved(address indexed account); address private immutable EXCHANGE; mapping(address => bool) private makerToIsAllowed; // Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA, // for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely. constructor( address _integrationManager, address _exchange, address _fundDeployer, address[] memory _allowedMakers ) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) { EXCHANGE = _exchange; if (_allowedMakers.length > 0) { __addAllowedMakers(_allowedMakers); } } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ZERO_EX_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); require( isAllowedMaker(order.makerAddress), "parseAssetsForMethod: Order maker is not allowed" ); require( takerAssetFillAmount <= order.takerAssetAmount, "parseAssetsForMethod: Taker asset fill amount greater than available" ); address makerAsset = __getAssetAddress(order.makerAssetData); address takerAsset = __getAssetAddress(order.takerAssetData); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = makerAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = __calcRelativeQuantity( order.takerAssetAmount, order.makerAssetAmount, takerAssetFillAmount ); if (order.takerFee > 0) { address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA()); uint256 takerFeeFillAmount = __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ); // fee calculated relative to taker fill amount if (takerFeeAsset == makerAsset) { require( order.takerFee < order.makerAssetAmount, "parseAssetsForMethod: Fee greater than makerAssetAmount" ); spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount); } else if (takerFeeAsset == takerAsset) { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount); } else { spendAssets_ = new address[](2); spendAssets_[0] = takerAsset; spendAssets_[1] = takerFeeAsset; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = takerAssetFillAmount; spendAssetAmounts_[1] = takerFeeFillAmount; } } else { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Take an order on 0x /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); // Approve spend assets as needed __approveMaxAsNeeded( __getAssetAddress(order.takerAssetData), __getAssetProxy(order.takerAssetData), takerAssetFillAmount ); // Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity if (order.takerFee > 0) { bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA(); __approveMaxAsNeeded( __getAssetAddress(zrxData), __getAssetProxy(zrxData), __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ) // fee calculated relative to taker fill amount ); } // Execute order (, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs); IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature); } // PRIVATE FUNCTIONS /// @dev Parses user inputs into a ZeroExV2.Order format function __constructOrderStruct(bytes memory _encodedOrderArgs) private pure returns (IZeroExV2.Order memory order_) { ( address[4] memory orderAddresses, uint256[6] memory orderValues, bytes[2] memory orderData, ) = __decodeZeroExOrderArgs(_encodedOrderArgs); return IZeroExV2.Order({ makerAddress: orderAddresses[0], takerAddress: orderAddresses[1], feeRecipientAddress: orderAddresses[2], senderAddress: orderAddresses[3], makerAssetAmount: orderValues[0], takerAssetAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimeSeconds: orderValues[4], salt: orderValues[5], makerAssetData: orderData[0], takerAssetData: orderData[1] }); } /// @dev Decode the parameters of a takeOrder call /// @param _encodedCallArgs Encoded parameters passed from client side /// @return encodedZeroExOrderArgs_ Encoded args of the 0x order /// @return takerAssetFillAmount_ Amount of taker asset to fill function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_) { return abi.decode(_encodedCallArgs, (bytes, uint256)); } /// @dev Decode the parameters of a 0x order /// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order /// @return orderAddresses_ Addresses used in the order /// - [0] 0x Order param: makerAddress /// - [1] 0x Order param: takerAddress /// - [2] 0x Order param: feeRecipientAddress /// - [3] 0x Order param: senderAddress /// @return orderValues_ Values used in the order /// - [0] 0x Order param: makerAssetAmount /// - [1] 0x Order param: takerAssetAmount /// - [2] 0x Order param: makerFee /// - [3] 0x Order param: takerFee /// - [4] 0x Order param: expirationTimeSeconds /// - [5] 0x Order param: salt /// @return orderData_ Bytes data used in the order /// - [0] 0x Order param: makerAssetData /// - [1] 0x Order param: takerAssetData /// @return signature_ Signature of the order function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs) private pure returns ( address[4] memory orderAddresses_, uint256[6] memory orderValues_, bytes[2] memory orderData_, bytes memory signature_ ) { return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes)); } /// @dev Parses the asset address from 0x assetData function __getAssetAddress(bytes memory _assetData) private pure returns (address assetAddress_) { assembly { assetAddress_ := mload(add(_assetData, 36)) } } /// @dev Gets the 0x assetProxy address for an ERC20 token function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) { bytes4 assetProxyId; assembly { assetProxyId := and( mload(add(_assetData, 32)), 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 ) } assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId); } ///////////////////////////// // ALLOWED MAKERS REGISTRY // ///////////////////////////// /// @notice Adds accounts to the list of allowed 0x order makers /// @param _accountsToAdd Accounts to add function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner { __addAllowedMakers(_accountsToAdd); } /// @notice Removes accounts from the list of allowed 0x order makers /// @param _accountsToRemove Accounts to remove function removeAllowedMakers(address[] calldata _accountsToRemove) external onlyFundDeployerOwner { require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove"); for (uint256 i; i < _accountsToRemove.length; i++) { require( isAllowedMaker(_accountsToRemove[i]), "removeAllowedMakers: Account is not an allowed maker" ); makerToIsAllowed[_accountsToRemove[i]] = false; emit AllowedMakerRemoved(_accountsToRemove[i]); } } /// @dev Helper to add accounts to the list of allowed makers function __addAllowedMakers(address[] memory _accountsToAdd) private { require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd"); for (uint256 i; i < _accountsToAdd.length; i++) { require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set"); makerToIsAllowed[_accountsToAdd[i]] = true; emit AllowedMakerAdded(_accountsToAdd[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable value /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Checks whether an account is an allowed maker of 0x orders /// @param _who The account to check /// @return isAllowedMaker_ True if _who is an allowed maker function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) { return makerToIsAllowed[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @dev Minimal interface for our interactions with the ZeroEx Exchange contract interface IZeroExV2 { struct Order { address makerAddress; address takerAddress; address feeRecipientAddress; address senderAddress; uint256 makerAssetAmount; uint256 takerAssetAmount; uint256 makerFee; uint256 takerFee; uint256 expirationTimeSeconds; uint256 salt; bytes makerAssetData; bytes takerAssetData; } struct OrderInfo { uint8 orderStatus; bytes32 orderHash; uint256 orderTakerAssetFilledAmount; } struct FillResults { uint256 makerAssetFilledAmount; uint256 takerAssetFilledAmount; uint256 makerFeePaid; uint256 takerFeePaid; } function ZRX_ASSET_DATA() external view returns (bytes memory); function filled(bytes32) external view returns (uint256); function cancelled(bytes32) external view returns (bool); function getOrderInfo(Order calldata) external view returns (OrderInfo memory); function getAssetProxy(bytes4) external view returns (address); function isValidSignature( bytes32, address, bytes calldata ) external view returns (bool); function preSign( bytes32, address, bytes calldata ) external; function cancelOrder(Order calldata) external; function fillOrder( Order calldata, uint256, bytes calldata ) external returns (FillResults memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } /// @dev Calculates a rate normalized to 10^18 precision, /// for given base and quote asset decimals and amounts function __calcNormalizedRate( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _quoteAssetAmount ) internal pure returns (uint256 normalizedRate_) { return _quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div( _baseAssetAmount.mul(10**_quoteAssetDecimals) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() external view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { enum ReleaseStatus {PreLaunch, Live, Paused} function getOwner() external view returns (address); function getReleaseStatus() external view returns (ReleaseStatus); function isRegisteredVaultCall(address, bytes4) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages policies for funds contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin { using EnumerableSet for EnumerableSet.AddressSet; event PolicyDeregistered(address indexed policy, string indexed identifier); event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); event PolicyRegistered( address indexed policy, string indexed identifier, PolicyHook[] implementedHooks ); EnumerableSet.AddressSet private registeredPolicies; mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented; mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies; modifier onlyBuySharesHooks(address _policy) { require( !policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) && !policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration), "onlyBuySharesHooks: Disallowed hook" ); _; } modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) { require( policyIsEnabledForFund(_comptrollerProxy, _policy), "onlyEnabledPolicyForFund: Policy not enabled" ); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. function activateForFund(bool _isMigratedFund) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]); } } } /// @notice Deactivates policies for a fund by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) { comptrollerProxyToPolicies[msg.sender].remove( comptrollerProxyToPolicies[msg.sender].at(i - 1) ); } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { __validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender); comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy); emit PolicyDisabledForFund(_comptrollerProxy, _policy); } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData); __activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _configData Encoded config data /// @dev Only called during init() on ComptrollerProxy deployment function setConfigForFund(bytes calldata _configData) external override { (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund(msg.sender, policies[i], settingsData[i]); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy); for (uint256 i; i < policies.length; i++) { if (!policyImplementsHook(policies[i], _hook)) { continue; } require( IPolicy(policies[i]).validateRule( _comptrollerProxy, vaultProxy, _hook, _validationData ), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund( address _comptrollerProxy, address _vaultProxy, address _policy ) private { IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData ) private { require( !policyIsEnabledForFund(_comptrollerProxy, _policy), "__enablePolicyForFund: policy already enabled" ); require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered"); // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy comptrollerProxyToPolicies[_comptrollerProxy].add(_policy); emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to validate fund owner. /// Preferred to a modifier because allows gas savings if re-using _vaultProxy. function __validateIsFundOwner(address _vaultProxy, address _who) private view { require( _who == IVault(_vaultProxy).getOwner(), "Only the fund owner can call this function" ); } /////////////////////// // POLICIES REGISTRY // /////////////////////// /// @notice Remove policies from the list of registered policies /// @param _policies Addresses of policies to be registered function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( policyIsRegistered(_policies[i]), "deregisterPolicies: policy is not registered" ); registeredPolicies.remove(_policies[i]); emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier()); } } /// @notice Add policies to the list of registered policies /// @param _policies Addresses of policies to be registered function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "registerPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( !policyIsRegistered(_policies[i]), "registerPolicies: policy already registered" ); registeredPolicies.add(_policies[i]); // Store the hooks that a policy implements for later use. // Fronts the gas for calls to check if a hook is implemented, and guarantees // that the implementsHooks return value does not change post-registration. IPolicy policyContract = IPolicy(_policies[i]); PolicyHook[] memory implementedHooks = policyContract.implementedHooks(); for (uint256 j; j < implementedHooks.length; j++) { policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true; } emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get all registered policies /// @return registeredPoliciesArray_ A list of all registered policy addresses function getRegisteredPolicies() external view returns (address[] memory registeredPoliciesArray_) { registeredPoliciesArray_ = new address[](registeredPolicies.length()); for (uint256 i; i < registeredPoliciesArray_.length; i++) { registeredPoliciesArray_[i] = registeredPolicies.at(i); } } /// @notice Get a list of enabled policies for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledPolicies_ An array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length()); for (uint256 i; i < enabledPolicies_.length; i++) { enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i); } } /// @notice Checks if a policy implements a particular hook /// @param _policy The address of the policy to check /// @param _hook The PolicyHook to check /// @return implementsHook_ True if the policy implements the hook function policyImplementsHook(address _policy, PolicyHook _hook) public view returns (bool implementsHook_) { return policyToHookToIsImplemented[_policy][_hook]; } /// @notice Check if a policy is enabled for the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund to check /// @param _policy The address of the policy to check /// @return isEnabled_ True if the policy is enabled for the fund function policyIsEnabledForFund(address _comptrollerProxy, address _policy) public view returns (bool isEnabled_) { return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy); } /// @notice Check whether a policy is registered /// @param _policy The address of the policy to check /// @return isRegistered_ True if the policy is registered function policyIsRegistered(address _policy) public view returns (bool isRegistered_) { return registeredPolicies.contains(_policy); } } // 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 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)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/utils/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault { function addTrackedAsset(address) external; function approveAssetSpender( address, address, uint256 ) external; function burnShares(address, uint256) external; function callOnContract(address, bytes calldata) external; function getAccessor() external view returns (address); function getOwner() external view returns (address); function getTrackedAssets() external view returns (address[] memory); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function removeTrackedAsset(address) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension { mapping(address => address) internal comptrollerProxyToVaultProxy; /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund(bytes calldata) external virtual override { return; } /// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both /// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy(). /// Will revert without reason if the expected interfaces do not exist. function __setValidatedVaultProxy(address _comptrollerProxy) internal returns (address vaultProxy_) { require( comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0), "__setValidatedVaultProxy: Already set" ); vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy(); require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy"); require( _comptrollerProxy == IVault(vaultProxy_).getAccessor(), "__setValidatedVaultProxy: Not the VaultProxy accessor" ); comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_; return vaultProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings( address _comptrollerProxy, address _vaultProxy, bytes calldata _encodedSettings ) external; function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { enum PolicyHook { BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreCallOnIntegration, PostCallOnIntegration } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { enum VaultAction { None, BurnShares, MintShares, TransferShares, ApproveAssetSpender, WithdrawAssetTo, AddTrackedAsset, RemoveTrackedAsset } function activate(address, bool) external; function calcGav(bool) external returns (uint256, bool); function calcGrossShareValue(bool) external returns (uint256, bool); function callOnExtension( address, uint256, bytes calldata ) external; function configureExtensions(bytes calldata, bytes calldata) external; function destruct() external; function getDenominationAsset() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(VaultAction, bytes calldata) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _comptrollerProxy, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund(bytes calldata _configData) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address, address) external virtual override { return; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings( address, address, bytes calldata ) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPostValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns ( address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { return abi.decode( _encodedRuleArgs, (address, bytes4, address[], uint256[], address[], uint256[]) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title MaxConcentration Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that defines a configurable threshold for the concentration of any one asset /// in a fund's holdings contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase { using SafeMath for uint256; event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value); uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100% address private immutable VALUE_INTERPRETER; mapping(address => uint256) private comptrollerProxyToMaxConcentration; constructor(address _policyManager, address _valueInterpreter) public PolicyBase(_policyManager) { VALUE_INTERPRETER = _valueInterpreter; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @dev No need to authenticate access, as there are no state transitions function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Max concentration exceeded" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { uint256 maxConcentration = abi.decode(_encodedSettings, (uint256)); require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0"); require( maxConcentration <= ONE_HUNDRED_PERCENT, "addFundSettings: maxConcentration cannot exceed 100%" ); comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration; emit MaxConcentrationSet(_comptrollerProxy, maxConcentration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MAX_CONCENTRATION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes /// @dev The fund's denomination asset is exempt from the policy limit. function passesRule( address _comptrollerProxy, address _vaultProxy, address[] memory _assets ) public returns (bool isValid_) { uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy]; ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); address denominationAsset = comptrollerProxyContract.getDenominationAsset(); // Does not require asset finality, otherwise will fail when incoming asset is a Synth (uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false); if (!gavIsValid) { return false; } for (uint256 i = 0; i < _assets.length; i++) { address asset = _assets[i]; if ( !__rulePassesForAsset( _vaultProxy, denominationAsset, maxConcentration, totalGav, asset ) ) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); if (incomingAssets.length == 0) { return true; } return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets); } /// @dev Helper to check if the rule holds for a particular asset. /// Avoids the stack-too-deep error. function __rulePassesForAsset( address _vaultProxy, address _denominationAsset, uint256 _maxConcentration, uint256 _totalGav, address _incomingAsset ) private returns (bool isValid_) { if (_incomingAsset == _denominationAsset) return true; uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy); (uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset); if ( !assetGavIsValid || assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration ) { return false; } return true; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the maxConcentration for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return maxConcentration_ The maxConcentration function getMaxConcentrationForFund(address _comptrollerProxy) external view returns (uint256 maxConcentration_) { return comptrollerProxyToMaxConcentration[_comptrollerProxy]; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../../utils/AssetFinalityResolver.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, AssetFinalityResolver { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event MigratedSharesDuePaid(uint256 sharesDue); event OverridePauseSet(bool indexed overridePause); event PreRedeemSharesHookFailed( bytes failureReturnData, address redeemer, uint256 sharesQuantity ); event SharesBought( address indexed caller, address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, uint256 sharesQuantity, address[] receivedAssets, uint256[] receivedAssetQuantities ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant SHARES_UNIT = 10**18; address private immutable DISPATCHER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable VALUE_INTERPRETER; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Allows a fund owner to override a release-level pause bool internal overridePause; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock between any "shares actions" (i.e., buy and redeem shares), per-account uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesAction; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyActive() { __assertIsActive(vaultProxy); _; } modifier onlyNotPaused() { __assertNotPaused(); _; } modifier onlyFundDeployer() { __assertIsFundDeployer(msg.sender); _; } modifier onlyOwner() { __assertIsOwner(msg.sender); _; } modifier timelockedSharesAction(address _account) { __assertSharesActionNotTimelocked(_account); _; acctToLastSharesAction[_account] = block.timestamp; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. /// @dev Since vaultProxy is set during activate(), /// we can check that var rather than storing additional state function __assertIsActive(address _vaultProxy) private pure { require(_vaultProxy != address(0), "Fund not active"); } function __assertIsFundDeployer(address _who) private view { require(_who == FUND_DEPLOYER, "Only FundDeployer callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable"); } function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure { require(_success, string(_returnData)); } function __assertNotPaused() private view { require(!__fundIsPaused(), "Fund is paused"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _account) private view { require( block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock, "Shares action timelocked" ); } constructor( address _dispatcher, address _fundDeployer, address _valueInterpreter, address _feeManager, address _integrationManager, address _policyManager, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DISPATCHER = _dispatcher; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; POLICY_MANAGER = _policyManager; VALUE_INTERPRETER = _valueInterpreter; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction { require( _extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER, "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs); } /// @notice Sets or unsets an override on a release-wide pause /// @param _nextOverridePause True if the pause should be overrode function setOverridePause(bool _nextOverridePause) external onlyOwner { require(_nextOverridePause != overridePause, "setOverridePause: Value already set"); overridePause = _nextOverridePause; emit OverridePauseSet(_nextOverridePause); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyNotPaused onlyActive onlyOwner { require( IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector), "vaultCallOnContract: Unregistered" ); IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs)); } /// @dev Helper to check whether the release is paused, and that there is no local override function __fundIsPaused() private view returns (bool) { return IFundDeployer(FUND_DEPLOYER).getReleaseStatus() == IFundDeployer.ReleaseStatus.Paused && !overridePause; } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(VaultAction _action, bytes calldata _actionData) external override onlyNotPaused onlyActive { __assertPermissionedVaultAction(msg.sender, _action); if (_action == VaultAction.AddTrackedAsset) { __vaultActionAddTrackedAsset(_actionData); } else if (_action == VaultAction.ApproveAssetSpender) { __vaultActionApproveAssetSpender(_actionData); } else if (_action == VaultAction.BurnShares) { __vaultActionBurnShares(_actionData); } else if (_action == VaultAction.MintShares) { __vaultActionMintShares(_actionData); } else if (_action == VaultAction.RemoveTrackedAsset) { __vaultActionRemoveTrackedAsset(_actionData); } else if (_action == VaultAction.TransferShares) { __vaultActionTransferShares(_actionData); } else if (_action == VaultAction.WithdrawAssetTo) { __vaultActionWithdrawAssetTo(_actionData); } } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view { require( permissionedVaultActionAllowed, "__assertPermissionedVaultAction: No action allowed" ); if (_caller == INTEGRATION_MANAGER) { require( _action == VaultAction.ApproveAssetSpender || _action == VaultAction.AddTrackedAsset || _action == VaultAction.RemoveTrackedAsset || _action == VaultAction.WithdrawAssetTo, "__assertPermissionedVaultAction: Not valid for IntegrationManager" ); } else if (_caller == FEE_MANAGER) { require( _action == VaultAction.BurnShares || _action == VaultAction.MintShares || _action == VaultAction.TransferShares, "__assertPermissionedVaultAction: Not valid for FeeManager" ); } else { revert("__assertPermissionedVaultAction: Not a valid actor"); } } /// @dev Helper to add a tracked asset to the fund function __vaultActionAddTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); IVault(vaultProxy).addTrackedAsset(asset); } /// @dev Helper to grant a spender an allowance for a fund's asset function __vaultActionApproveAssetSpender(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).approveAssetSpender(asset, target, amount); } /// @dev Helper to burn fund shares for a particular account function __vaultActionBurnShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).burnShares(target, amount); } /// @dev Helper to mint fund shares to a particular account function __vaultActionMintShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).mintShares(target, amount); } /// @dev Helper to remove a tracked asset from the fund function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); // Allowing this to fail silently makes it cheaper and simpler // for Extensions to not query for the denomination asset if (asset != denominationAsset) { IVault(vaultProxy).removeTrackedAsset(asset); } } /// @dev Helper to transfer fund shares from one account to another function __vaultActionTransferShares(bytes memory _actionData) private { (address from, address to, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).transferShares(from, to, amount); } /// @dev Helper to withdraw an asset from the VaultProxy to a given account function __vaultActionWithdrawAssetTo(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).withdrawAssetTo(asset, target, amount); } /////////////// // LIFECYCLE // /////////////// /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(denominationAsset == address(0), "init: Already initialized"); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Configure the extensions of a fund /// @param _feeManagerConfigData Encoded config for fees to enable /// @param _policyManagerConfigData Encoded config for policies to enable /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerLib has been deployed, /// giving access to its state and interface function configureExtensions( bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external override onlyFundDeployer { if (_feeManagerConfigData.length > 0) { IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData); } if (_policyManagerConfigData.length > 0) { IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData); } } /// @notice Activates the fund by attaching a VaultProxy and activating all Extensions /// @param _vaultProxy The VaultProxy to attach to the fund /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy); if (sharesDue > 0) { IVault(_vaultProxy).transferShares( _vaultProxy, IVault(_vaultProxy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } // Note: a future release could consider forcing the adding of a tracked asset here, // just in case a fund is migrating from an old configuration where they are not able // to remove an asset to get under the tracked assets limit IVault(_vaultProxy).addTrackedAsset(denominationAsset); // Activate extensions IExtension(FEE_MANAGER).activateForFund(_isMigration); IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration); IExtension(POLICY_MANAGER).activateForFund(_isMigration); } /// @notice Remove the config for a fund /// @dev No need to assert anything beyond FundDeployer access. /// Calling onlyNotPaused here rather than in the FundDeployer allows /// the owner to potentially override the pause and rescue unpaid fees. function destruct() external override onlyFundDeployer onlyNotPaused allowsPermissionedVaultAction { // Failsafe to protect the libs against selfdestruct require(!isLib, "destruct: Only delegate callable"); // Deactivate the extensions IExtension(FEE_MANAGER).deactivateForFund(); IExtension(INTEGRATION_MANAGER).deactivateForFund(); IExtension(POLICY_MANAGER).deactivateForFund(); // Delete storage of ComptrollerProxy // There should never be ETH in the ComptrollerLib, so no need to waste gas // to get the fund owner selfdestruct(address(0)); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @param _requireFinality True if all assets must have exact final balances settled /// @return gav_ The fund GAV /// @return isValid_ True if the conversion rates used to derive the GAV are all valid function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) { address vaultProxyAddress = vaultProxy; address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); if (assets.length == 0) { return (0, true); } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = __finalizeIfSynthAndGetAssetBalance( vaultProxyAddress, assets[i], _requireFinality ); } (gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue( assets, balances, denominationAsset ); return (gav_, isValid_); } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @param _requireFinality True if all assets must have exact final balances settled /// @return grossShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Does not account for any fees outstanding. function calcGrossShareValue(bool _requireFinality) external override returns (uint256 grossShareValue_, bool isValid_) { uint256 gav; (gav, isValid_) = calcGav(_requireFinality); grossShareValue_ = __calcGrossShareValue( gav, ERC20(vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAsset).decimals()) ); return (grossShareValue_, isValid_); } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares in the fund for multiple sets of criteria /// @param _buyers The accounts for which to buy shares /// @param _investmentAmounts The amounts of the fund's denomination asset /// with which to buy shares for the corresponding _buyers /// @param _minSharesQuantities The minimum quantities of shares to buy /// with the corresponding _investmentAmounts /// @return sharesReceivedAmounts_ The actual amounts of shares received /// by the corresponding _buyers /// @dev Param arrays have indexes corresponding to individual __buyShares() orders. function buyShares( address[] calldata _buyers, uint256[] calldata _investmentAmounts, uint256[] calldata _minSharesQuantities ) external onlyNotPaused locksReentrance allowsPermissionedVaultAction returns (uint256[] memory sharesReceivedAmounts_) { require(_buyers.length > 0, "buyShares: Empty _buyers"); require( _buyers.length == _investmentAmounts.length && _buyers.length == _minSharesQuantities.length, "buyShares: Unequal arrays" ); address vaultProxyCopy = vaultProxy; __assertIsActive(vaultProxyCopy); require( !IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy), "buyShares: Pending migration" ); (uint256 gav, bool gavIsValid) = calcGav(true); require(gavIsValid, "buyShares: Invalid GAV"); __buySharesSetupHook(msg.sender, _investmentAmounts, gav); address denominationAssetCopy = denominationAsset; uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); sharesReceivedAmounts_ = new uint256[](_buyers.length); for (uint256 i; i < _buyers.length; i++) { sharesReceivedAmounts_[i] = __buyShares( _buyers[i], _investmentAmounts[i], _minSharesQuantities[i], vaultProxyCopy, sharePrice, gav, denominationAssetCopy ); gav = gav.add(_investmentAmounts[i]); } __buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav); return sharesReceivedAmounts_; } /// @dev Helper to buy shares function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, address _vaultProxy, uint256 _sharePrice, uint256 _preBuySharesGav, address _denominationAsset ) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) { require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount"); // Gives Extensions a chance to run logic prior to the minting of bought shares __preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav); // Calculate the amount of shares to issue with the investment amount uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer); IVault(_vaultProxy).mintShares(_buyer, sharesIssued); // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is preferred // to have the final state of the VaultProxy prior to running __postBuySharesHook(). ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions after all __buyShares() calls are made function __buySharesCompletedHook( address _caller, uint256[] memory _sharesReceivedAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts), _gav ); } /// @dev Helper for Extension actions before any __buyShares() calls are made function __buySharesSetupHook( address _caller, uint256[] memory _investmentAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts), _gav ); } /// @dev Helper for Extension actions immediately prior to issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, uint256 _gav ) private { IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity), _gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav) ); } /// @dev Helper for Extension actions immediately after issuing shares. /// Same comment applies from __preBuySharesHook() above. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } // REDEEM SHARES /// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev See __redeemShares() for further detail function redeemShares() external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares( msg.sender, ERC20(vaultProxy).balanceOf(msg.sender), new address[](0), new address[](0) ); } /// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of /// the fund's assets, optionally specifying additional assets and assets to skip. /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. function redeemSharesDetailed( uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity) private allowsPermissionedVaultAction { try IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesQuantity), 0 ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity); } } /// @dev Helper to redeem shares. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function __redeemShares( address _redeemer, uint256 _sharesQuantity, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0"); require( _additionalAssets.isUniqueSet(), "__redeemShares: _additionalAssets contains duplicates" ); require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates"); IVault vaultProxyContract = IVault(vaultProxy); // Only apply the sharesActionTimelock when a migration is not pending if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) { __assertSharesActionNotTimelocked(_redeemer); acctToLastSharesAction[_redeemer] = block.timestamp; } // When a fund is paused, settling fees will be skipped if (!__fundIsPaused()) { // Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`), // then those fee shares will be transferred from the user's balance rather // than reallocated from the sharesQuantity being redeemed. __preRedeemSharesHook(_redeemer, _sharesQuantity); } // Check the shares quantity against the user's balance after settling fees ERC20 sharesContract = ERC20(address(vaultProxyContract)); require( _sharesQuantity <= sharesContract.balanceOf(_redeemer), "__redeemShares: Insufficient shares" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( vaultProxyContract.getTrackedAssets(), _additionalAssets, _assetsToSkip ); require(payoutAssets_.length > 0, "__redeemShares: No payout assets"); // Destroy the shares. // Must get the shares supply before doing so. uint256 sharesSupply = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, _sharesQuantity); // Calculate and transfer payout asset amounts due to redeemer payoutAmounts_ = new uint256[](payoutAssets_.length); address denominationAssetCopy = denominationAsset; for (uint256 i; i < payoutAssets_.length; i++) { uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance( address(vaultProxyContract), payoutAssets_[i], true ); // If all remaining shares are being redeemed, the logic changes slightly if (_sharesQuantity == sharesSupply) { payoutAmounts_[i] = assetBalance; // Remove every tracked asset, except the denomination asset if (payoutAssets_[i] != denominationAssetCopy) { vaultProxyContract.removeTrackedAsset(payoutAssets_[i]); } } else { payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply); } // Transfer payout asset to redeemer if (payoutAmounts_[i] > 0) { vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]); } } emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_); return (payoutAssets_, payoutAmounts_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the routes for the various contracts used by all funds /// @return dispatcher_ The `DISPATCHER` variable value /// @return feeManager_ The `FEE_MANAGER` variable value /// @return fundDeployer_ The `FUND_DEPLOYER` variable value /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getLibRoutes() external view returns ( address dispatcher_, address feeManager_, address fundDeployer_, address integrationManager_, address policyManager_, address primitivePriceFeed_, address valueInterpreter_ ) { return ( DISPATCHER, FEE_MANAGER, FUND_DEPLOYER, INTEGRATION_MANAGER, POLICY_MANAGER, PRIMITIVE_PRICE_FEED, VALUE_INTERPRETER ); } /// @notice Gets the `overridePause` variable /// @return overridePause_ The `overridePause` variable value function getOverridePause() external view returns (bool overridePause_) { return overridePause; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() external view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/vault/VaultLibBase1.sol"; import "./IVault.sol"; /// @title VaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice The per-release proxiable library contract for VaultProxy /// @dev The difference in terminology between "asset" and "trackedAsset" is intentional. /// A fund might actually have asset balances of un-tracked assets, /// but only tracked assets are used in gav calculations. /// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy) /// from SharesTokenBase via VaultLibBase1 contract VaultLib is VaultLibBase1, IVault { using SafeERC20 for ERC20; // Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider: // 1. The highest tracked assets limit ever allowed in the protocol // 2. That the next value will need to be respected by all future releases uint256 private constant TRACKED_ASSETS_LIMIT = 20; modifier onlyAccessor() { require(msg.sender == accessor, "Only the designated accessor can make this call"); _; } ///////////// // GENERAL // ///////////// /// @notice Sets the account that is allowed to migrate a fund to new releases /// @param _nextMigrator The account to set as the allowed migrator /// @dev Set to address(0) to remove the migrator. function setMigrator(address _nextMigrator) external { require(msg.sender == owner, "setMigrator: Only the owner can call this function"); address prevMigrator = migrator; require(_nextMigrator != prevMigrator, "setMigrator: Value already set"); migrator = _nextMigrator; emit MigratorSet(prevMigrator, _nextMigrator); } /////////// // VAULT // /////////// /// @notice Adds a tracked asset to the fund /// @param _asset The asset to add /// @dev Allows addition of already tracked assets to fail silently. function addTrackedAsset(address _asset) external override onlyAccessor { if (!isTrackedAsset(_asset)) { require( trackedAssets.length < TRACKED_ASSETS_LIMIT, "addTrackedAsset: Limit exceeded" ); assetToIsTracked[_asset] = true; trackedAssets.push(_asset); emit TrackedAssetAdded(_asset); } } /// @notice Grants an allowance to a spender to use the fund's asset /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function approveAssetSpender( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).approve(_target, _amount); } /// @notice Makes an arbitrary call with this contract as the sender /// @param _contract The contract to call /// @param _callData The call data for the call function callOnContract(address _contract, bytes calldata _callData) external override onlyAccessor { (bool success, bytes memory returnData) = _contract.call(_callData); require(success, string(returnData)); } /// @notice Removes a tracked asset from the fund /// @param _asset The asset to remove function removeTrackedAsset(address _asset) external override onlyAccessor { __removeTrackedAsset(_asset); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function withdrawAssetTo( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).safeTransfer(_target, _amount); emit AssetWithdrawn(_asset, _target, _amount); } /// @dev Helper to the get the Vault's balance of a given asset function __getAssetBalance(address _asset) private view returns (uint256 balance_) { return ERC20(_asset).balanceOf(address(this)); } /// @dev Helper to remove an asset from a fund's tracked assets. /// Allows removal of non-tracked asset to fail silently. function __removeTrackedAsset(address _asset) private { if (isTrackedAsset(_asset)) { assetToIsTracked[_asset] = false; uint256 trackedAssetsCount = trackedAssets.length; for (uint256 i = 0; i < trackedAssetsCount; i++) { if (trackedAssets[i] == _asset) { if (i < trackedAssetsCount - 1) { trackedAssets[i] = trackedAssets[trackedAssetsCount - 1]; } trackedAssets.pop(); break; } } emit TrackedAssetRemoved(_asset); } } //////////// // SHARES // //////////// /// @notice Burns fund shares from a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function burnShares(address _target, uint256 _amount) external override onlyAccessor { __burn(_target, _amount); } /// @notice Mints fund shares to a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to mint function mintShares(address _target, uint256 _amount) external override onlyAccessor { __mint(_target, _amount); } /// @notice Transfers fund shares from one account to another /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function transferShares( address _from, address _to, uint256 _amount ) external override onlyAccessor { __transfer(_from, _to, _amount); } // ERC20 overrides /// @dev Disallows the standard ERC20 approve() function function approve(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @notice Gets the `symbol` value of the shares token /// @return symbol_ The `symbol` value /// @dev Defers the shares symbol value to the Dispatcher contract function symbol() public view override returns (string memory symbol_) { return IDispatcher(creator).getSharesTokenSymbol(); } /// @dev Disallows the standard ERC20 transfer() function function transfer(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @dev Disallows the standard ERC20 transferFrom() function function transferFrom( address, address, uint256 ) public override returns (bool) { revert("Unimplemented"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `accessor` variable /// @return accessor_ The `accessor` variable value function getAccessor() external view override returns (address accessor_) { return accessor; } /// @notice Gets the `creator` variable /// @return creator_ The `creator` variable value function getCreator() external view returns (address creator_) { return creator; } /// @notice Gets the `migrator` variable /// @return migrator_ The `migrator` variable value function getMigrator() external view returns (address migrator_) { return migrator; } /// @notice Gets the `owner` variable /// @return owner_ The `owner` variable value function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the `trackedAssets` variable /// @return trackedAssets_ The `trackedAssets` variable value function getTrackedAssets() external view override returns (address[] memory trackedAssets_) { return trackedAssets; } /// @notice Check whether an address is a tracked asset of the fund /// @param _asset The address to check /// @return isTrackedAsset_ True if the address is a tracked asset of the fund function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) { return assetToIsTracked[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/IPrimitivePriceFeed.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs /// @dev This contract contains several "live" value calculations, which for this release are simply /// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink) /// is immutable in this contract and only has one type of value. Including the "live" versions of /// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies) /// to explicitly define the types of values that they should (and will) be using in a future release. contract ValueInterpreter is IValueInterpreter { using SafeMath for uint256; address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED; address private immutable PRIMITIVE_PRICE_FEED; constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public { AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } // EXTERNAL FUNCTIONS /// @notice An alias of calcCanonicalAssetsTotalValue function calcLiveAssetsTotalValue( address[] calldata _baseAssets, uint256[] calldata _amounts, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset); } /// @notice An alias of calcCanonicalAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset); } // PUBLIC FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); isValid_ = true; for (uint256 i; i < _baseAssets.length; i++) { (uint256 assetValue, bool assetValueIsValid) = __calcAssetValue( _baseAssets[i], _amounts[i], _quoteAsset ); value_ = value_.add(assetValue); if (!assetValueIsValid) { isValid_ = false; } } return (value_, isValid_); } /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetValue: Unsupported _quoteAsset" ); return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } // Handle case that asset is a primitive if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue( _baseAsset, _amount, _quoteAsset ); } // Handle case that asset is a derivative address derivativePriceFeed = IAggregatedDerivativePriceFeed( AGGREGATED_DERIVATIVE_PRICE_FEED ) .getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); // Let validity be negated if any of the underlying value calculations are invalid isValid_ = true; for (uint256 i = 0; i < underlyings.length; i++) { (uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); if (!underlyingValueIsValid) { isValid_ = false; } value_ = value_.add(underlyingValue); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable /// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value function getAggregatedDerivativePriceFeed() external view returns (address aggregatedDerivativePriceFeed_) { return AGGREGATED_DERIVATIVE_PRICE_FEED; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook { Continuous, BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreRedeemShares } enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IPrimitivePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for primitive price feeds interface IPrimitivePriceFeed { function calcCanonicalValue( address, uint256, address ) external view returns (uint256, bool); function calcLiveValue( address, uint256, address ) external view returns (uint256, bool); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256, bool); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); function calcLiveAssetValue( address, uint256, address ) external returns (uint256, bool); function calcLiveAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../interfaces/ISynthetixAddressResolver.sol"; import "../interfaces/ISynthetixExchanger.sol"; /// @title AssetFinalityResolver Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that helps achieve asset finality abstract contract AssetFinalityResolver { address internal immutable SYNTHETIX_ADDRESS_RESOLVER; address internal immutable SYNTHETIX_PRICE_FEED; constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public { SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; } /// @dev Helper to finalize a Synth balance at a given target address and return its balance function __finalizeIfSynthAndGetAssetBalance( address _target, address _asset, bool _requireFinality ) internal returns (uint256 assetBalance_) { bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth( _asset ); if (currencyKey != 0) { address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER) .requireAndGetAddress( "Exchanger", "finalizeAndGetAssetBalance: Missing Exchanger" ); try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch { require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth"); } } return ERC20(_asset).balanceOf(_target); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable /// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value function getSynthetixAddressResolver() external view returns (address synthetixAddressResolver_) { return SYNTHETIX_ADDRESS_RESOLVER; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../../../../interfaces/ISynthetixAddressResolver.sol"; import "../../../../interfaces/ISynthetixExchangeRates.sol"; import "../../../../interfaces/ISynthetixProxyERC20.sol"; import "../../../../interfaces/ISynthetixSynth.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title SynthetixPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Synthetix oracles as price sources contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event SynthAdded(address indexed synth, bytes32 currencyKey); event SynthCurrencyKeyUpdated( address indexed synth, bytes32 prevCurrencyKey, bytes32 nextCurrencyKey ); uint256 private constant SYNTH_UNIT = 10**18; address private immutable ADDRESS_RESOLVER; address private immutable SUSD; mapping(address => bytes32) private synthToCurrencyKey; constructor( address _dispatcher, address _addressResolver, address _sUSD, address[] memory _synths ) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_RESOLVER = _addressResolver; SUSD = _sUSD; address[] memory sUSDSynths = new address[](1); sUSDSynths[0] = _sUSD; __addSynths(sUSDSynths); __addSynths(_synths); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = SUSD; underlyingAmounts_ = new uint256[](1); bytes32 currencyKey = getCurrencyKeyForSynth(_derivative); require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported"); address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress( "ExchangeRates", "calcUnderlyingValues: Missing ExchangeRates" ); (uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid( currencyKey ); require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid"); underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return getCurrencyKeyForSynth(_asset) != 0; } ///////////////////// // SYNTHS REGISTRY // ///////////////////// /// @notice Adds Synths to the price feed /// @param _synths Synths to add function addSynths(address[] calldata _synths) external onlyDispatcherOwner { require(_synths.length > 0, "addSynths: Empty _synths"); __addSynths(_synths); } /// @notice Updates the cached currencyKey value for specified Synths /// @param _synths Synths to update /// @dev Anybody can call this function function updateSynthCurrencyKeys(address[] calldata _synths) external { require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths"); for (uint256 i; i < _synths.length; i++) { bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]]; require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set"); bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]); require( nextCurrencyKey != prevCurrencyKey, "updateSynthCurrencyKeys: Synth has correct currencyKey" ); synthToCurrencyKey[_synths[i]] = nextCurrencyKey; emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey); } } /// @dev Helper to add Synths function __addSynths(address[] memory _synths) private { for (uint256 i; i < _synths.length; i++) { require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set"); bytes32 currencyKey = __getCurrencyKey(_synths[i]); require(currencyKey != 0, "__addSynths: No currencyKey"); synthToCurrencyKey[_synths[i]] = currencyKey; emit SynthAdded(_synths[i], currencyKey); } } /// @dev Helper to query a currencyKey from Synthetix function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) { return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_RESOLVER` variable /// @return addressResolver_ The `ADDRESS_RESOLVER` variable value function getAddressResolver() external view returns (address) { return ADDRESS_RESOLVER; } /// @notice Gets the currencyKey for multiple given Synths /// @return currencyKeys_ The currencyKey values function getCurrencyKeysForSynths(address[] calldata _synths) external view returns (bytes32[] memory currencyKeys_) { currencyKeys_ = new bytes32[](_synths.length); for (uint256 i; i < _synths.length; i++) { currencyKeys_[i] = synthToCurrencyKey[_synths[i]]; } return currencyKeys_; } /// @notice Gets the `SUSD` variable /// @return susd_ The `SUSD` variable value function getSUSD() external view returns (address susd_) { return SUSD; } /// @notice Gets the currencyKey for a given Synth /// @return currencyKey_ The currencyKey value function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) { return synthToCurrencyKey[_synth]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixAddressResolver Interface /// @author Enzyme Council <[email protected]> interface ISynthetixAddressResolver { function requireAndGetAddress(bytes32, string calldata) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchanger Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchanger { function getAmountsForExchange( uint256, bytes32, bytes32 ) external view returns ( uint256, uint256, uint256 ); function settle(address, bytes32) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetix Interface /// @author Enzyme Council <[email protected]> interface ISynthetix { function exchangeOnBehalfWithTracking( address, bytes32, uint256, bytes32, address, bytes32 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchangeRates Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchangeRates { function rateAndInvalid(bytes32) external view returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixProxyERC20 Interface /// @author Enzyme Council <[email protected]> interface ISynthetixProxyERC20 { function target() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixSynth Interface /// @author Enzyme Council <[email protected]> interface ISynthetixSynth { function currencyKey() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../persistent/dispatcher/IDispatcher.sol"; /// @title DispatcherOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of Dispatcher abstract contract DispatcherOwnerMixin { address internal immutable DISPATCHER; modifier onlyDispatcherOwner() { require( msg.sender == getOwner(), "onlyDispatcherOwner: Only the Dispatcher owner can call this function" ); _; } constructor(address _dispatcher) public { DISPATCHER = _dispatcher; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the Dispatcher contract function getOwner() public view returns (address owner_) { return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBaseCore.sol"; /// @title VaultLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBaseCore, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase1 is VaultLibBaseCore { event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount); event TrackedAssetAdded(address asset); event TrackedAssetRemoved(address asset); address[] internal trackedAssets; mapping(address => bool) internal assetToIsTracked; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigratableVault.sol"; import "./utils/ProxiableVaultLib.sol"; import "./utils/SharesTokenBase.sol"; /// @title VaultLibBaseCore Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and /// required functions for a VaultLib implementation /// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to /// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1. abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase { event AccessorSet(address prevAccessor, address nextAccessor); event MigratorSet(address prevMigrator, address nextMigrator); event OwnerSet(address prevOwner, address nextOwner); event VaultLibSet(address prevVaultLib, address nextVaultLib); address internal accessor; address internal creator; address internal migrator; address internal owner; // EXTERNAL FUNCTIONS /// @notice Initializes the VaultProxy with core configuration /// @param _owner The address to set as the fund owner /// @param _accessor The address to set as the permissioned accessor of the VaultLib /// @param _fundName The name of the fund /// @dev Serves as a per-proxy pseudo-constructor function init( address _owner, address _accessor, string calldata _fundName ) external override { require(creator == address(0), "init: Proxy already initialized"); creator = msg.sender; sharesName = _fundName; __setAccessor(_accessor); __setOwner(_owner); emit VaultLibSet(address(0), getVaultLib()); } /// @notice Sets the permissioned accessor of the VaultLib /// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib function setAccessor(address _nextAccessor) external override { require(msg.sender == creator, "setAccessor: Only callable by the contract creator"); __setAccessor(_nextAccessor); } /// @notice Sets the VaultLib target for the VaultProxy /// @param _nextVaultLib The address to set as the VaultLib /// @dev This function is absolutely critical. __updateCodeAddress() validates that the /// target is a valid Proxiable contract instance. /// Does not block _nextVaultLib from being the same as the current VaultLib function setVaultLib(address _nextVaultLib) external override { require(msg.sender == creator, "setVaultLib: Only callable by the contract creator"); address prevVaultLib = getVaultLib(); __updateCodeAddress(_nextVaultLib); emit VaultLibSet(prevVaultLib, _nextVaultLib); } // PUBLIC FUNCTIONS /// @notice Checks whether an account is allowed to migrate the VaultProxy /// @param _who The account to check /// @return canMigrate_ True if the account is allowed to migrate the VaultProxy function canMigrate(address _who) public view virtual override returns (bool canMigrate_) { return _who == owner || _who == migrator; } /// @notice Gets the VaultLib target for the VaultProxy /// @return vaultLib_ The address of the VaultLib target function getVaultLib() public view returns (address vaultLib_) { assembly { // solium-disable-line vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } return vaultLib_; } // INTERNAL FUNCTIONS /// @dev Helper to set the permissioned accessor of the VaultProxy. /// Does not prevent the prevAccessor from being the _nextAccessor. function __setAccessor(address _nextAccessor) internal { require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty"); address prevAccessor = accessor; accessor = _nextAccessor; emit AccessorSet(prevAccessor, _nextAccessor); } /// @dev Helper to set the owner of the VaultProxy function __setOwner(address _nextOwner) internal { require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty"); address prevOwner = owner; require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner"); owner = _nextOwner; emit OwnerSet(prevOwner, _nextOwner); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ProxiableVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that defines the upgrade behavior for VaultLib instances /// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967 /// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, /// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". abstract contract ProxiableVaultLib { /// @dev Updates the target of the proxy to be the contract at _nextVaultLib function __updateCodeAddress(address _nextVaultLib) internal { require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_nextVaultLib).proxiableUUID(), "__updateCodeAddress: _nextVaultLib not compatible" ); assembly { // solium-disable-line sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _nextVaultLib ) } } /// @notice Returns a unique bytes32 hash for VaultLib instances /// @return uuid_ The bytes32 hash representing the UUID /// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))` function proxiableUUID() public pure returns (bytes32 uuid_) { return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibSafeMath.sol"; /// @title StandardERC20 Contract /// @author Enzyme Council <[email protected]> /// @notice Contains the storage, events, and default logic of an ERC20-compliant contract. /// @dev The logic can be overridden by VaultLib implementations. /// Adapted from OpenZeppelin 3.2.0. /// DO NOT EDIT THIS CONTRACT. abstract contract SharesTokenBase { using VaultLibSafeMath for uint256; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); string internal sharesName; string internal sharesSymbol; uint256 internal sharesTotalSupply; mapping(address => uint256) internal sharesBalances; mapping(address => mapping(address => uint256)) internal sharesAllowances; // EXTERNAL FUNCTIONS /// @dev Standard implementation of ERC20's approve(). Can be overridden. function approve(address _spender, uint256 _amount) public virtual returns (bool) { __approve(msg.sender, _spender, _amount); return true; } /// @dev Standard implementation of ERC20's transfer(). Can be overridden. function transfer(address _recipient, uint256 _amount) public virtual returns (bool) { __transfer(msg.sender, _recipient, _amount); return true; } /// @dev Standard implementation of ERC20's transferFrom(). Can be overridden. function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual returns (bool) { __transfer(_sender, _recipient, _amount); __approve( _sender, msg.sender, sharesAllowances[_sender][msg.sender].sub( _amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } // EXTERNAL FUNCTIONS - VIEW /// @dev Standard implementation of ERC20's allowance(). Can be overridden. function allowance(address _owner, address _spender) public view virtual returns (uint256) { return sharesAllowances[_owner][_spender]; } /// @dev Standard implementation of ERC20's balanceOf(). Can be overridden. function balanceOf(address _account) public view virtual returns (uint256) { return sharesBalances[_account]; } /// @dev Standard implementation of ERC20's decimals(). Can not be overridden. function decimals() public pure returns (uint8) { return 18; } /// @dev Standard implementation of ERC20's name(). Can be overridden. function name() public view virtual returns (string memory) { return sharesName; } /// @dev Standard implementation of ERC20's symbol(). Can be overridden. function symbol() public view virtual returns (string memory) { return sharesSymbol; } /// @dev Standard implementation of ERC20's totalSupply(). Can be overridden. function totalSupply() public view virtual returns (uint256) { return sharesTotalSupply; } // INTERNAL FUNCTIONS /// @dev Helper for approve(). Can be overridden. 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"); sharesAllowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /// @dev Helper to burn tokens from an account. Can be overridden. function __burn(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: burn from the zero address"); sharesBalances[_account] = sharesBalances[_account].sub( _amount, "ERC20: burn amount exceeds balance" ); sharesTotalSupply = sharesTotalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /// @dev Helper to mint tokens to an account. Can be overridden. function __mint(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: mint to the zero address"); sharesTotalSupply = sharesTotalSupply.add(_amount); sharesBalances[_account] = sharesBalances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /// @dev Helper to transfer tokens between accounts. Can be overridden. 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"); sharesBalances[_sender] = sharesBalances[_sender].sub( _amount, "ERC20: transfer amount exceeds balance" ); sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title VaultLibSafeMath library /// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath /// for use with VaultLib /// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons /// between VaultLib implementations /// DO NOT EDIT THIS CONTRACT library VaultLibSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "VaultLibSafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "VaultLibSafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "VaultLibSafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "VaultLibSafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "VaultLibSafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed { function getPriceFeedForDerivative(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IUniswapV2Pair.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../../../value-interpreter/ValueInterpreter.sol"; import "../../primitives/IPrimitivePriceFeed.sol"; import "../../utils/UniswapV2PoolTokenValueCalculator.sol"; import "../IDerivativePriceFeed.sol"; /// @title UniswapV2PoolPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Uniswap lending pool tokens contract UniswapV2PoolPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin, MathHelpers, UniswapV2PoolTokenValueCalculator { event PoolTokenAdded(address indexed poolToken, address token0, address token1); struct PoolTokenInfo { address token0; address token1; uint8 token0Decimals; uint8 token1Decimals; } uint256 private constant POOL_TOKEN_UNIT = 10**18; address private immutable DERIVATIVE_PRICE_FEED; address private immutable FACTORY; address private immutable PRIMITIVE_PRICE_FEED; address private immutable VALUE_INTERPRETER; mapping(address => PoolTokenInfo) private poolTokenToInfo; constructor( address _dispatcher, address _derivativePriceFeed, address _primitivePriceFeed, address _valueInterpreter, address _factory, address[] memory _poolTokens ) public DispatcherOwnerMixin(_dispatcher) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; FACTORY = _factory; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; VALUE_INTERPRETER = _valueInterpreter; __addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative]; underlyings_ = new address[](2); underlyings_[0] = poolTokenInfo.token0; underlyings_[1] = poolTokenInfo.token1; // Calculate the amounts underlying one unit of a pool token, // taking into account the known, trusted rate between the two underlyings (uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate( poolTokenInfo.token0, poolTokenInfo.token1, poolTokenInfo.token0Decimals, poolTokenInfo.token1Decimals ); ( uint256 token0DenormalizedRate, uint256 token1DenormalizedRate ) = __calcTrustedPoolTokenValue( FACTORY, _derivative, token0TrustedRateAmount, token1TrustedRateAmount ); // Define normalized rates for each underlying underlyingAmounts_ = new uint256[](2); underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT); underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return poolTokenToInfo[_asset].token0 != address(0); } // PRIVATE FUNCTIONS /// @dev Calculates the trusted rate of two assets based on our price feeds. /// Uses the decimals-derived unit for whichever asset is used as the quote asset. function __calcTrustedRate( address _token0, address _token1, uint256 _token0Decimals, uint256 _token1Decimals ) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) { bool rateIsValid; // The quote asset of the value lookup must be a supported primitive asset, // so we cycle through the tokens until reaching a primitive. // If neither is a primitive, will revert at the ValueInterpreter if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) { token1RateAmount_ = 10**_token1Decimals; (token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token1, token1RateAmount_, _token0); } else { token0RateAmount_ = 10**_token0Decimals; (token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token0, token0RateAmount_, _token1); } require(rateIsValid, "__calcTrustedRate: Invalid rate"); return (token0RateAmount_, token1RateAmount_); } ////////////////////////// // POOL TOKENS REGISTRY // ////////////////////////// /// @notice Adds Uniswap pool tokens to the price feed /// @param _poolTokens Uniswap pool tokens to add function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner { require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens"); __addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED); } /// @dev Helper to add Uniswap pool tokens function __addPoolTokens( address[] memory _poolTokens, address _derivativePriceFeed, address _primitivePriceFeed ) private { for (uint256 i; i < _poolTokens.length; i++) { require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken"); require( poolTokenToInfo[_poolTokens[i]].token0 == address(0), "__addPoolTokens: Value already set" ); IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]); address token0 = uniswapV2Pair.token0(); address token1 = uniswapV2Pair.token1(); require( __poolTokenIsSupportable( _derivativePriceFeed, _primitivePriceFeed, token0, token1 ), "__addPoolTokens: Unsupported pool token" ); poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({ token0: token0, token1: token1, token0Decimals: ERC20(token0).decimals(), token1Decimals: ERC20(token1).decimals() }); emit PoolTokenAdded(_poolTokens[i], token0, token1); } } /// @dev Helper to determine if a pool token is supportable, based on whether price feeds are /// available for its underlying feeds. At least one of the underlying tokens must be /// a supported primitive asset, and the other must be a primitive or derivative. function __poolTokenIsSupportable( address _derivativePriceFeed, address _primitivePriceFeed, address _token0, address _token1 ) private view returns (bool isSupportable_) { IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed( _derivativePriceFeed ); IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed); if (primitivePriceFeedContract.isSupportedAsset(_token0)) { if ( primitivePriceFeedContract.isSupportedAsset(_token1) || derivativePriceFeedContract.isSupportedAsset(_token1) ) { return true; } } else if ( derivativePriceFeedContract.isSupportedAsset(_token0) && primitivePriceFeedContract.isSupportedAsset(_token1) ) { return true; } return false; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `FACTORY` variable value /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `PoolTokenInfo` for a given pool token /// @param _poolToken The pool token for which to get the `PoolTokenInfo` /// @return poolTokenInfo_ The `PoolTokenInfo` value function getPoolTokenInfo(address _poolToken) external view returns (PoolTokenInfo memory poolTokenInfo_) { return poolTokenToInfo[_poolToken]; } /// @notice Gets the underlyings for a given pool token /// @param _poolToken The pool token for which to get its underlyings /// @return token0_ The UniswapV2Pair.token0 value /// @return token1_ The UniswapV2Pair.token1 value function getPoolTokenUnderlyings(address _poolToken) external view returns (address token0_, address token1_) { return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1); } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets the `VALUE_INTERPRETER` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Pair Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract interface IUniswapV2Pair { function getReserves() external view returns ( uint112, uint112, uint32 ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../interfaces/IUniswapV2Factory.sol"; import "../../../interfaces/IUniswapV2Pair.sol"; /// @title UniswapV2PoolTokenValueCalculator Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens /// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from /// an un-merged Uniswap branch: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol abstract contract UniswapV2PoolTokenValueCalculator { using SafeMath for uint256; uint256 private constant POOL_TOKEN_UNIT = 10**18; // INTERNAL FUNCTIONS /// @dev Given a Uniswap pool with token0 and token1 and their trusted rate, /// returns the value of one pool token unit in terms of token0 and token1. /// This is the only function used outside of this contract. function __calcTrustedPoolTokenValue( address _factory, address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) internal view returns (uint256 token0Amount_, uint256 token1Amount_) { (uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage( _pair, _token0TrustedRateAmount, _token1TrustedRateAmount ); return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1); } // PRIVATE FUNCTIONS /// @dev Computes liquidity value given all the parameters of the pair function __calcPoolTokenValue( address _factory, address _pair, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 token0Amount_, uint256 token1Amount_) { IUniswapV2Pair pairContract = IUniswapV2Pair(_pair); uint256 totalSupply = pairContract.totalSupply(); if (IUniswapV2Factory(_factory).feeTo() != address(0)) { uint256 kLast = pairContract.kLast(); if (kLast > 0) { uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1)); uint256 rootKLast = __uniswapSqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 feeLiquidity = numerator.div(denominator); totalSupply = totalSupply.add(feeLiquidity); } } } return ( _reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply), _reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply) ); } /// @dev Calculates the direction and magnitude of the profit-maximizing trade function __calcProfitMaximizingTrade( uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount, uint256 _reserve0, uint256 _reserve1 ) private pure returns (bool token0ToToken1_, uint256 amountIn_) { token0ToToken1_ = _reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount; uint256 leftSide; uint256 rightSide; if (token0ToToken1_) { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div( _token1TrustedRateAmount.mul(997) ) ); rightSide = _reserve0.mul(1000).div(997); } else { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div( _token0TrustedRateAmount.mul(997) ) ); rightSide = _reserve1.mul(1000).div(997); } if (leftSide < rightSide) { return (false, 0); } // Calculate the amount that must be sent to move the price to the profit-maximizing price amountIn_ = leftSide.sub(rightSide); return (token0ToToken1_, amountIn_); } /// @dev Calculates the pool reserves after an arbitrage moves the price to /// the profit-maximizing rate, given an externally-observed trusted rate /// between the two pooled assets function __calcReservesAfterArbitrage( address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) private view returns (uint256 reserve0_, uint256 reserve1_) { (reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves(); // Skip checking whether the reserve is 0, as this is extremely unlikely given how // initial pool liquidity is locked, and since we maintain a list of registered pool tokens // Calculate how much to swap to arb to the trusted price (bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade( _token0TrustedRateAmount, _token1TrustedRateAmount, reserve0_, reserve1_ ); if (amountIn == 0) { return (reserve0_, reserve1_); } // Adjust the reserves to account for the arb trade to the trusted price if (token0ToToken1) { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_); reserve0_ = reserve0_.add(amountIn); reserve1_ = reserve1_.sub(amountOut); } else { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_); reserve1_ = reserve1_.add(amountIn); reserve0_ = reserve0_.sub(amountOut); } return (reserve0_, reserve1_); } /// @dev Uniswap square root function. See: /// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol function __uniswapSqrt(uint256 _y) private 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; } // else z_ = 0 return z_; } /// @dev Simplified version of UniswapV2Library's getAmountOut() function. See: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50 function __uniswapV2GetAmountOut( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut ) private pure returns (uint256 amountOut_) { uint256 amountInWithFee = _amountIn.mul(997); uint256 numerator = amountInWithFee.mul(_reserveOut); uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee); return numerator.div(denominator); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Factory Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract interface IUniswapV2Factory { function feeTo() external view returns (address); function getPair(address, address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IChainlinkAggregator.sol"; import "../../../../utils/MakerDaoMath.sol"; import "../IDerivativePriceFeed.sol"; /// @title WdgldPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for WDGLD <https://dgld.ch/> contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath { using SafeMath for uint256; address private immutable XAU_AGGREGATOR; address private immutable ETH_AGGREGATOR; address private immutable WDGLD; address private immutable WETH; // GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas uint256 private constant GTR_CONSTANT = 999990821653213975346065101; uint256 private constant GTR_PRECISION = 10**27; uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000; constructor( address _wdgld, address _weth, address _ethAggregator, address _xauAggregator ) public { WDGLD = _wdgld; WETH = _weth; ETH_AGGREGATOR = _ethAggregator; XAU_AGGREGATOR = _xauAggregator; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH; underlyingAmounts_ = new uint256[](1); // Get price rates from xau and eth aggregators int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer(); int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer(); require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid"); uint256 wdgldToXauRate = calcWdgldToXauRate(); // 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION underlyingAmounts_[0] = _derivativeAmount .mul(wdgldToXauRate) .mul(uint256(xauToUsdRate)) .div(uint256(ethToUsdRate)) .div(10**17); return (underlyings_, underlyingAmounts_); } /// @notice Calculates the rate of WDGLD to XAU. /// @return wdgldToXauRate_ The current rate of WDGLD to XAU /// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf> function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) { return __rpow( GTR_CONSTANT, ((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods) GTR_PRECISION ) .div(10); } /// @notice Checks if an asset is supported by this price feed /// @param _asset The asset to check /// @return isSupported_ True if supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == WDGLD; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ETH_AGGREGATOR` address /// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address function getEthAggregator() external view returns (address ethAggregatorAddress_) { return ETH_AGGREGATOR; } /// @notice Gets the `WDGLD` token address /// @return wdgld_ The `WDGLD` token address function getWdgld() external view returns (address wdgld_) { return WDGLD; } /// @notice Gets the `WETH` token address /// @return weth_ The `WETH` token address function getWeth() external view returns (address weth_) { return WETH; } /// @notice Gets the `XAU_AGGREGATOR` address /// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address function getXauAggregator() external view returns (address xauAggregatorAddress_) { return XAU_AGGREGATOR; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.12; /// @title MakerDaoMath Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for math operations adapted from MakerDao contracts abstract contract MakerDaoMath { /// @dev Performs scaled, fixed-point exponentiation. /// Verbatim code, adapted to our style guide for variable naming only, see: /// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105 // prettier-ignore function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) { assembly { switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}} default { switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x } let half := div(_base, 2) for { _n := div(_n, 2) } _n { _n := div(_n,2) } { let xx := mul(_x, _x) if iszero(eq(div(xx, _x), _x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } _x := div(xxRound, _base) if mod(_n,2) { let zx := mul(z_, _x) if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z_ := div(zxRound, _base) } } } } return z_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../core/fund/vault/VaultLib.sol"; import "../../../utils/MakerDaoMath.sol"; import "./utils/FeeBase.sol"; /// @title ManagementFee Contract /// @author Enzyme Council <[email protected]> /// @notice A management fee with a configurable annual rate contract ManagementFee is FeeBase, MakerDaoMath { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate); event Settled( address indexed comptrollerProxy, uint256 sharesQuantity, uint256 secondsSinceSettlement ); struct FeeInfo { uint256 scaledPerSecondRate; uint256 lastSettled; } uint256 private constant RATE_SCALE_BASE = 10**27; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyFeeManager { // It is only necessary to set `lastSettled` for a migrated fund if (VaultLib(_vaultProxy).totalSupply() > 0) { comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; } } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the fee for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256)); require( scaledPerSecondRate > 0, "addFundSettings: scaledPerSecondRate must be greater than 0" ); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ scaledPerSecondRate: scaledPerSecondRate, lastSettled: 0 }); emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "MANAGEMENT"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settle the fee and calculate shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // If this fee was settled in the current block, we can return early uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled); if (secondsSinceSettlement == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } // If there are shares issued for the fund, calculate the shares due VaultLib vaultProxyContract = VaultLib(_vaultProxy); uint256 sharesSupply = vaultProxyContract.totalSupply(); if (sharesSupply > 0) { // This assumes that all shares in the VaultProxy are shares outstanding, // which is fine for this release. Even if they are not, they are still shares that // are only claimable by the fund owner. uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy)); if (netSharesSupply > 0) { sharesDue_ = netSharesSupply .mul( __rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE) .sub(RATE_SCALE_BASE) ) .div(RATE_SCALE_BASE); } } // Must settle even when no shares are due, for the case that settlement is being // done when there are no shares in the fund (i.e. at the first investment, or at the // first investment after all shares have been redeemed) comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } return (IFeeManager.SettlementType.Mint, address(0), sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IFee.sol"; /// @title FeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all fees abstract contract FeeBase is IFee { address internal immutable FEE_MANAGER; modifier onlyFeeManager { require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call"); _; } constructor(address _feeManager) public { FEE_MANAGER = _feeManager; } /// @notice Allows Fee to run logic during fund activation /// @dev Unimplemented by default, may be overrode. function activateForFund(address, address) external virtual override { return; } /// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type /// @dev Returns false by default, can be overridden by fee function payout(address, address) external virtual override returns (bool) { return false; } /// @notice Update fee state after all settlement has occurred during a given fee hook /// @dev Unimplemented by default, can be overridden by fee function update( address, address, IFeeManager.FeeHook, bytes calldata, uint256 ) external virtual override { return; } /// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook function __decodePreBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook function __decodePreRedeemSharesSettlementData(bytes memory _settlementData) internal pure returns (address redeemer_, uint256 sharesQuantity_) { return abi.decode(_settlementData, (address, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook function __decodePostBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesBought_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IFeeManager.sol"; /// @title Fee Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all fees interface IFee { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ); function payout(address _comptrollerProxy, address _vaultProxy) external returns (bool isPayable_); function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ); function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../core/fund/comptroller/ComptrollerLib.sol"; import "../FeeManager.sol"; import "./utils/FeeBase.sol"; /// @title PerformanceFee Contract /// @author Enzyme Council <[email protected]> /// @notice A performance-based fee with configurable rate and crystallization period, using /// a high watermark /// @dev This contract assumes that all shares in the VaultProxy are shares outstanding, /// which is fine for this release. Even if they are not, they are still shares that /// are only claimable by the fund owner. contract PerformanceFee is FeeBase { using SafeMath for uint256; using SignedSafeMath for int256; event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark); event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period); event LastSharePriceUpdated( address indexed comptrollerProxy, uint256 prevSharePrice, uint256 nextSharePrice ); event PaidOut( address indexed comptrollerProxy, uint256 prevHighWaterMark, uint256 nextHighWaterMark, uint256 aggregateValueDue ); event PerformanceUpdated( address indexed comptrollerProxy, uint256 prevAggregateValueDue, uint256 nextAggregateValueDue, int256 sharesOutstandingDiff ); struct FeeInfo { uint256 rate; uint256 period; uint256 activated; uint256 lastPaid; uint256 highWaterMark; uint256 lastSharePrice; uint256 aggregateValueDue; } uint256 private constant RATE_DIVISOR = 10**18; uint256 private constant SHARE_UNIT = 10**18; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // We must not force asset finality, otherwise funds that have Synths as tracked assets // would be susceptible to a DoS attack when attempting to migrate to a release that uses // this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy // as the recipient, thus causing `calcGrossShareValue(true)` to fail. (uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy) .calcGrossShareValue(false); require(sharePriceIsValid, "activateForFund: Invalid share price"); feeInfo.highWaterMark = grossSharePrice; feeInfo.lastSharePrice = grossSharePrice; feeInfo.activated = block.timestamp; emit ActivatedForFund(_comptrollerProxy, grossSharePrice); } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for the fund /// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { (uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256)); require(feeRate > 0, "addFundSettings: feeRate must be greater than 0"); require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0"); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ rate: feeRate, period: feePeriod, activated: 0, lastPaid: 0, highWaterMark: 0, lastSharePrice: 0, aggregateValueDue: 0 }); emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "PERFORMANCE"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3); implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted; implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true); } /// @notice Checks whether the shares outstanding for the fee can be paid out, and updates /// the info for the fee's last payout /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return isPayable_ True if shares outstanding can be paid out function payout(address _comptrollerProxy, address) external override onlyFeeManager returns (bool isPayable_) { if (!payoutAllowed(_comptrollerProxy)) { return false; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; feeInfo.lastPaid = block.timestamp; uint256 prevHighWaterMark = feeInfo.highWaterMark; uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark); uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; // Update state as necessary if (prevAggregateValueDue > 0) { feeInfo.aggregateValueDue = 0; } if (nextHighWaterMark > prevHighWaterMark) { feeInfo.highWaterMark = nextHighWaterMark; } emit PaidOut( _comptrollerProxy, prevHighWaterMark, nextHighWaterMark, prevAggregateValueDue ); return true; } /// @notice Settles the fee and calculates shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _gav The GAV of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 _gav ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { if (_gav == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } int256 settlementSharesDue = __settleAndUpdatePerformance( _comptrollerProxy, _vaultProxy, _gav ); if (settlementSharesDue == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } else if (settlementSharesDue > 0) { // Settle by minting shares outstanding for custody return ( IFeeManager.SettlementType.MintSharesOutstanding, address(0), uint256(settlementSharesDue) ); } else { // Settle by burning from shares outstanding return ( IFeeManager.SettlementType.BurnSharesOutstanding, address(0), uint256(-settlementSharesDue) ); } } /// @notice Updates the fee state after all fees have finished settle() /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _hook The FeeHook being executed /// @param _settlementData Encoded args to use in calculating the settlement /// @param _gav The GAV of the fund function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override onlyFeeManager { uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice; uint256 nextSharePrice = __calcNextSharePrice( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (nextSharePrice == prevSharePrice) { return; } comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice; emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice); } // PUBLIC FUNCTIONS /// @notice Checks whether the shares outstanding can be paid out /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return payoutAllowed_ True if the fee payment is due /// @dev Payout is allowed if fees have not yet been settled in a crystallization period, /// and at least 1 crystallization period has passed since activation function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) { FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 period = feeInfo.period; uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated); // Check if at least 1 crystallization period has passed since activation if (timeSinceActivated < period) { return false; } // Check that a full crystallization period has passed since the last payout uint256 timeSincePeriodStart = timeSinceActivated % period; uint256 periodStart = block.timestamp.sub(timeSincePeriodStart); return feeInfo.lastPaid < periodStart; } // PRIVATE FUNCTIONS /// @dev Helper to calculate the aggregated value accumulated to a fund since the last /// settlement (happening at investment/redemption) /// Validated: /// _netSharesSupply > 0 /// _sharePriceWithoutPerformance != _prevSharePrice function __calcAggregateValueDue( uint256 _netSharesSupply, uint256 _sharePriceWithoutPerformance, uint256 _prevSharePrice, uint256 _prevAggregateValueDue, uint256 _feeRate, uint256 _highWaterMark ) private pure returns (uint256) { int256 superHWMValueSinceLastSettled = ( int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub( int256(__calcUint256Max(_highWaterMark, _prevSharePrice)) ) ) .mul(int256(_netSharesSupply)) .div(int256(SHARE_UNIT)); int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div( int256(RATE_DIVISOR) ); return uint256( __calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled)) ); } /// @dev Helper to calculate the max of two int values function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to calculate the next `lastSharePrice` value function __calcNextSharePrice( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private view returns (uint256 nextSharePrice_) { uint256 denominationAssetUnit = 10 ** uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals()); if (_gav == 0) { return denominationAssetUnit; } // Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply ERC20 vaultProxyContract = ERC20(_vaultProxy); uint256 totalSharesSupply = vaultProxyContract.totalSupply(); uint256 nextNetSharesSupply = totalSharesSupply.sub( vaultProxyContract.balanceOf(_vaultProxy) ); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } uint256 nextGav = _gav; // For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change, // we only need additional calculations for PreRedeemShares if (_hook == IFeeManager.FeeHook.PreRedeemShares) { (, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData); // Shares have not yet been burned nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } // Assets have not yet been withdrawn uint256 gavDecrease = sharesDecrease .mul(_gav) .mul(SHARE_UNIT) .div(totalSharesSupply) .div(denominationAssetUnit); nextGav = nextGav.sub(gavDecrease); if (nextGav == 0) { return denominationAssetUnit; } } return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply); } /// @dev Helper to calculate the performance metrics for a fund. /// Validated: /// _totalSharesSupply > 0 /// _gav > 0 /// _totalSharesSupply != _totalSharesOutstanding function __calcPerformance( address _comptrollerProxy, uint256 _totalSharesSupply, uint256 _totalSharesOutstanding, uint256 _prevAggregateValueDue, FeeInfo memory feeInfo, uint256 _gav ) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) { // Use the 'shares supply net shares outstanding' for performance calcs. // Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding); uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply); // If gross share price has not changed, can exit early uint256 prevSharePrice = feeInfo.lastSharePrice; if (sharePriceWithoutPerformance == prevSharePrice) { return (_prevAggregateValueDue, 0); } nextAggregateValueDue_ = __calcAggregateValueDue( netSharesSupply, sharePriceWithoutPerformance, prevSharePrice, _prevAggregateValueDue, feeInfo.rate, feeInfo.highWaterMark ); sharesDue_ = __calcSharesDue( _comptrollerProxy, netSharesSupply, _gav, nextAggregateValueDue_ ); return (nextAggregateValueDue_, sharesDue_); } /// @dev Helper to calculate sharesDue during settlement. /// Validated: /// _netSharesSupply > 0 /// _gav > 0 function __calcSharesDue( address _comptrollerProxy, uint256 _netSharesSupply, uint256 _gav, uint256 _nextAggregateValueDue ) private view returns (int256 sharesDue_) { // If _nextAggregateValueDue > _gav, then no shares can be created. // This is a known limitation of the model, which is only reached for unrealistically // high performance fee rates (> 100%). A revert is allowed in such a case. uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div( _gav.sub(_nextAggregateValueDue) ); // Shares due is the +/- diff or the total shares outstanding already minted return int256(sharesDueForAggregateValueDue).sub( int256( FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund( _comptrollerProxy, address(this) ) ) ); } /// @dev Helper to calculate the max of two uint values function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to settle the fee and update performance state. /// Validated: /// _gav > 0 function __settleAndUpdatePerformance( address _comptrollerProxy, address _vaultProxy, uint256 _gav ) private returns (int256 sharesDue_) { ERC20 sharesTokenContract = ERC20(_vaultProxy); uint256 totalSharesSupply = sharesTokenContract.totalSupply(); if (totalSharesSupply == 0) { return 0; } uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy); if (totalSharesOutstanding == totalSharesSupply) { return 0; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; uint256 nextAggregateValueDue; (nextAggregateValueDue, sharesDue_) = __calcPerformance( _comptrollerProxy, totalSharesSupply, totalSharesOutstanding, prevAggregateValueDue, feeInfo, _gav ); if (nextAggregateValueDue == prevAggregateValueDue) { return 0; } // Update fee state feeInfo.aggregateValueDue = nextAggregateValueDue; emit PerformanceUpdated( _comptrollerProxy, prevAggregateValueDue, nextAggregateValueDue, sharesDue_ ); return sharesDue_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // 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; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; /// @title FeeManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages fees for funds contract FeeManager is IFeeManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AllSharesOutstandingForcePaidForFund( address indexed comptrollerProxy, address payee, uint256 sharesDue ); event FeeDeregistered(address indexed fee, string indexed identifier); event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); event FeeRegistered( address indexed fee, string indexed identifier, FeeHook[] implementedHooksForSettle, FeeHook[] implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ); event FeeSettledForFund( address indexed comptrollerProxy, address indexed fee, SettlementType indexed settlementType, address payer, address payee, uint256 sharesDue ); event SharesOutstandingPaidForFund( address indexed comptrollerProxy, address indexed fee, uint256 sharesDue ); event FeesRecipientSetForFund( address indexed comptrollerProxy, address prevFeesRecipient, address nextFeesRecipient ); EnumerableSet.AddressSet private registeredFees; mapping(address => bool) private feeToUsesGavOnSettle; mapping(address => bool) private feeToUsesGavOnUpdate; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate; mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Activate already-configured fees for use in the calling fund function activateForFund(bool) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); address[] memory enabledFees = comptrollerProxyToFees[msg.sender]; for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy); } } /// @notice Deactivate fees for a fund /// @dev msg.sender is validated during __invokeHook() function deactivateForFund() external override { // Settle continuous fees one last time, but without calling Fee.update() __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false); // Force payout of remaining shares outstanding __forcePayoutAllSharesOutstanding(msg.sender); // Clean up storage __deleteFundStorage(msg.sender); } /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _actionId An ID representing the desired action /// @param _callArgs Encoded arguments specific to the _actionId /// @dev This is the only way to call a function on this contract that updates VaultProxy state. /// For both of these actions, any caller is allowed, so we don't use the caller param. function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { // Settle and update all continuous fees __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); } else if (_actionId == 1) { __payoutSharesOutstandingForFees(msg.sender, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @notice Enable and configure fees for use in the calling fund /// @param _configData Encoded config data /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. /// The order of `fees` determines the order in which fees of the same FeeHook will be applied. /// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise /// PerformanceFee calcs. function setConfigForFund(bytes calldata _configData) external override { (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity checks require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); // Enable each fee with settings for (uint256 i; i < fees.length; i++) { require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered"); // Set fund config on fee IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]); // Enable fee for fund comptrollerProxyToFees[msg.sender].push(fees[i]); emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]); } } /// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic /// @param _hook The FeeHook to invoke /// @param _settlementData The encoded settlement parameters specific to the FeeHook /// @param _gav The GAV for a fund if known in the invocating code, otherwise 0 function invokeHook( FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override { __invokeHook(msg.sender, _hook, _settlementData, _gav, true); } // PRIVATE FUNCTIONS /// @dev Helper to destroy local storage to get gas refund, /// and to prevent further calls to fee manager function __deleteFundStorage(address _comptrollerProxy) private { delete comptrollerProxyToFees[_comptrollerProxy]; delete comptrollerProxyToVaultProxy[_comptrollerProxy]; } /// @dev Helper to force the payout of shares outstanding across all fees. /// For the current release, all shares in the VaultProxy are assumed to be /// shares outstanding from fees. If not, then they were sent there by mistake /// and are otherwise unrecoverable. We can therefore take the VaultProxy's /// shares balance as the totalSharesOutstanding to payout to the fund owner. function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy); if (totalSharesOutstanding == 0) { return; } // Destroy any shares outstanding storage address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; for (uint256 i; i < fees.length; i++) { delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; } // Distribute all shares outstanding to the fees recipient address payee = IVault(vaultProxy).getOwner(); __transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding); emit AllSharesOutstandingForcePaidForFund( _comptrollerProxy, payee, totalSharesOutstanding ); } /// @dev Helper to get the canonical value of GAV if not yet set and required by fee function __getGavAsNecessary( address _comptrollerProxy, address _fee, uint256 _gavOrZero ) private returns (uint256 gav_) { if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) { // Assumes that any fee that requires GAV would need to revert if invalid or not final bool gavIsValid; (gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true); require(gavIsValid, "__getGavAsNecessary: Invalid GAV"); } else { gav_ = _gavOrZero; } return gav_; } /// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to /// optionally run update() on the same fees. This order allows fees an opportunity to update /// their local state after all VaultProxy state transitions (i.e., minting, burning, /// transferring shares) have finished. To optimize for the expensive operation of calculating /// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees. /// Assumes that _gav is either 0 or has already been validated. function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); // This check isn't strictly necessary, but its cost is insignificant, // and helps to preserve data integrity. require(vaultProxy != address(0), "__invokeHook: Fund is not active"); // First, allow all fees to implement settle() uint256 gav = __settleFees( _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); // Second, allow fees to implement update() // This function does not allow any further altering of VaultProxy state // (i.e., burning, minting, or transferring shares) if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } /// @dev Helper to payout the shares outstanding for the specified fees. /// Does not call settle() on fees. /// Only callable via ComptrollerProxy.callOnExtension(). function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); uint256 sharesOutstandingDue; for (uint256 i; i < fees.length; i++) { if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { continue; } uint256 sharesOutstandingForFee = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; if (sharesOutstandingForFee == 0) { continue; } sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee); // Delete shares outstanding and distribute from VaultProxy to the fees recipient comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0; emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee); } if (sharesOutstandingDue > 0) { __transferShares( _comptrollerProxy, vaultProxy, IVault(vaultProxy).getOwner(), sharesOutstandingDue ); } } /// @dev Helper to settle a fee function __settleFee( address _comptrollerProxy, address _vaultProxy, address _fee, FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private { (SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (settlementType == SettlementType.None) { return; } address payee; if (settlementType == SettlementType.Direct) { payee = IVault(_vaultProxy).getOwner(); __transferShares(_comptrollerProxy, payer, payee, sharesDue); } else if (settlementType == SettlementType.Mint) { payee = IVault(_vaultProxy).getOwner(); __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.Burn) { __burnShares(_comptrollerProxy, payer, sharesDue); } else if (settlementType == SettlementType.MintSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.BurnSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); } else { revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } /// @dev Helper to settle fees that implement a given fee hook function __settleFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private returns (uint256 gav_) { gav_ = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeSettlesOnHook(_fees[i], _hook)) { continue; } gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_); __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } /// @dev Helper to update fees that implement a given fee hook function __updateFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private { uint256 gav = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeUpdatesOnHook(_fees[i], _hook)) { continue; } gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav); IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } /////////////////// // FEES REGISTRY // /////////////////// /// @notice Remove fees from the list of registered fees /// @param _fees Addresses of fees to be deregistered function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "deregisterFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered"); registeredFees.remove(_fees[i]); emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier()); } } /// @notice Add fees to the list of registered fees /// @param _fees Addresses of fees to be registered /// @dev Stores the hooks that a fee implements and whether each implementation uses GAV, /// which fronts the gas for calls to check if a hook is implemented, and guarantees /// that these hook implementation return values do not change post-registration. function registerFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "registerFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered"); registeredFees.add(_fees[i]); IFee feeContract = IFee(_fees[i]); ( FeeHook[] memory implementedHooksForSettle, FeeHook[] memory implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ) = feeContract.implementedHooks(); // Stores the hooks for which each fee implements settle() and update() for (uint256 j; j < implementedHooksForSettle.length; j++) { feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true; } for (uint256 j; j < implementedHooksForUpdate.length; j++) { feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true; } // Stores whether each fee requires GAV during its implementations for settle() and update() if (usesGavOnSettle) { feeToUsesGavOnSettle[_fees[i]] = true; } if (usesGavOnUpdate) { feeToUsesGavOnUpdate[_fees[i]] = true; } emit FeeRegistered( _fees[i], feeContract.identifier(), implementedHooksForSettle, implementedHooksForUpdate, usesGavOnSettle, usesGavOnUpdate ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled fees for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledFees_ An array of enabled fee addresses function getEnabledFeesForFund(address _comptrollerProxy) external view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } /// @notice Get the amount of shares outstanding for a particular fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fee The fee address /// @return sharesOutstanding_ The amount of shares outstanding function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) external view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; } /// @notice Get all registered fees /// @return registeredFees_ A list of all registered fee addresses function getRegisteredFees() external view returns (address[] memory registeredFees_) { registeredFees_ = new address[](registeredFees.length()); for (uint256 i; i < registeredFees_.length; i++) { registeredFees_[i] = registeredFees.at(i); } return registeredFees_; } /// @notice Checks if a fee implements settle() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return settlesOnHook_ True if the fee settles on the given hook function feeSettlesOnHook(address _fee, FeeHook _hook) public view returns (bool settlesOnHook_) { return feeToHookToImplementsSettle[_fee][_hook]; } /// @notice Checks if a fee implements update() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return updatesOnHook_ True if the fee updates on the given hook function feeUpdatesOnHook(address _fee, FeeHook _hook) public view returns (bool updatesOnHook_) { return feeToHookToImplementsUpdate[_fee][_hook]; } /// @notice Checks if a fee uses GAV in its settle() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during settle() implementation function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnSettle[_fee]; } /// @notice Checks if a fee uses GAV in its update() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during update() implementation function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnUpdate[_fee]; } /// @notice Check whether a fee is registered /// @param _fee The address of the fee to check /// @return isRegisteredFee_ True if the fee is registered function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) { return registeredFees.contains(_fee); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; /// @title PermissionedVaultActionMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for extensions that can make permissioned vault calls abstract contract PermissionedVaultActionMixin { /// @notice Adds a tracked asset to the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to add function __addTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.AddTrackedAsset, abi.encode(_asset) ); } /// @notice Grants an allowance to a spender to use a fund's asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function __approveAssetSpender( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.ApproveAssetSpender, abi.encode(_asset, _target, _amount) ); } /// @notice Burns fund shares for a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function __burnShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.BurnShares, abi.encode(_target, _amount) ); } /// @notice Mints fund shares to a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account to which to mint shares /// @param _amount The amount of shares to mint function __mintShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.MintShares, abi.encode(_target, _amount) ); } /// @notice Removes a tracked asset from the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to remove function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.RemoveTrackedAsset, abi.encode(_asset) ); } /// @notice Transfers fund shares from one account to another /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function __transferShares( address _comptrollerProxy, address _from, address _to, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.TransferShares, abi.encode(_from, _to, _amount) ); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function __withdrawAssetTo( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.WithdrawAssetTo, abi.encode(_asset, _target, _amount) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IWETH.sol"; import "../core/fund/comptroller/ComptrollerLib.sol"; import "../extensions/fee-manager/FeeManager.sol"; /// @title FundActionsWrapper Contract /// @author Enzyme Council <[email protected]> /// @notice Logic related to wrapping fund actions, not necessary in the core protocol contract FundActionsWrapper { using SafeERC20 for ERC20; address private immutable FEE_MANAGER; address private immutable WETH_TOKEN; mapping(address => bool) private accountToHasMaxWethAllowance; constructor(address _feeManager, address _weth) public { FEE_MANAGER = _feeManager; WETH_TOKEN = _weth; } /// @dev Needed in case WETH not fully used during exchangeAndBuyShares, /// to unwrap into ETH and refund receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return netShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Accounts for fees outstanding. This is a convenience function for external consumption /// that can be used to determine the cost of purchasing shares at any given point in time. /// It essentially just bundles settling all fees that implement the Continuous hook and then /// looking up the gross share value. function calcNetShareValueForFund(address _comptrollerProxy) external returns (uint256 netShareValue_, bool isValid_) { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); return comptrollerProxyContract.calcGrossShareValue(false); } /// @notice Exchanges ETH into a fund's denomination asset and then buys shares /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _buyer The account for which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH /// @param _exchange The exchange on which to execute the swap to the denomination asset /// @param _exchangeApproveTarget The address that should be given an allowance of WETH /// for the given _exchange /// @param _exchangeData The data with which to call the exchange to execute the swap /// to the denomination asset /// @param _minInvestmentAmount The minimum amount of the denomination asset /// to receive in the trade for investment (not necessary for WETH) /// @return sharesReceivedAmount_ The actual amount of shares received /// @dev Use a reasonable _minInvestmentAmount always, in case the exchange /// does not perform as expected (low incoming asset amount, blend of assets, etc). /// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData, /// and _minInvestmentAmount will be ignored. function exchangeAndBuyShares( address _comptrollerProxy, address _denominationAsset, address _buyer, uint256 _minSharesQuantity, address _exchange, address _exchangeApproveTarget, bytes calldata _exchangeData, uint256 _minInvestmentAmount ) external payable returns (uint256 sharesReceivedAmount_) { // Wrap ETH into WETH IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}(); // If denominationAsset is WETH, can just buy shares directly if (_denominationAsset == WETH_TOKEN) { __approveMaxWethAsNeeded(_comptrollerProxy); return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity); } // Exchange ETH to the fund's denomination asset __approveMaxWethAsNeeded(_exchangeApproveTarget); (bool success, bytes memory returnData) = _exchange.call(_exchangeData); require(success, string(returnData)); // Confirm the amount received in the exchange is above the min acceptable amount uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this)); require( investmentAmount >= _minInvestmentAmount, "exchangeAndBuyShares: _minInvestmentAmount not met" ); // Give the ComptrollerProxy max allowance for its denomination asset as necessary __approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount); // Buy fund shares sharesReceivedAmount_ = __buyShares( _comptrollerProxy, _buyer, investmentAmount, _minSharesQuantity ); // Unwrap and refund any remaining WETH not used in the exchange uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this)); if (remainingWeth > 0) { IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth); (success, returnData) = msg.sender.call{value: remainingWeth}(""); require(success, string(returnData)); } return sharesReceivedAmount_; } /// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout /// any shares outstanding on those fees /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fees The fees for which to run these actions /// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence. /// The caller must pass in the fees that they want to run this logic on. function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund( address _comptrollerProxy, address[] calldata _fees ) external { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees)); } // PUBLIC FUNCTIONS /// @notice Gets all fees that implement the `Continuous` fee hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return continuousFees_ The fees that implement the `Continuous` fee hook function getContinuousFeesForFund(address _comptrollerProxy) public view returns (address[] memory continuousFees_) { FeeManager feeManagerContract = FeeManager(FEE_MANAGER); address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy); // Count the continuous fees uint256 continuousFeesCount; bool[] memory implementsContinuousHook = new bool[](fees.length); for (uint256 i; i < fees.length; i++) { if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) { continuousFeesCount++; implementsContinuousHook[i] = true; } } // Return early if no continuous fees if (continuousFeesCount == 0) { return new address[](0); } // Create continuous fees array continuousFees_ = new address[](continuousFeesCount); uint256 continuousFeesIndex; for (uint256 i; i < fees.length; i++) { if (implementsContinuousHook[i]) { continuousFees_[continuousFeesIndex] = fees[i]; continuousFeesIndex++; } } return continuousFees_; } // PRIVATE FUNCTIONS /// @dev Helper to approve a target with the max amount of an asset, only when necessary function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to approve a target with the max amount of weth, only when necessary. /// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this /// once per target. function __approveMaxWethAsNeeded(address _target) internal { if (!accountHasMaxWethAllowance(_target)) { ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max); accountToHasMaxWethAllowance[_target] = true; } } /// @dev Helper for buying shares function __buyShares( address _comptrollerProxy, address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) private returns (uint256 sharesReceivedAmount_) { address[] memory buyers = new address[](1); buyers[0] = _buyer; uint256[] memory investmentAmounts = new uint256[](1); investmentAmounts[0] = _investmentAmount; uint256[] memory minSharesQuantities = new uint256[](1); minSharesQuantities[0] = _minSharesQuantity; return ComptrollerLib(_comptrollerProxy).buyShares( buyers, investmentAmounts, minSharesQuantities )[0]; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Checks whether an account has the max allowance for WETH /// @param _who The account to check /// @return hasMaxWethAllowance_ True if the account has the max allowance function accountHasMaxWethAllowance(address _who) public view returns (bool hasMaxWethAllowance_) { return accountToHasMaxWethAllowance[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorLib Contract /// @author Enzyme Council <[email protected]> /// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances, /// in which shares requests are manually executed by a permissioned user /// @dev This will not work with a `denominationAsset` that does not transfer /// the exact expected amount or has an elastic supply. contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor { using SafeERC20 for ERC20; using SafeMath for uint256; event RequestCanceled( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestCreated( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecuted( address indexed caller, address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecutorAdded(address indexed account); event RequestExecutorRemoved(address indexed account); struct RequestInfo { uint256 investmentAmount; uint256 minSharesQuantity; } uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes; address private comptrollerProxy; address private denominationAsset; address private fundOwner; mapping(address => RequestInfo) private ownerToRequestInfo; mapping(address => bool) private acctToIsRequestExecutor; mapping(address => uint256) private ownerToLastRequestCancellation; modifier onlyFundOwner() { require(msg.sender == fundOwner, "Only fund owner callable"); _; } /// @notice Initializes a proxy instance that uses this library /// @dev Serves as a per-proxy pseudo-constructor function init(address _comptrollerProxy) external override { require(comptrollerProxy == address(0), "init: Already initialized"); comptrollerProxy = _comptrollerProxy; // Cache frequently-used values that require external calls ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); denominationAsset = comptrollerProxyContract.getDenominationAsset(); fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner(); } /// @notice Cancels the shares request of the caller function cancelRequest() external { RequestInfo memory request = ownerToRequestInfo[msg.sender]; require(request.investmentAmount > 0, "cancelRequest: Request does not exist"); // Delete the request, start the cooldown period, and return the investment asset delete ownerToRequestInfo[msg.sender]; ownerToLastRequestCancellation[msg.sender] = block.timestamp; ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount); emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity); } /// @notice Creates a shares request for the caller /// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external { require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0"); require( ownerToRequestInfo[msg.sender].investmentAmount == 0, "createRequest: The request owner can only create one request before executed or canceled" ); require( ownerToLastRequestCancellation[msg.sender] < block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK), "createRequest: Cannot create request during cancellation cooldown period" ); // Create the Request and take custody of investment asset ownerToRequestInfo[msg.sender] = RequestInfo({ investmentAmount: _investmentAmount, minSharesQuantity: _minSharesQuantity }); ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount); emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity); } /// @notice Executes multiple shares requests /// @param _requestOwners The owners of the pending shares requests function executeRequests(address[] calldata _requestOwners) external { require( msg.sender == fundOwner || isRequestExecutor(msg.sender), "executeRequests: Invalid caller" ); require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty"); ( address[] memory buyers, uint256[] memory investmentAmounts, uint256[] memory minSharesQuantities, uint256 totalInvestmentAmount ) = __convertRequestsToBuySharesParams(_requestOwners); // Since ComptrollerProxy instances are fully trusted, // we can approve them with the max amount of the denomination asset, // and only top the approval back to max if ever necessary. address comptrollerProxyCopy = comptrollerProxy; ERC20 denominationAssetContract = ERC20(denominationAsset); if ( denominationAssetContract.allowance(address(this), comptrollerProxyCopy) < totalInvestmentAmount ) { denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max); } ComptrollerLib(comptrollerProxyCopy).buyShares( buyers, investmentAmounts, minSharesQuantities ); } /// @dev Helper to convert raw shares requests into the format required by buyShares(). /// It also removes any empty requests, which is necessary to prevent a DoS attack where a user /// cancels their request earlier in the same block (can be repeated from multiple accounts). /// This function also removes shares requests and fires success events as it loops through them. function __convertRequestsToBuySharesParams(address[] memory _requestOwners) private returns ( address[] memory buyers_, uint256[] memory investmentAmounts_, uint256[] memory minSharesQuantities_, uint256 totalInvestmentAmount_ ) { uint256 existingRequestsCount = _requestOwners.length; uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length); // Loop through once to get the count of existing requests for (uint256 i; i < _requestOwners.length; i++) { allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount; if (allInvestmentAmounts[i] == 0) { existingRequestsCount--; } } // Loop through a second time to format requests for buyShares(), // and to delete the requests and emit events early so no further looping is needed. buyers_ = new address[](existingRequestsCount); investmentAmounts_ = new uint256[](existingRequestsCount); minSharesQuantities_ = new uint256[](existingRequestsCount); uint256 existingRequestsIndex; for (uint256 i; i < _requestOwners.length; i++) { if (allInvestmentAmounts[i] == 0) { continue; } buyers_[existingRequestsIndex] = _requestOwners[i]; investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i]; minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]] .minSharesQuantity; totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]); delete ownerToRequestInfo[_requestOwners[i]]; emit RequestExecuted( msg.sender, buyers_[existingRequestsIndex], investmentAmounts_[existingRequestsIndex], minSharesQuantities_[existingRequestsIndex] ); existingRequestsIndex++; } return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_); } /////////////////////////////// // REQUEST EXECUTOR REGISTRY // /////////////////////////////// /// @notice Adds accounts to request executors /// @param _requestExecutors Accounts to add function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( !isRequestExecutor(_requestExecutors[i]), "addRequestExecutors: Value already set" ); require( _requestExecutors[i] != fundOwner, "addRequestExecutors: The fund owner cannot be added" ); acctToIsRequestExecutor[_requestExecutors[i]] = true; emit RequestExecutorAdded(_requestExecutors[i]); } } /// @notice Removes accounts from request executors /// @param _requestExecutors Accounts to remove function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( isRequestExecutor(_requestExecutors[i]), "removeRequestExecutors: Account is not a request executor" ); acctToIsRequestExecutor[_requestExecutors[i]] = false; emit RequestExecutorRemoved(_requestExecutors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of `comptrollerProxy` variable /// @return comptrollerProxy_ The `comptrollerProxy` variable value function getComptrollerProxy() external view returns (address comptrollerProxy_) { return comptrollerProxy; } /// @notice Gets the value of `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the value of `fundOwner` variable /// @return fundOwner_ The `fundOwner` variable value function getFundOwner() external view returns (address fundOwner_) { return fundOwner; } /// @notice Gets the request info of a user /// @param _requestOwner The address of the user that creates the request /// @return requestInfo_ The request info created by the user function getSharesRequestInfoForOwner(address _requestOwner) external view returns (RequestInfo memory requestInfo_) { return ownerToRequestInfo[_requestOwner]; } /// @notice Checks whether an account is a request executor /// @param _who The account to check /// @return isRequestExecutor_ True if _who is a request executor function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) { return acctToIsRequestExecutor[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAuthUserExecutedSharesRequestor Interface /// @author Enzyme Council <[email protected]> interface IAuthUserExecutedSharesRequestor { function init(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./AuthUserExecutedSharesRequestorProxy.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorFactory Contract /// @author Enzyme Council <[email protected]> /// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances contract AuthUserExecutedSharesRequestorFactory { event SharesRequestorProxyDeployed( address indexed comptrollerProxy, address sharesRequestorProxy ); address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; address private immutable DISPATCHER; mapping(address => address) private comptrollerProxyToSharesRequestorProxy; constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public { AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib; DISPATCHER = _dispatcher; } /// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance /// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy /// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy function deploySharesRequestorProxy(address _comptrollerProxy) external returns (address sharesRequestorProxy_) { // Confirm fund is genuine VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy()); require( vaultProxyContract.getAccessor() == _comptrollerProxy, "deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy" ); require( IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) != address(0), "deploySharesRequestorProxy: Not a genuine fund" ); // Validate that the caller is the fund owner require( msg.sender == vaultProxyContract.getOwner(), "deploySharesRequestorProxy: Only fund owner callable" ); // Validate that a proxy does not already exist require( comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0), "deploySharesRequestorProxy: Proxy already exists" ); // Deploy the proxy bytes memory constructData = abi.encodeWithSelector( IAuthUserExecutedSharesRequestor.init.selector, _comptrollerProxy ); sharesRequestorProxy_ = address( new AuthUserExecutedSharesRequestorProxy( constructData, AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB ) ); comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_; emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_); return sharesRequestorProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable /// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value function getAuthUserExecutedSharesRequestorLib() external view returns (address authUserExecutedSharesRequestorLib_) { return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; } /// @notice Gets the value of the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy /// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy) external view returns (address sharesRequestorProxy_) { return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/Proxy.sol"; contract AuthUserExecutedSharesRequestorProxy is Proxy { constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib) public Proxy(_constructData, _authUserExecutedSharesRequestorLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Proxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all Proxy instances /// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract Proxy { constructor(bytes memory _constructData, address _contractLogic) public { assembly { sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } fallback() external payable { assembly { let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/Proxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is Proxy { constructor(bytes memory _constructData, address _comptrollerLib) public Proxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/utils/IMigrationHookHandler.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler { event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData, bool indexed forMigration ); event NewFundCreated( address indexed creator, address comptrollerProxy, address vaultProxy, address indexed fundOwner, string fundName, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData ); event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus); event VaultCallDeregistered(address indexed contractAddress, bytes4 selector); event VaultCallRegistered(address indexed contractAddress, bytes4 selector); // Constants address private immutable CREATOR; address private immutable DISPATCHER; address private immutable VAULT_LIB; // Pseudo-constants (can only be set once) address private comptrollerLib; // Storage ReleaseStatus private releaseStatus; mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall; mapping(address => address) private pendingComptrollerProxyToCreator; modifier onlyLiveRelease() { require(releaseStatus == ReleaseStatus.Live, "Release is not Live"); _; } modifier onlyMigrator(address _vaultProxy) { require( IVault(_vaultProxy).canMigrate(msg.sender), "Only a permissioned migrator can call this function" ); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) { require( msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy], "Only the ComptrollerProxy creator can call this function" ); _; } constructor( address _dispatcher, address _vaultLib, address[] memory _vaultCallContracts, bytes4[] memory _vaultCallSelectors ) public { if (_vaultCallContracts.length > 0) { __registerVaultCalls(_vaultCallContracts, _vaultCallSelectors); } CREATOR = msg.sender; DISPATCHER = _dispatcher; VAULT_LIB = _vaultLib; } ///////////// // GENERAL // ///////////// /// @notice Sets the comptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address /// @dev Can only be set once function setComptrollerLib(address _comptrollerLib) external onlyOwner { require( comptrollerLib == address(0), "setComptrollerLib: This value can only be set once" ); comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the status of the protocol to a new state /// @param _nextStatus The next status state to set function setReleaseStatus(ReleaseStatus _nextStatus) external { require( msg.sender == IDispatcher(DISPATCHER).getOwner(), "setReleaseStatus: Only the Dispatcher owner can call this function" ); require( _nextStatus != ReleaseStatus.PreLaunch, "setReleaseStatus: Cannot return to PreLaunch status" ); require( comptrollerLib != address(0), "setReleaseStatus: Can only set the release status when comptrollerLib is set" ); ReleaseStatus prevStatus = releaseStatus; require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status"); releaseStatus = _nextStatus; emit ReleaseStatusSet(prevStatus, _nextStatus); } /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the /// contract's deployer, for convenience in setting up configuration. /// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council) /// sets the releaseStatus to `Live`. function getOwner() public view override returns (address owner_) { if (releaseStatus == ReleaseStatus.PreLaunch) { return CREATOR; } return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous /// release can migrate in a subsequent step /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigratedFundConfig( address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_) { comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, true ); pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender; return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { return __createNewFund( _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); } /// @dev Helper to avoid the stack-too-deep error during createNewFund function __createNewFund( address _fundOwner, string memory _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private returns (address comptrollerProxy_, address vaultProxy_) { require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty"); comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, false ); vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy( VAULT_LIB, _fundOwner, comptrollerProxy_, _fundName ); IComptroller(comptrollerProxy_).activate(vaultProxy_, false); emit NewFundCreated( msg.sender, comptrollerProxy_, vaultProxy_, _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); return (comptrollerProxy_, vaultProxy_); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData, bool _forMigration ) private returns (address comptrollerProxy_) { require( _denominationAsset != address(0), "__deployComptrollerProxy: _denominationAsset cannot be empty" ); bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib)); if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) { IComptroller(comptrollerProxy_).configureExtensions( _feeManagerConfigData, _policyManagerConfigData ); } emit ComptrollerProxyDeployed( msg.sender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, _forMigration ); return comptrollerProxy_; } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigration(address _vaultProxy) external { __cancelMigration(_vaultProxy, false); } /// @notice Cancels fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigrationEmergency(address _vaultProxy) external { __cancelMigration(_vaultProxy, true); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigration(address _vaultProxy) external { __executeMigration(_vaultProxy, false); } /// @notice Executes fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigrationEmergency(address _vaultProxy) external { __executeMigration(_vaultProxy, true); } /// @dev Unimplemented function invokeMigrationInCancelHook( address, address, address, address ) external virtual override { return; } /// @notice Signal a fund migration /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigration(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, false); } /// @notice Signal a fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, true); } /// @dev Helper to cancel a migration function __cancelMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure); } /// @dev Helper to execute a migration function __executeMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(DISPATCHER); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassFailure); IComptroller(comptrollerProxy).activate(_vaultProxy, true); delete pendingComptrollerProxyToCreator[comptrollerProxy]; } /// @dev Helper to signal a migration function __signalMigration( address _vaultProxy, address _comptrollerProxy, bool _bypassFailure ) private onlyLiveRelease onlyPendingComptrollerProxyCreator(_comptrollerProxy) onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).signalMigration( _vaultProxy, _comptrollerProxy, VAULT_LIB, _bypassFailure ); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override { if (_hook != MigrationOutHook.PreMigrate) { return; } require( msg.sender == DISPATCHER, "postMigrateOriginHook: Only Dispatcher can call this function" ); // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config IComptroller(comptrollerProxy).destruct(); } ////////////// // REGISTRY // ////////////// /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i]), "deregisterVaultCalls: Call not registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); __registerVaultCalls(_contracts, _selectors); } /// @dev Helper to register allowed vault calls function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors) private { require( _contracts.length == _selectors.length, "__registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i]), "__registerVaultCalls: Call already registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() external view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() external view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the creator of a pending ComptrollerProxy /// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator function getPendingComptrollerProxyCreator(address _comptrollerProxy) external view returns (address pendingComptrollerProxyCreator_) { return pendingComptrollerProxyToCreator[_comptrollerProxy]; } /// @notice Gets the `releaseStatus` variable value /// @return status_ The `releaseStatus` variable value function getReleaseStatus() external view override returns (ReleaseStatus status_) { return releaseStatus; } /// @notice Gets the `VAULT_LIB` variable value /// @return vaultLib_ The `VAULT_LIB` variable value function getVaultLib() external view returns (address vaultLib_) { return VAULT_LIB; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall(address _contract, bytes4 _selector) public view override returns (bool isRegistered_) { return contractToSelectorToIsRegisteredVaultCall[_contract][_selector]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[email protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../utils/AddressArrayLib.sol"; import "../../utils/AssetFinalityResolver.sol"; import "../policy-manager/IPolicyManager.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./integrations/IIntegrationAdapter.sol"; import "./IIntegrationManager.sol"; /// @title IntegrationManager /// @author Enzyme Council <[email protected]> /// @notice Extension to handle DeFi integration actions for funds contract IntegrationManager is IIntegrationManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin, AssetFinalityResolver { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AdapterDeregistered(address indexed adapter, string indexed identifier); event AdapterRegistered(address indexed adapter, string indexed identifier); event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account); event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account); event CallOnIntegrationExecutedForFund( address indexed comptrollerProxy, address vaultProxy, address caller, address indexed adapter, bytes4 indexed selector, bytes integrationData, address[] incomingAssets, uint256[] incomingAssetAmounts, address[] outgoingAssets, uint256[] outgoingAssetAmounts ); address private immutable DERIVATIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; EnumerableSet.AddressSet private registeredAdapters; mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser; constructor( address _fundDeployer, address _policyManager, address _derivativePriceFeed, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public FundDeployerOwnerMixin(_fundDeployer) AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; POLICY_MANAGER = _policyManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } ///////////// // GENERAL // ///////////// /// @notice Activates the extension by storing the VaultProxy function activateForFund(bool) external override { __setValidatedVaultProxy(msg.sender); } /// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The user to authorize function addAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, true); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true; emit AuthUserAddedForFund(_comptrollerProxy, _who); } /// @notice Deactivate the extension by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; } /// @notice Removes an authorized user from the IntegrationManager for the given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The authorized user to remove function removeAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, false); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false; emit AuthUserRemovedForFund(_comptrollerProxy, _who); } /// @notice Checks whether an account is an authorized IntegrationManager user for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The account to check /// @return isAuthUser_ True if the account is an authorized user or the fund owner function isAuthUserForFund(address _comptrollerProxy, address _who) public view returns (bool isAuthUser_) { return comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] || _who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); } /// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser function __validateSetAuthUser( address _comptrollerProxy, address _who, bool _nextIsAuthUser ) private view { require( comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0), "__validateSetAuthUser: Fund has not been activated" ); address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); require( msg.sender == fundOwner, "__validateSetAuthUser: Only the fund owner can call this function" ); require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner"); if (_nextIsAuthUser) { require( !comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is already an authorized user" ); } else { require( comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is not an authorized user" ); } } /////////////////////////////// // CALL-ON-EXTENSION ACTIONS // /////////////////////////////// /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _caller The user who called for this action /// @param _actionId An ID representing the desired action /// @param _callArgs The encoded args for the action function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external override { // Since we validate and store the ComptrollerProxy-VaultProxy pairing during // activateForFund(), this function does not require further validation of the // sending ComptrollerProxy address vaultProxy = comptrollerProxyToVaultProxy[msg.sender]; require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active"); require( isAuthUserForFund(msg.sender, _caller), "receiveCallFromComptroller: Not an authorized user" ); // Dispatch the action if (_actionId == 0) { __callOnIntegration(_caller, vaultProxy, _callArgs); } else if (_actionId == 1) { __addZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else if (_actionId == 2) { __removeZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @dev Adds assets with a zero balance as tracked assets of the fund function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); for (uint256 i; i < assets.length; i++) { require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__addZeroBalanceTrackedAssets: Balance is not zero" ); __addTrackedAsset(msg.sender, assets[i]); } } /// @dev Removes assets with a zero balance from tracked assets of the fund function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); address denominationAsset = IComptroller(msg.sender).getDenominationAsset(); for (uint256 i; i < assets.length; i++) { require( assets[i] != denominationAsset, "__removeZeroBalanceTrackedAssets: Cannot remove denomination asset" ); require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__removeZeroBalanceTrackedAssets: Balance is not zero" ); __removeTrackedAsset(msg.sender, assets[i]); } } ///////////////////////// // CALL ON INTEGRATION // ///////////////////////// /// @notice Universal method for calling third party contract functions through adapters /// @param _caller The caller of this function via the ComptrollerProxy /// @param _vaultProxy The VaultProxy of the fund /// @param _callArgs The encoded args for this function /// - _adapter Adapter of the integration on which to execute a call /// - _selector Method selector of the adapter method to execute /// - _integrationData Encoded arguments specific to the adapter /// @dev msg.sender is the ComptrollerProxy. /// Refer to specific adapter to see how to encode its arguments. function __callOnIntegration( address _caller, address _vaultProxy, bytes memory _callArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); __preCoIHook(adapter, selector); /// Passing decoded _callArgs leads to stack-too-deep error ( address[] memory incomingAssets, uint256[] memory incomingAssetAmounts, address[] memory outgoingAssets, uint256[] memory outgoingAssetAmounts ) = __callOnIntegrationInner(_vaultProxy, _callArgs); __postCoIHook( adapter, selector, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); __emitCoIEvent( _vaultProxy, _caller, adapter, selector, integrationData, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); } /// @dev Helper to execute the bulk of logic of callOnIntegration. /// Avoids the stack-too-deep-error. function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { ( address[] memory expectedIncomingAssets, uint256[] memory preCallIncomingAssetBalances, uint256[] memory minIncomingAssetAmounts, SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory maxSpendAssetAmounts, uint256[] memory preCallSpendAssetBalances ) = __preProcessCoI(vaultProxy, _callArgs); __executeCoI( vaultProxy, _callArgs, abi.encode( spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, expectedIncomingAssets ) ); ( incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_ ) = __postProcessCoI( vaultProxy, expectedIncomingAssets, preCallIncomingAssetBalances, minIncomingAssetAmounts, spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, preCallSpendAssetBalances ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to decode CoI args function __decodeCallOnIntegrationArgs(bytes memory _callArgs) private pure returns ( address adapter_, bytes4 selector_, bytes memory integrationData_ ) { return abi.decode(_callArgs, (address, bytes4, bytes)); } /// @dev Helper to emit the CallOnIntegrationExecuted event. /// Avoids stack-too-deep error. function __emitCoIEvent( address _vaultProxy, address _caller, address _adapter, bytes4 _selector, bytes memory _integrationData, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { emit CallOnIntegrationExecutedForFund( msg.sender, _vaultProxy, _caller, _adapter, _selector, _integrationData, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ); } /// @dev Helper to execute a call to an integration /// @dev Avoids stack-too-deep error function __executeCoI( address _vaultProxy, bytes memory _callArgs, bytes memory _encodedAssetTransferArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); (bool success, bytes memory returnData) = adapter.call( abi.encodeWithSelector( selector, _vaultProxy, integrationData, _encodedAssetTransferArgs ) ); require(success, string(returnData)); } /// @dev Helper to get the vault's balance of a particular asset function __getVaultAssetBalance(address _vaultProxy, address _asset) private view returns (uint256) { return ERC20(_asset).balanceOf(_vaultProxy); } /// @dev Helper to check if an asset is supported function __isSupportedAsset(address _asset) private view returns (bool isSupported_) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) || IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset); } /// @dev Helper for the actions to take on external contracts prior to executing CoI function __preCoIHook(address _adapter, bytes4 _selector) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PreCallOnIntegration, abi.encode(_adapter, _selector) ); } /// @dev Helper for the internal actions to take prior to executing CoI function __preProcessCoI(address _vaultProxy, bytes memory _callArgs) private returns ( address[] memory expectedIncomingAssets_, uint256[] memory preCallIncomingAssetBalances_, uint256[] memory minIncomingAssetAmounts_, SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory preCallSpendAssetBalances_ ) { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered"); // Note that expected incoming and spend assets are allowed to overlap // (e.g., a fee for the incomingAsset charged in a spend asset) ( spendAssetsHandleType_, spendAssets_, maxSpendAssetAmounts_, expectedIncomingAssets_, minIncomingAssetAmounts_ ) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData); require( spendAssets_.length == maxSpendAssetAmounts_.length, "__preProcessCoI: Spend assets arrays unequal" ); require( expectedIncomingAssets_.length == minIncomingAssetAmounts_.length, "__preProcessCoI: Incoming assets arrays unequal" ); require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset"); require( expectedIncomingAssets_.isUniqueSet(), "__preProcessCoI: Duplicate incoming asset" ); IVault vaultProxyContract = IVault(_vaultProxy); preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length); for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) { require( expectedIncomingAssets_[i] != address(0), "__preProcessCoI: Empty incoming asset address" ); require( minIncomingAssetAmounts_[i] > 0, "__preProcessCoI: minIncomingAssetAmount must be >0" ); require( __isSupportedAsset(expectedIncomingAssets_[i]), "__preProcessCoI: Non-receivable incoming asset" ); // Get pre-call balance of each incoming asset. // If the asset is not tracked by the fund, allow the balance to default to 0. if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) { // We do not require incoming asset finality, but we attempt to finalize so that // the final incoming asset amount is more accurate. There is no need to finalize // post-tx. preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, expectedIncomingAssets_[i], false ); } } // Get pre-call balances of spend assets and grant approvals to adapter preCallSpendAssetBalances_ = new uint256[](spendAssets_.length); for (uint256 i = 0; i < spendAssets_.length; i++) { require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset"); require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount"); // A spend asset must either be a tracked asset of the fund or a supported asset, // in order to prevent seeding the fund with a malicious token and performing arbitrary // actions within an adapter. require( vaultProxyContract.isTrackedAsset(spendAssets_[i]) || __isSupportedAsset(spendAssets_[i]), "__preProcessCoI: Non-spendable spend asset" ); // If spend asset is also an incoming asset, no need to record its balance if (!expectedIncomingAssets_.contains(spendAssets_[i])) { // By requiring spend asset finality before CoI, we will know whether or // not the asset balance was entirely spent during the call. There is no need // to finalize post-tx. preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, spendAssets_[i], true ); } // Grant spend assets access to the adapter. // Note that spendAssets_ is already asserted to a unique set. if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) { // Use exact approve amount rather than increasing allowances, // because all adapters finish their actions atomically. __approveAssetSpender( msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i] ); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) { __withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) { __removeTrackedAsset(msg.sender, spendAssets_[i]); } } } /// @dev Helper for the actions to take on external contracts after executing CoI function __postCoIHook( address _adapter, bytes4 _selector, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PostCallOnIntegration, abi.encode( _adapter, _selector, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ) ); } /// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI function __postProcessCoI( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { address[] memory increasedSpendAssets; uint256[] memory increasedSpendAssetAmounts; ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets, increasedSpendAssetAmounts ) = __reconcileCoISpendAssets( _vaultProxy, _spendAssetsHandleType, _spendAssets, _maxSpendAssetAmounts, _preCallSpendAssetBalances ); (incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets( _vaultProxy, _expectedIncomingAssets, _preCallIncomingAssetBalances, _minIncomingAssetAmounts, increasedSpendAssets, increasedSpendAssetAmounts ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to process incoming asset balance changes. /// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets". function __reconcileCoIIncomingAssets( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, address[] memory _increasedSpendAssets, uint256[] memory _increasedSpendAssetAmounts ) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) { // Incoming assets = expected incoming assets + spend assets with increased balances uint256 incomingAssetsCount = _expectedIncomingAssets.length.add( _increasedSpendAssets.length ); // Calculate and validate incoming asset amounts incomingAssets_ = new address[](incomingAssetsCount); incomingAssetAmounts_ = new uint256[](incomingAssetsCount); for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) { uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i]) .sub(_preCallIncomingAssetBalances[i]); require( balanceDiff >= _minIncomingAssetAmounts[i], "__reconcileCoIAssets: Received incoming asset less than expected" ); // Even if the asset's previous balance was >0, it might not have been tracked __addTrackedAsset(msg.sender, _expectedIncomingAssets[i]); incomingAssets_[i] = _expectedIncomingAssets[i]; incomingAssetAmounts_[i] = balanceDiff; } // Append increaseSpendAssets to incomingAsset vars if (_increasedSpendAssets.length > 0) { uint256 incomingAssetIndex = _expectedIncomingAssets.length; for (uint256 i = 0; i < _increasedSpendAssets.length; i++) { incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i]; incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i]; incomingAssetIndex++; } } return (incomingAssets_, incomingAssetAmounts_); } /// @dev Helper to process spend asset balance changes. /// "outgoingAssets" are the spend assets with a decrease in balance. /// "increasedSpendAssets" are the spend assets with an unexpected increase in balance. /// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of /// the spendAsset, which would be transferred to the fund at the end of the tx. function __reconcileCoISpendAssets( address _vaultProxy, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_, address[] memory increasedSpendAssets_, uint256[] memory increasedSpendAssetAmounts_ ) { // Determine spend asset balance changes uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length); uint256 outgoingAssetsCount; uint256 increasedSpendAssetsCount; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssetsCount++; continue; } // Determine if the asset is outgoing or incoming, and store the post-balance for later use postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]); // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { outgoingAssetsCount++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetsCount++; } } // Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance) outgoingAssets_ = new address[](outgoingAssetsCount); outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount); increasedSpendAssets_ = new address[](increasedSpendAssetsCount); increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount); uint256 outgoingAssetsIndex; uint256 increasedSpendAssetsIndex; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset. if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately. // No need to validate the max spend asset amount. if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; outgoingAssetsIndex++; continue; } // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { if (postCallSpendAssetBalances[i] == 0) { __removeTrackedAsset(msg.sender, _spendAssets[i]); outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; } else { outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub( postCallSpendAssetBalances[i] ); } require( outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i], "__reconcileCoISpendAssets: Spent amount greater than expected" ); outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetsIndex++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i] .sub(_preCallSpendAssetBalances[i]); increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i]; increasedSpendAssetsIndex++; } } return ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets_, increasedSpendAssetAmounts_ ); } /////////////////////////// // INTEGRATIONS REGISTRY // /////////////////////////// /// @notice Remove integration adapters from the list of registered adapters /// @param _adapters Addresses of adapters to be deregistered function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require( adapterIsRegistered(_adapters[i]), "deregisterAdapters: Adapter is not registered" ); registeredAdapters.remove(_adapters[i]); emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /// @notice Add integration adapters to the list of registered adapters /// @param _adapters Addresses of adapters to be registered function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty"); require( !adapterIsRegistered(_adapters[i]), "registerAdapters: Adapter already registered" ); registeredAdapters.add(_adapters[i]); emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks if an integration adapter is registered /// @param _adapter The adapter to check /// @return isRegistered_ True if the adapter is registered function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) { return registeredAdapters.contains(_adapter); } /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets all registered integration adapters /// @return registeredAdaptersArray_ A list of all registered integration adapters function getRegisteredAdapters() external view returns (address[] memory registeredAdaptersArray_) { registeredAdaptersArray_ = new address[](registeredAdapters.length()); for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) { registeredAdaptersArray_[i] = registeredAdapters.at(i); } return registeredAdaptersArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../utils/AdapterBase.sol"; /// @title SynthetixAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Synthetix contract SynthetixAdapter is AdapterBase { address private immutable ORIGINATOR; address private immutable SYNTHETIX; address private immutable SYNTHETIX_PRICE_FEED; bytes32 private immutable TRACKING_CODE; constructor( address _integrationManager, address _synthetixPriceFeed, address _originator, address _synthetix, bytes32 _trackingCode ) public AdapterBase(_integrationManager) { ORIGINATOR = _originator; SYNTHETIX = _synthetix; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; TRACKING_CODE = _trackingCode; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "SYNTHETIX"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.None, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Synthetix /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address incomingAsset, , address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address[] memory synths = new address[](2); synths[0] = outgoingAsset; synths[1] = incomingAsset; bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED) .getCurrencyKeysForSynths(synths); ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking( _vaultProxy, currencyKeys[0], outgoingAssetAmount, currencyKeys[1], ORIGINATOR, TRACKING_CODE ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ORIGINATOR` variable /// @return originator_ The `ORIGINATOR` variable value function getOriginator() external view returns (address originator_) { return ORIGINATOR; } /// @notice Gets the `SYNTHETIX` variable /// @return synthetix_ The `SYNTHETIX` variable value function getSynthetix() external view returns (address synthetix_) { return SYNTHETIX; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } /// @notice Gets the `TRACKING_CODE` variable /// @return trackingCode_ The `TRACKING_CODE` variable value function getTrackingCode() external view returns (bytes32 trackingCode_) { return TRACKING_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; import "../../utils/DispatcherOwnerMixin.sol"; import "./IPrimitivePriceFeed.sol"; /// @title ChainlinkPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); event PrimitiveUpdated( address indexed primitive, address prevAggregator, address nextAggregator ); event StalePrimitiveRemoved(address indexed primitive); event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; address private immutable WETH_TOKEN; address private ethUsdAggregator; uint256 private staleRateThreshold; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor( address _dispatcher, address _wethToken, address _ethUsdAggregator, address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) public DispatcherOwnerMixin(_dispatcher) { WETH_TOKEN = _wethToken; staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer __setEthUsdAggregator(_ethUsdAggregator); if (_primitives.length > 0) { __addPrimitives(_primitives, _aggregators, _rateAssets); } } // EXTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid function calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) public view override returns (uint256 quoteAssetAmount_, bool isValid_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); if (baseAssetRate <= 0) { return (0, false); } int256 quoteAssetRate = __getLatestRateData(_quoteAsset); if (quoteAssetRate <= 0) { return (0, false); } (quoteAssetAmount_, isValid_) = __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); return (quoteAssetAmount_, isValid_); } /// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid /// @dev Live and canonical values are the same for Chainlink function calcLiveValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) external view override returns (uint256 quoteAssetAmount_, bool isValid_) { return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_, bool isValid_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return ( __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ), true ); } int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer(); if (ethPerUsdRate <= 0) { return (0, false); } // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return ( __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return ( __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == WETH_TOKEN) { return int256(ETH_UNIT); } address aggregator = primitiveToAggregatorInfo[_primitive].aggregator; require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); return IChainlinkAggregator(aggregator).latestAnswer(); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) private { address prevEthUsdAggregator = ethUsdAggregator; require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyDispatcherOwner { require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty"); __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner { require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0), "removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } /// @notice Removes stale primitives from the feed /// @param _primitives The stale primitives to remove /// @dev Callable by anybody function removeStalePrimitives(address[] calldata _primitives) external { require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive"); require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale"); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit StalePrimitiveRemoved(_primitives[i]); } } /// @notice Sets the `staleRateThreshold` variable /// @param _nextStaleRateThreshold The next `staleRateThreshold` value function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner { uint256 prevStaleRateThreshold = staleRateThreshold; require( _nextStaleRateThreshold != prevStaleRateThreshold, "__setStaleRateThreshold: Value already set" ); staleRateThreshold = _nextStaleRateThreshold; emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold); } /// @notice Updates the aggregators for given primitives /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators) external onlyDispatcherOwner { require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty"); require( _primitives.length == _aggregators.length, "updatePrimitives: Unequal _primitives and _aggregators array lengths" ); for (uint256 i; i < _primitives.length; i++) { address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added"); require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set"); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i]; emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]); } } /// @notice Checks whether the current rate is considered stale for the specified aggregator /// @param _aggregator The Chainlink aggregator of which to check staleness /// @return rateIsStale_ True if the rate is considered stale function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) { return IChainlinkAggregator(_aggregator).latestTimestamp() < block.timestamp.sub(staleRateThreshold); } /// @dev Helper to add primitives to the feed function __addPrimitives( address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) private { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i = 0; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { require(_aggregator != address(0), "__validateAggregator: Empty _aggregator"); require( IChainlinkAggregator(_aggregator).latestAnswer() > 0, "__validateAggregator: No rate detected" ); require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregatorInfo variable value for a primitive /// @param _primitive The primitive asset for which to get the aggregatorInfo value /// @return aggregatorInfo_ The aggregatorInfo value function getAggregatorInfoForPrimitive(address _primitive) external view returns (AggregatorInfo memory aggregatorInfo_) { return primitiveToAggregatorInfo[_primitive]; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() external view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the `staleRateThreshold` variable value /// @return staleRateThreshold_ The `staleRateThreshold` variable value function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) { return staleRateThreshold; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == WETH_TOKEN) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == WETH_TOKEN) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; /// @dev This contract acts as a centralized rate provider for mocks. /// Suited for a dev environment, it doesn't take into account gas costs. contract CentralizedRateProvider is Ownable { using SafeMath for uint256; address private immutable WETH; uint256 private maxDeviationPerSender; // Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env). address private valueInterpreter; address private aggregateDerivativePriceFeed; address private primitivePriceFeed; constructor(address _weth, uint256 _maxDeviationPerSender) public { maxDeviationPerSender = _maxDeviationPerSender; WETH = _weth; } /// @dev Calculates the value of a _baseAsset relative to a _quoteAsset. /// Label to ValueInterprete's calcLiveAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public returns (uint256 value_) { uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals()); uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals()); // 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) { (value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, _amount, _quoteAsset ); return value_; } // 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) { (uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, 10**uint256(ERC20(_quoteAsset).decimals()), _baseAsset ); uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate); value_ = _amount.mul(rate).div(baseDecimalsRate); return value_; } // 3. If both assets are derivatives, calculate the rate against ETH. (uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, baseDecimalsRate, WETH ); (uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, quoteDecimalsRate, WETH ); value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div( baseDecimalsRate ); return value_; } /// @dev Calculates a randomized live value of an asset /// Aggregation of two randomization seeds: msg.sender, and by block.number. function calcLiveAssetValueRandomized( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); // Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)] uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress( liveAssetValue, msg.sender, maxDeviationPerSender ); // Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)] value_ = __calcValueRandomizedByUint( senderRandomizedValue_, block.number, _maxDeviationPerBlock ); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness function calcLiveAssetValueRandomizedByBlockNumber( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness function calcLiveAssetValueRandomizedBySender( address _baseAsset, uint256 _amount, address _quoteAsset ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender); return value_; } function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner { maxDeviationPerSender = _maxDeviationPerSender; } /// @dev Connector from release environment, inject price variables into the provider. function setReleasePriceAddresses( address _valueInterpreter, address _aggregateDerivativePriceFeed, address _primitivePriceFeed ) external onlyOwner { valueInterpreter = _valueInterpreter; aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed; primitivePriceFeed = _primitivePriceFeed; } // PRIVATE FUNCTIONS /// @dev Calculates a a pseudo-randomized value as a seed an address function __calcValueRandomizedByAddress( uint256 _meanValue, address _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Value between [0, 100] uint256 senderRandomFactor = uint256(uint8(_seed)) .mul(100) .div(256) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation); return value_; } /// @dev Calculates a a pseudo-randomized value as a seed an uint256 function __calcValueRandomizedByUint( uint256 _meanValue, uint256 _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Depending on the _seed number, it will be one of {20, 40, 60, 80, 100} uint256 randomFactor = (_seed.mod(2).mul(20)) .add((_seed.mod(3).mul(40))) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation); return value_; } /// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation) /// TODO: Refactor to use 18 decimal precision function __calcDeviatedValue( uint256 _meanValue, uint256 _offset, uint256 _maxDeviation ) private pure returns (uint256 value_) { return _meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub( _meanValue.mul(_maxDeviation).div(uint256(100)) ); } /////////////////// // STATE GETTERS // /////////////////// function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) { return maxDeviationPerSender; } function getValueInterpreter() public view returns (address valueInterpreter_) { return valueInterpreter; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IUniswapV2Pair.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; /// @dev This price source mocks the integration with Uniswap Pair /// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/> contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) { using SafeMath for uint256; address private immutable TOKEN_0; address private immutable TOKEN_1; address private immutable CENTRALIZED_RATE_PROVIDER; constructor( address _centralizedRateProvider, address _token0, address _token1 ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; TOKEN_0 = _token0; TOKEN_1 = _token1; } /// @dev returns reserves for each token on the Uniswap Pair /// Reserves will be used to calculate the pair price /// Inherited from IUniswapV2Pair function getReserves() external returns ( uint112 reserve0_, uint112 reserve1_, uint32 blockTimestampLast_ ) { uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this)); reserve0_ = uint112(baseAmount); reserve1_ = uint112( CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN_0, baseAmount, TOKEN_1 ) ); return (reserve0_, reserve1_, blockTimestampLast_); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Inherited from IUniswapV2Pair function token0() public view returns (address) { return TOKEN_0; } /// @dev Inherited from IUniswapV2Pair function token1() public view returns (address) { return TOKEN_1; } /// @dev Inherited from IUniswapV2Pair function kLast() public pure returns (uint256) { return 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MockToken is ERC20Burnable, Ownable { using SafeMath for uint256; mapping(address => bool) private addressToIsMinter; modifier onlyMinter() { require( addressToIsMinter[msg.sender] || owner() == msg.sender, "msg.sender is not owner or minter" ); _; } constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); _mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals))); } function mintFor(address _who, uint256 _amount) external onlyMinter { _mint(_who, _amount); } function mint(uint256 _amount) external onlyMinter { _mint(msg.sender, _amount); } function addMinters(address[] memory _minters) public onlyOwner { for (uint256 i = 0; i < _minters.length; i++) { addressToIsMinter[_minters[i]] = true; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @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); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../release/core/fund/comptroller/ComptrollerLib.sol"; import "./MockToken.sol"; /// @title MockReentrancyToken Contract /// @author Enzyme Council <[email protected]> /// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) { bool public bad; address public comptrollerProxy; function makeItReentracyToken(address _comptrollerProxy) external { bad = true; comptrollerProxy = _comptrollerProxy; } function transfer(address recipient, uint256 amount) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).redeemShares(); } else { _transfer(_msgSender(), recipient, amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).buyShares( new address[](0), new uint256[](0), new uint256[](0) ); } else { _transfer(sender, recipient, amount); } return true; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixProxyERC20.sol"; import "./../../release/interfaces/ISynthetixSynth.sol"; import "./MockToken.sol"; contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken { using SafeMath for uint256; bytes32 public override currencyKey; uint256 public constant WAITING_PERIOD_SECS = 3 * 60; mapping(address => uint256) public timelockByAccount; constructor( string memory _name, string memory _symbol, uint8 _decimals, bytes32 _currencyKey ) public MockToken(_name, _symbol, _decimals) { currencyKey = _currencyKey; } function setCurrencyKey(bytes32 _currencyKey) external onlyOwner { currencyKey = _currencyKey; } function _isLocked(address account) internal view returns (bool) { return timelockByAccount[account] >= now; } function _beforeTokenTransfer( address from, address, uint256 ) internal override { require(!_isLocked(from), "Cannot settle during waiting period"); } function target() external view override returns (address) { return address(this); } function isLocked(address account) external view returns (bool) { return _isLocked(account); } function burnFrom(address account, uint256 amount) public override { _burn(account, amount); } function lock(address account) public { timelockByAccount[account] = now.add(WAITING_PERIOD_SECS); } function unlock(address account) public { timelockByAccount[account] = 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IUniswapV2Factory.sol"; import "../../../../interfaces/IUniswapV2Router2.sol"; import "../utils/AdapterBase.sol"; /// @title UniswapV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Uniswap v2 contract UniswapV2Adapter is AdapterBase { using SafeMath for uint256; address private immutable FACTORY; address private immutable ROUTER; constructor( address _integrationManager, address _router, address _factory ) public AdapterBase(_integrationManager) { FACTORY = _factory; ROUTER = _router; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "UNISWAP_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, , uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); spendAssets_ = new address[](2); spendAssets_[0] = outgoingAssets[0]; spendAssets_[1] = outgoingAssets[1]; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0]; spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1]; incomingAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair( outgoingAssets[0], outgoingAssets[1] ); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair( incomingAssets[0], incomingAssets[1] ); spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](2); incomingAssets_[0] = incomingAssets[0]; incomingAssets_[1] = incomingAssets[1]; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0]; minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1]; } else if (_selector == TAKE_ORDER_SELECTOR) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2"); spendAssets_ = new address[](1); spendAssets_[0] = path[0]; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = path[path.length - 1]; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, uint256[2] memory minOutgoingAssetAmounts, ) = __decodeLendCallArgs(_encodedCallArgs); __lend( _vaultProxy, outgoingAssets[0], outgoingAssets[1], maxOutgoingAssetAmounts[0], maxOutgoingAssetAmounts[1], minOutgoingAssetAmounts[0], minOutgoingAssetAmounts[1] ); } /// @notice Redeems pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); // More efficient to parse pool token from _encodedAssetTransferArgs than external call (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __redeem( _vaultProxy, spendAssets[0], outgoingAssetAmount, incomingAssets[0], incomingAssets[1], minIncomingAssetAmounts[0], minIncomingAssetAmounts[1] ); } /// @notice Trades assets on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); __takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path); } // PRIVATE FUNCTIONS /// @dev Helper to decode the lend encoded call arguments function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[2] memory outgoingAssets_, uint256[2] memory maxOutgoingAssetAmounts_, uint256[2] memory minOutgoingAssetAmounts_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256)); } /// @dev Helper to decode the redeem encoded call arguments function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, address[2] memory incomingAssets_, uint256[2] memory minIncomingAssetAmounts_ ) { return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2])); } /// @dev Helper to decode the take order encoded call arguments function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[] memory path_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[], uint256, uint256)); } /// @dev Helper to execute lend. Avoids stack-too-deep error. function __lend( address _vaultProxy, address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired); __approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired); // Execute lend on Uniswap IUniswapV2Router2(ROUTER).addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute redeem. Avoids stack-too-deep error. function __redeem( address _vaultProxy, address _poolToken, uint256 _poolTokenAmount, address _tokenA, address _tokenB, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount); // Execute redeem on Uniswap IUniswapV2Router2(ROUTER).removeLiquidity( _tokenA, _tokenB, _poolTokenAmount, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, uint256 _outgoingAssetAmount, uint256 _minIncomingAssetAmount, address[] memory _path ) private { __approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount); // Execute fill IUniswapV2Router2(ROUTER).swapExactTokensForTokens( _outgoingAssetAmount, _minIncomingAssetAmount, _path, _vaultProxy, block.timestamp.add(1) ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FACTORY` variable /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `ROUTER` variable /// @return router_ The `ROUTER` variable value function getRouter() external view returns (address router_) { return ROUTER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title UniswapV2Router2 Interface /// @author Enzyme Council <[email protected]> /// @dev Minimal interface for our interactions with Uniswap V2's Router2 interface IUniswapV2Router2 { function addLiquidity( address, address, uint256, uint256, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ); function removeLiquidity( address, address, uint256, uint256, uint256, address, uint256 ) external returns (uint256, uint256); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeToken.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CurvePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Curve pool tokens contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event DerivativeAdded( address indexed derivative, address indexed pool, address indexed invariantProxyAsset, uint256 invariantProxyAssetDecimals ); event DerivativeRemoved(address indexed derivative); // Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes. // We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools. struct DerivativeInfo { address pool; address invariantProxyAsset; uint256 invariantProxyAssetDecimals; } uint256 private constant VIRTUAL_PRICE_UNIT = 10**18; address private immutable ADDRESS_PROVIDER; mapping(address => DerivativeInfo) private derivativeToInfo; constructor(address _dispatcher, address _addressProvider) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_PROVIDER = _addressProvider; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) public override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative]; require( derivativeInfo.pool != address(0), "calcUnderlyingValues: _derivative is not supported" ); underlyings_ = new address[](1); underlyings_[0] = derivativeInfo.invariantProxyAsset; underlyingAmounts_ = new uint256[](1); if (derivativeInfo.invariantProxyAssetDecimals == 18) { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .div(VIRTUAL_PRICE_UNIT); } else { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .mul(10**derivativeInfo.invariantProxyAssetDecimals) .div(VIRTUAL_PRICE_UNIT.mul(2)); } return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return derivativeToInfo[_asset].pool != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add /// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants, /// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools function addDerivatives( address[] calldata _derivatives, address[] calldata _invariantProxyAssets ) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require( _derivatives.length == _invariantProxyAssets.length, "addDerivatives: Unequal arrays" ); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require( _invariantProxyAssets[i] != address(0), "addDerivatives: Empty invariantProxyAsset" ); require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set"); // First, try assuming that the derivative is an LP token ICurveRegistry curveRegistryContract = ICurveRegistry( ICurveAddressProvider(ADDRESS_PROVIDER).get_registry() ); address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]); // If the derivative is not a valid LP token, try to treat it as a liquidity gauge token if (pool == address(0)) { // We cannot confirm whether a liquidity gauge token is a valid token // for a particular liquidity gauge, due to some pools using // old liquidity gauge contracts that did not incorporate a token pool = curveRegistryContract.get_pool_from_lp_token( ICurveLiquidityGaugeToken(_derivatives[i]).lp_token() ); // Likely unreachable as above calls will revert on Curve, but doesn't hurt require( pool != address(0), "addDerivatives: Not a valid LP token or liquidity gauge token" ); } uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals(); derivativeToInfo[_derivatives[i]] = DerivativeInfo({ pool: pool, invariantProxyAsset: _invariantProxyAssets[i], invariantProxyAssetDecimals: invariantProxyAssetDecimals }); // Confirm that a non-zero price can be returned for the registered derivative (, uint256[] memory underlyingAmounts) = calcUnderlyingValues( _derivatives[i], 1 ether ); require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price"); emit DerivativeAdded( _derivatives[i], pool, _invariantProxyAssets[i], invariantProxyAssetDecimals ); } } /// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative"); require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set"); delete derivativeToInfo[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `DerivativeInfo` for a given derivative /// @param _derivative The derivative for which to get the `DerivativeInfo` /// @return derivativeInfo_ The `DerivativeInfo` value function getDerivativeInfo(address _derivative) external view returns (DerivativeInfo memory derivativeInfo_) { return derivativeToInfo[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveAddressProvider interface /// @author Enzyme Council <[email protected]> interface ICurveAddressProvider { function get_address(uint256) external view returns (address); function get_registry() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeToken interface /// @author Enzyme Council <[email protected]> /// @notice Common interface functions for all Curve liquidity gauge token contracts interface ICurveLiquidityGaugeToken { function lp_token() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityPool interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityPool { function coins(uint256) external view returns (address); function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistry interface /// @author Enzyme Council <[email protected]> interface ICurveRegistry { function get_gauges(address) external view returns (address[10] memory, int128[10] memory); function get_lp_token(address) external view returns (address); function get_pool_from_lp_token(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeV2.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../../interfaces/ICurveStableSwapSteth.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase2.sol"; /// @title CurveLiquidityStethAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth) contract CurveLiquidityStethAdapter is AdapterBase2 { int128 private constant POOL_INDEX_ETH = 0; int128 private constant POOL_INDEX_STETH = 1; address private immutable LIQUIDITY_GAUGE_TOKEN; address private immutable LP_TOKEN; address private immutable POOL; address private immutable STETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _liquidityGaugeToken, address _lpToken, address _pool, address _stethToken, address _wethToken ) public AdapterBase2(_integrationManager) { LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken; LP_TOKEN = _lpToken; POOL = _pool; STETH_TOKEN = _stethToken; WETH_TOKEN = _wethToken; // Max approve contracts to spend relevant tokens ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max); ERC20(_stethToken).safeApprove(_pool, type(uint256).max); } /// @dev Needed to receive ETH from redemption and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_LIQUIDITY_STETH"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); if (outgoingWethAmount > 0 && outgoingStethAmount > 0) { spendAssets_ = new address[](2); spendAssets_[0] = WETH_TOKEN; spendAssets_[1] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingWethAmount; spendAssetAmounts_[1] = outgoingStethAmount; } else if (outgoingWethAmount > 0) { spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingWethAmount; } else { spendAssets_ = new address[](1); spendAssets_[0] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingStethAmount; } incomingAssets_ = new address[](1); if (_selector == LEND_SELECTOR) { incomingAssets_[0] = LP_TOKEN; } else { incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool receiveSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); if (_selector == REDEEM_SELECTOR) { spendAssets_[0] = LP_TOKEN; } else { spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; if (receiveSingleAsset) { incomingAssets_ = new address[](1); minIncomingAssetAmounts_ = new uint256[](1); if (minIncomingWethAmount == 0) { require( minIncomingStethAmount > 0, "parseAssetsForMethod: No min asset amount specified for receiveSingleAsset" ); incomingAssets_[0] = STETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingStethAmount; } else { require( minIncomingStethAmount == 0, "parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset" ); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingWethAmount; } } else { incomingAssets_ = new address[](2); incomingAssets_[0] = WETH_TOKEN; incomingAssets_[1] = STETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingWethAmount; minIncomingAssetAmounts_[1] = minIncomingStethAmount; } } else if (_selector == STAKE_SELECTOR) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LP_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLPTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLPTokenAmount; } else if (_selector == UNSTAKE_SELECTOR) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LP_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); } /// @notice Lends assets for steth LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lendAndStake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); __stake(ERC20(LP_TOKEN).balanceOf(address(this))); } /// @notice Redeems steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLPTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __redeem( outgoingLPTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } /// @notice Stakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function stake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); __stake(outgoingLPTokenAmount); } /// @notice Unstakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); } /// @notice Unstakes steth LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstakeAndRedeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLiquidityGaugeTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); __redeem( outgoingLiquidityGaugeTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } // PRIVATE FUNCTIONS /// @dev Helper to execute lend function __lend( uint256 _outgoingWethAmount, uint256 _outgoingStethAmount, uint256 _minIncomingLPTokenAmount ) private { if (_outgoingWethAmount > 0) { IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount); } ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}( [_outgoingWethAmount, _outgoingStethAmount], _minIncomingLPTokenAmount ); } /// @dev Helper to execute redeem function __redeem( uint256 _outgoingLPTokenAmount, uint256 _minIncomingWethAmount, uint256 _minIncomingStethAmount, bool _redeemSingleAsset ) private { if (_redeemSingleAsset) { // "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been // validated in parseAssetsForMethod() if (_minIncomingWethAmount > 0) { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_ETH, _minIncomingWethAmount ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } else { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_STETH, _minIncomingStethAmount ); } } else { ICurveStableSwapSteth(POOL).remove_liquidity( _outgoingLPTokenAmount, [_minIncomingWethAmount, _minIncomingStethAmount] ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } /// @dev Helper to execute stake function __stake(uint256 _lpTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this)); } /// @dev Helper to execute unstake function __unstake(uint256 _liquidityGaugeTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingWethAmount_, uint256 outgoingStethAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256)); } /// @dev Helper to decode the encoded call arguments for redeeming. /// If `receiveSingleAsset_` is `true`, then one (and only one) of /// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0 /// to indicate which asset is to be received. function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, uint256 minIncomingWethAmount_, uint256 minIncomingStethAmount_, bool receiveSingleAsset_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLPTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLiquidityGaugeTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable /// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) { return LIQUIDITY_GAUGE_TOKEN; } /// @notice Gets the `LP_TOKEN` variable /// @return lpToken_ The `LP_TOKEN` variable value function getLPToken() external view returns (address lpToken_) { return LP_TOKEN; } /// @notice Gets the `POOL` variable /// @return pool_ The `POOL` variable value function getPool() external view returns (address pool_) { return POOL; } /// @notice Gets the `STETH_TOKEN` variable /// @return stethToken_ The `STETH_TOKEN` variable value function getStethToken() external view returns (address stethToken_) { return STETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeV2 interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityGaugeV2 { function deposit(uint256, address) external; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveStableSwapSteth interface /// @author Enzyme Council <[email protected]> interface ICurveStableSwapSteth { function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./AdapterBase.sol"; /// @title AdapterBase2 Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters that extends AdapterBase /// @dev This is a temporary contract that will be merged into AdapterBase with the next release abstract contract AdapterBase2 is AdapterBase { /// @dev Provides a standard implementation for transferring incoming assets and /// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action modifier postActionAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; ( , address[] memory spendAssets, , address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); __transferFullAssetBalances(_vaultProxy, incomingAssets); __transferFullAssetBalances(_vaultProxy, spendAssets); } /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, spendAssets); } constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @dev Helper to transfer full asset balances of current contract to the specified target function __transferFullAssetBalances(address _target, address[] memory _assets) internal { for (uint256 i = 0; i < _assets.length; i++) { uint256 balance = ERC20(_assets[i]).balanceOf(address(this)); if (balance > 0) { ERC20(_assets[i]).safeTransfer(_target, balance); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IParaSwapAugustusSwapper.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title ParaSwapAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with ParaSwap contract ParaSwapAdapter is AdapterBase { using SafeMath for uint256; string private constant REFERRER = "enzyme"; address private immutable EXCHANGE; address private immutable TOKEN_TRANSFER_PROXY; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _tokenTransferProxy, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; TOKEN_TRANSFER_PROXY = _tokenTransferProxy; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH refund from sent network fees receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "PARASWAP"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, , address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; // Format outgoing assets depending on if there are network fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { // We are not performing special logic if the incomingAsset is the fee asset if (outgoingAsset == WETH_TOKEN) { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees); } else { spendAssets_ = new address[](2); spendAssets_[0] = outgoingAsset; spendAssets_[1] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingAssetAmount; spendAssetAmounts_[1] = totalNetworkFees; } } else { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on ParaSwap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { __takeOrder(_vaultProxy, _encodedCallArgs); } // PRIVATE FUNCTIONS /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to decode the encoded callOnIntegration call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics address outgoingAsset_, uint256 outgoingAssetAmount_, IParaSwapAugustusSwapper.Path[] memory paths_ ) { return abi.decode( _encodedCallArgs, (address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[]) ); } /// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata. /// Avoids the stack-too-deep error. function __encodeMultiSwapCallData( address _vaultProxy, address _incomingAsset, uint256 _minIncomingAssetAmount, uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics address _outgoingAsset, uint256 _outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private pure returns (bytes memory multiSwapCallData) { return abi.encodeWithSelector( IParaSwapAugustusSwapper.multiSwap.selector, _outgoingAsset, // fromToken _incomingAsset, // toToken _outgoingAssetAmount, // fromAmount _minIncomingAssetAmount, // toAmount _expectedIncomingAssetAmount, // expectedAmount _paths, // path 0, // mintPrice payable(_vaultProxy), // beneficiary 0, // donationPercentage REFERRER // referrer ); } /// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call. /// Avoids the stack-too-deep error. function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees) private { (bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}( _multiSwapCallData ); require(success, string(returnData)); } /// @dev Helper for the inner takeOrder() logic. /// Avoids the stack-too-deep error. function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private { ( address incomingAsset, uint256 minIncomingAssetAmount, uint256 expectedIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount); // If there are network fees, unwrap enough WETH to cover the fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { __unwrapWeth(totalNetworkFees); } // Get the callData for the low-level multiSwap() call bytes memory multiSwapCallData = __encodeMultiSwapCallData( _vaultProxy, incomingAsset, minIncomingAssetAmount, expectedIncomingAssetAmount, outgoingAsset, outgoingAssetAmount, paths ); // Execute the trade on ParaSwap __executeMultiSwap(multiSwapCallData, totalNetworkFees); // If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned if (totalNetworkFees > 0) { __wrapEth(); } } /// @dev Helper to unwrap specified amount of WETH into ETH. /// Avoids the stack-too-deep error. function __unwrapWeth(uint256 _amount) private { IWETH(payable(WETH_TOKEN)).withdraw(_amount); } /// @dev Helper to wrap all ETH in contract as WETH. /// Avoids the stack-too-deep error. function __wrapEth() private { uint256 ethBalance = payable(address(this)).balance; if (ethBalance > 0) { IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}(); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `TOKEN_TRANSFER_PROXY` variable /// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value function getTokenTransferProxy() external view returns (address tokenTransferProxy_) { return TOKEN_TRANSFER_PROXY; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title ParaSwap IAugustusSwapper interface interface IParaSwapAugustusSwapper { struct Route { address payable exchange; address targetExchange; uint256 percent; bytes payload; uint256 networkFee; } struct Path { address to; uint256 totalNetworkFee; Route[] routes; } function multiSwap( address, address, uint256, uint256, uint256, Path[] calldata, uint256, address payable, uint256, string calldata ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IParaSwapAugustusSwapper.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockParaSwapIntegratee is SwapperBase { using SafeMath for uint256; address private immutable MOCK_CENTRALIZED_RATE_PROVIDER; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public { MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Must be `public` to avoid error function multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, uint256, // toAmount (min received amount) uint256, // expectedAmount IParaSwapAugustusSwapper.Path[] memory _paths, uint256, // mintPrice address, // beneficiary uint256, // donationPercentage string memory // referrer ) public payable returns (uint256) { return __multiSwap(_fromToken, _toToken, _fromAmount, _paths); } /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to avoid the stack-too-deep error function __multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private returns (uint256) { address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _toToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation); uint256 totalNetworkFees = __calcTotalNetworkFees(_paths); address[] memory assetsToIntegratee; uint256[] memory assetsToIntegrateeAmounts; if (totalNetworkFees > 0) { assetsToIntegratee = new address[](2); assetsToIntegratee[1] = ETH_ADDRESS; assetsToIntegrateeAmounts = new uint256[](2); assetsToIntegrateeAmounts[1] = totalNetworkFees; } else { assetsToIntegratee = new address[](1); assetsToIntegrateeAmounts = new uint256[](1); } assetsToIntegratee[0] = _fromToken; assetsToIntegrateeAmounts[0] = _fromAmount; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } /////////////////// // STATE GETTERS // /////////////////// function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) { return blockNumberDeviation; } function getCentralizedRateProvider() external view returns (address centralizedRateProvider_) { return MOCK_CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract SwapperBase is EthConstantMixin { receive() external payable {} function __swapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken, uint256 _actualRate ) internal returns (uint256 destAmount_) { address[] memory assetsToIntegratee = new address[](1); assetsToIntegratee[0] = _srcToken; uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); assetsToIntegrateeAmounts[0] = _srcAmount; address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _destToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = _actualRate; __swap( _trader, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } function __swap( address payable _trader, address[] memory _assetsToIntegratee, uint256[] memory _assetsToIntegrateeAmounts, address[] memory _assetsFromIntegratee, uint256[] memory _assetsFromIntegrateeAmounts ) internal { // Take custody of incoming assets for (uint256 i = 0; i < _assetsToIntegratee.length; i++) { address asset = _assetsToIntegratee[i]; uint256 amount = _assetsToIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsToIntegratee"); require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts"); // Incoming ETH amounts can be ignored if (asset == ETH_ADDRESS) { continue; } ERC20(asset).transferFrom(_trader, address(this), amount); } // Distribute outgoing assets for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) { address asset = _assetsFromIntegratee[i]; uint256 amount = _assetsFromIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsFromIntegratee"); require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts"); if (asset == ETH_ADDRESS) { _trader.transfer(amount); } else { ERC20(asset).transfer(_trader, amount); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; abstract contract EthConstantMixin { address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/NormalizedRateProviderBase.sol"; import "../../utils/SwapperBase.sol"; abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public NormalizedRateProviderBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRate(address _baseAsset, address _quoteAsset) internal view override returns (uint256) { // 1. Return constant if base asset is quote asset if (_baseAsset == _quoteAsset) { return 10**RATE_PRECISION; } // 2. Check for a direct rate uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset]; if (directRate > 0) { return directRate; } // 3. Check for inverse direct rate uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset]; if (iDirectRate > 0) { return 10**(RATE_PRECISION.mul(2)).div(iDirectRate); } // 4. Else return 1 return 10**RATE_PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./RateProviderBase.sol"; abstract contract NormalizedRateProviderBase is RateProviderBase { using SafeMath for uint256; uint256 public immutable RATE_PRECISION; constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public RateProviderBase(_specialAssets, _specialAssetDecimals) { RATE_PRECISION = _ratePrecision; for (uint256 i = 0; i < _defaultRateAssets.length; i++) { for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) { assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] = 10**_ratePrecision; assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] = 10**_ratePrecision; } } } // TODO: move to main contracts' utils for use with prices function __calcDenormalizedQuoteAssetAmount( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _rate ) internal view returns (uint256) { return _rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div( 10**(RATE_PRECISION.add(_baseAssetDecimals)) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract RateProviderBase is EthConstantMixin { mapping(address => mapping(address => uint256)) public assetToAssetRate; // Handles non-ERC20 compliant assets like ETH and USD mapping(address => uint8) public specialAssetToDecimals; constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public { require( _specialAssets.length == _specialAssetDecimals.length, "constructor: _specialAssets and _specialAssetDecimals are uneven lengths" ); for (uint256 i = 0; i < _specialAssets.length; i++) { specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i]; } specialAssetToDecimals[ETH_ADDRESS] = 18; } function __getDecimalsForAsset(address _asset) internal view returns (uint256) { uint256 decimals = specialAssetToDecimals[_asset]; if (decimals == 0) { decimals = uint256(ERC20(_asset).decimals()); } return decimals; } function __getRate(address _baseAsset, address _quoteAsset) internal view virtual returns (uint256) { return assetToAssetRate[_baseAsset][_quoteAsset]; } function setRates( address[] calldata _baseAssets, address[] calldata _quoteAssets, uint256[] calldata _rates ) external { require( _baseAssets.length == _quoteAssets.length, "setRates: _baseAssets and _quoteAssets are uneven lengths" ); require( _baseAssets.length == _rates.length, "setRates: _baseAssets and _rates are uneven lengths" ); for (uint256 i = 0; i < _baseAssets.length; i++) { assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i]; } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title AssetUnitCacheMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin to store a cache of asset units abstract contract AssetUnitCacheMixin { event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit); mapping(address => uint256) private assetToUnit; /// @notice Caches the decimal-relative unit for a given asset /// @param _asset The asset for which to cache the decimal-relative unit /// @dev Callable by any account function cacheAssetUnit(address _asset) public { uint256 prevUnit = getCachedUnitForAsset(_asset); uint256 nextUnit = 10**uint256(ERC20(_asset).decimals()); if (nextUnit != prevUnit) { assetToUnit[_asset] = nextUnit; emit AssetUnitCached(_asset, prevUnit, nextUnit); } } /// @notice Caches the decimal-relative units for multiple given assets /// @param _assets The assets for which to cache the decimal-relative units /// @dev Callable by any account function cacheAssetUnits(address[] memory _assets) public { for (uint256 i; i < _assets.length; i++) { cacheAssetUnit(_assets[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the cached decimal-relative unit for a given asset /// @param _asset The asset for which to get the cached decimal-relative unit /// @return unit_ The cached decimal-relative unit function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) { return assetToUnit[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; /// @title SinglePeggedDerivativePriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed { address private immutable DERIVATIVE; address private immutable UNDERLYING; constructor(address _derivative, address _underlying) public { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "constructor: Unequal decimals" ); DERIVATIVE = _derivative; UNDERLYING = _underlying; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = UNDERLYING; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == DERIVATIVE; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE` variable value /// @return derivative_ The `DERIVATIVE` variable value function getDerivative() external view returns (address derivative_) { return DERIVATIVE; } /// @notice Gets the `UNDERLYING` variable value /// @return underlying_ The `UNDERLYING` variable value function getUnderlying() external view returns (address underlying_) { return UNDERLYING; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SinglePeggedDerivativePriceFeedBase contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _derivative, address _underlying) public SinglePeggedDerivativePriceFeedBase(_derivative, _underlying) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title StakehoundEthPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]yme.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title LidoStethPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/) contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IKyberNetworkProxy.sol"; import "../../../../interfaces/IWETH.sol"; import "../../../../utils/MathHelpers.sol"; import "../utils/AdapterBase.sol"; /// @title KyberAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Kyber Network contract KyberAdapter is AdapterBase, MathHelpers { address private immutable EXCHANGE; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "KYBER_NETWORK"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require( incomingAsset != outgoingAsset, "parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same" ); require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Kyber /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); uint256 minExpectedRate = __calcNormalizedRate( ERC20(outgoingAsset).decimals(), outgoingAssetAmount, ERC20(incomingAsset).decimals(), minIncomingAssetAmount ); if (outgoingAsset == WETH_TOKEN) { __swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate); } else if (incomingAsset == WETH_TOKEN) { __swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate); } else { __swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate); } } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /// @dev Executes a swap of ETH to ERC20 function __swapNativeAssetToToken( address _incomingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}( _incomingAsset, _minExpectedRate ); } /// @dev Executes a swap of ERC20 to ETH function __swapTokenToNativeAsset( address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToEther( _outgoingAsset, _outgoingAssetAmount, _minExpectedRate ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } /// @dev Executes a swap of ERC20 to ERC20 function __swapTokenToToken( address _incomingAsset, address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToToken( _outgoingAsset, _outgoingAssetAmount, _incomingAsset, _minExpectedRate ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Kyber Network interface interface IKyberNetworkProxy { function swapEtherToToken(address, uint256) external payable returns (uint256); function swapTokenToEther( address, uint256, uint256 ) external returns (uint256); function swapTokenToToken( address, uint256, address, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/utils/MathHelpers.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers { using SafeMath for uint256; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable WETH; uint256 private constant PRECISION = 18; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address _centralizedRateProvider, address _weth, uint256 _blockNumberDeviation ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; WETH = _weth; blockNumberDeviation = _blockNumberDeviation; } function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation); __swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount); return msg.value; } function swapTokenToEther( address _srcToken, uint256 _srcAmount, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount); return _srcAmount; } function swapTokenToToken( address _srcToken, uint256 _srcAmount, address _destToken, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount); return _srcAmount; } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } function getExpectedRate( address _srcToken, address _destToken, uint256 _amount ) external returns (uint256 rate_, uint256 worstRate_) { if (_srcToken == ETH_ADDRESS) { _srcToken = WETH; } if (_destToken == ETH_ADDRESS) { _destToken = WETH; } uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken); rate_ = __calcNormalizedRate( ERC20(_srcToken).decimals(), _amount, ERC20(_destToken).decimals(), destAmount ); worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100); } /////////////////// // STATE GETTERS // /////////////////// function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getWeth() public view returns (address) { return WETH; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/MockChainlinkPriceSource.sol"; /// @dev This price source offers two different options getting prices /// The first one is getting a fixed rate, which can be useful for tests /// The second approach calculates dinamically the rate making use of a chainlink price source /// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates } contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates { using SafeMath for uint256; mapping(bytes32 => uint256) private fixedRate; mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator; enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } constructor(address _ethUsdAggregator) public { currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({ aggregator: _ethUsdAggregator, rateAsset: RateAsset.USD }); } function setPriceSourcesForCurrencyKeys( bytes32[] calldata _currencyKeys, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyOwner { require( _currencyKeys.length == _aggregators.length && _rateAssets.length == _aggregators.length ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); } } function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner { fixedRate[_currencyKey] = _rate; } /// @dev Calculates the rate from a currency key against USD function rateAndInvalid(bytes32 _currencyKey) external view override returns (uint256 rate_, bool isInvalid_) { uint256 storedRate = getFixedRate(_currencyKey); if (storedRate != 0) { rate_ = storedRate; } else { AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey); address aggregator = aggregatorInfo.aggregator; if (aggregator == address(0)) { rate_ = 0; isInvalid_ = true; return (rate_, isInvalid_); } uint256 decimals = MockChainlinkPriceSource(aggregator).decimals(); rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul( 10**(uint256(18).sub(decimals)) ); if (aggregatorInfo.rateAsset == RateAsset.ETH) { uint256 ethToUsd = uint256( MockChainlinkPriceSource( getAggregatorFromCurrencyKey(bytes32("ETH")) .aggregator ) .latestAnswer() ); rate_ = rate_.mul(ethToUsd).div(10**8); } } isInvalid_ = (rate_ == 0); return (rate_, isInvalid_); } /////////////////// // STATE GETTERS // /////////////////// function getAggregatorFromCurrencyKey(bytes32 _currencyKey) public view returns (AggregatorInfo memory _aggregator) { return currencyKeyToAggregator[_currencyKey]; } function getFixedRate(bytes32 _currencyKey) public view returns (uint256) { return fixedRate[_currencyKey]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; contract MockChainlinkPriceSource { event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); uint256 public DECIMALS; int256 public latestAnswer; uint256 public latestTimestamp; uint256 public roundId; address public aggregator; constructor(uint256 _decimals) public { DECIMALS = _decimals; latestAnswer = int256(10**_decimals); latestTimestamp = now; roundId = 1; aggregator = address(this); } function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external { latestAnswer = _nextAnswer; latestTimestamp = _nextTimestamp; roundId = roundId + 1; emit AnswerUpdated(latestAnswer, roundId, latestTimestamp); } function setAggregator(address _nextAggregator) external { aggregator = _nextAggregator; } function decimals() public view returns (uint256) { return DECIMALS; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockSynthetixToken.sol"; /// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts /// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals /// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts> contract MockSynthetixIntegratee is Ownable, MockToken { using SafeMath for uint256; mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval; mapping(bytes32 => address) private currencyKeyToSynth; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable EXCHANGE_RATES; uint256 private immutable FEE; uint256 private constant UNIT_FEE = 1000; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _centralizedRateProvider, address _exchangeRates, uint256 _fee ) public MockToken(_name, _symbol, _decimals) { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; EXCHANGE_RATES = address(_exchangeRates); FEE = _fee; } receive() external payable {} function exchangeOnBehalfWithTracking( address _exchangeForAddress, bytes32 _srcCurrencyKey, uint256 _srcAmount, bytes32 _destinationCurrencyKey, address, bytes32 ) external returns (uint256 amountReceived_) { require( canExchangeFor(_exchangeForAddress, msg.sender), "exchangeOnBehalfWithTracking: Not approved to act on behalf" ); amountReceived_ = __calculateAndSwap( _exchangeForAddress, _srcAmount, _srcCurrencyKey, _destinationCurrencyKey ); return amountReceived_; } function getAmountsForExchange( uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) public returns ( uint256 amountReceived_, uint256 fee_, uint256 exchangeFeeRate_ ) { address srcToken = currencyKeyToSynth[_srcCurrencyKey]; address destToken = currencyKeyToSynth[_destCurrencyKey]; require( currencyKeyToSynth[_srcCurrencyKey] != address(0) && currencyKeyToSynth[_destCurrencyKey] != address(0), "getAmountsForExchange: Currency key doesn't have an associated synth" ); uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken); exchangeFeeRate_ = FEE; amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE); fee_ = destAmount.sub(amountReceived_); return (amountReceived_, fee_, exchangeFeeRate_); } function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths) external { require( _currencyKeys.length == _synths.length, "setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths" ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToSynth[_currencyKeys[i]] = _synths[i]; } } function approveExchangeOnBehalf(address _delegate) external { authorizerToDelegateToApproval[msg.sender][_delegate] = true; } function __calculateAndSwap( address _exchangeForAddress, uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) private returns (uint256 amountReceived_) { MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]); MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]); require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed"); require( address(destSynth) != address(0), "__calculateAndSwap: Destination synth is not listed" ); require( !srcSynth.isLocked(_exchangeForAddress), "__calculateAndSwap: Cannot settle during waiting period" ); (amountReceived_, , ) = getAmountsForExchange( _srcAmount, _srcCurrencyKey, _destCurrencyKey ); srcSynth.burnFrom(_exchangeForAddress, _srcAmount); destSynth.mintFor(_exchangeForAddress, amountReceived_); destSynth.lock(_exchangeForAddress); return amountReceived_; } function requireAndGetAddress(bytes32 _name, string calldata) external view returns (address resolvedAddress_) { if (_name == "ExchangeRates") { return EXCHANGE_RATES; } return address(this); } function settle(address, bytes32) external returns ( uint256, uint256, uint256 ) {} /////////////////// // STATE GETTERS // /////////////////// function canExchangeFor(address _authorizer, address _delegate) public view returns (bool canExchange_) { return authorizerToDelegateToApproval[_authorizer][_delegate]; } function getExchangeRates() public view returns (address exchangeRates_) { return EXCHANGE_RATES; } function getFee() public view returns (uint256 fee_) { return FEE; } function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) { return currencyKeyToSynth[_currencyKey]; } function getUnitFee() public pure returns (uint256 fee_) { return UNIT_FEE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../prices/CentralizedRateProvider.sol"; import "./utils/SimpleMockIntegrateeBase.sol"; /// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/> /// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/> contract MockUniswapV2Integratee is SwapperBase, Ownable { using SafeMath for uint256; mapping(address => mapping(address => address)) private assetToAssetToPair; address private immutable CENTRALIZED_RATE_PROVIDER; uint256 private constant PRECISION = 18; // Set in %, defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair, address _centralizedRateProvider, uint256 _blockNumberDeviation ) public { addPair(_listOfToken0, _listOfToken1, _listOfPair); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Adds the maximum possible value from {_amountADesired _amountBDesired} /// Makes use of the value interpreter to perform those calculations function addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ) { __addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired); } /// @dev Removes the specified amount of liquidity /// Returns 50% of the incoming liquidity value on each token. function removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity, uint256, uint256, address, uint256 ) public returns (uint256, uint256) { __removeLiquidity(_tokenA, _tokenB, _liquidity); } function swapExactTokensForTokens( uint256 amountIn, uint256, address[] calldata path, address, uint256 ) external returns (uint256[] memory) { uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation); __swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut); } /// @dev We don't calculate any intermediate values here because they aren't actually used /// Returns the randomized by sender value of the edge path assets function getAmountsOut(uint256 _amountIn, address[] calldata _path) external returns (uint256[] memory amounts_) { require(_path.length >= 2, "getAmountsOut: path must be >= 2"); address assetIn = _path[0]; address assetOut = _path[_path.length - 1]; uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut); amounts_ = new uint256[](_path.length); amounts_[0] = _amountIn; amounts_[_path.length - 1] = amountOut; return amounts_; } function addPair( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair ) public onlyOwner { require( _listOfPair.length == _listOfToken0.length, "constructor: _listOfPair and _listOfToken0 have an unequal length" ); require( _listOfPair.length == _listOfToken1.length, "constructor: _listOfPair and _listOfToken1 have an unequal length" ); for (uint256 i; i < _listOfPair.length; i++) { address token0 = _listOfToken0[i]; address token1 = _listOfToken1[i]; address pair = _listOfPair[i]; assetToAssetToPair[token0][token1] = pair; assetToAssetToPair[token1][token0] = pair; } } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } // PRIVATE FUNCTIONS /// Avoids stack-too-deep error. function __addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired ) private { address pair = getPair(_tokenA, _tokenB); uint256 amountA; uint256 amountB; uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenA, _amountADesired, _tokenB); uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA); if (amountBFromA >= _amountBDesired) { amountA = amountAFromB; amountB = _amountBDesired; } else { amountA = _amountADesired; amountB = amountBFromA; } uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA); // Calculate the inverse rate to know the amount of LPToken to return from a unit of token uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken); // Total liquidity can be calculated as 2x liquidity from amount A uint256 totalLiquidity = uint256(2).mul( amountA.mul(inverseRate).div(uint256(10**PRECISION)) ); require( ERC20(pair).balanceOf(address(this)) >= totalLiquidity, "__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount" ); address[] memory assetsToIntegratee = new address[](2); uint256[] memory assetsToIntegrateeAmounts = new uint256[](2); address[] memory assetsFromIntegratee = new address[](1); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsToIntegratee[0] = _tokenA; assetsToIntegrateeAmounts[0] = amountA; assetsToIntegratee[1] = _tokenB; assetsToIntegrateeAmounts[1] = amountB; assetsFromIntegratee[0] = pair; assetsFromIntegrateeAmounts[0] = totalLiquidity; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /// Avoids stack-too-deep error. function __removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity ) private { address pair = assetToAssetToPair[_tokenA][_tokenB]; require(pair != address(0), "__removeLiquidity: this pair doesn't exist"); uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenA) .div(uint256(2)); uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenB) .div(uint256(2)); address[] memory assetsToIntegratee = new address[](1); uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); address[] memory assetsFromIntegratee = new address[](2); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2); assetsToIntegratee[0] = pair; assetsToIntegrateeAmounts[0] = _liquidity; assetsFromIntegratee[0] = _tokenA; assetsFromIntegrateeAmounts[0] = amountA; assetsFromIntegratee[1] = _tokenB; assetsFromIntegrateeAmounts[1] = amountB; require( ERC20(_tokenA).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount" ); require( ERC20(_tokenB).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount" ); __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /////////////////// // STATE GETTERS // /////////////////// /// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue function feeTo() external pure returns (address) { return address(0); } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } function getPair(address _token0, address _token1) public view returns (address) { return assetToAssetToPair[_token0][_token1]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockIntegrateeBase.sol"; abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public MockIntegrateeBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRateAndSwapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken ) internal returns (uint256 destAmount_) { uint256 actualRate = __getRate(_srcToken, _destToken); __swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate); return actualRate; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../../prices/CentralizedRateProvider.sol"; import "../../utils/SwapperBase.sol"; contract MockCTokenBase is ERC20, SwapperBase, Ownable { address internal immutable TOKEN; address internal immutable CENTRALIZED_RATE_PROVIDER; uint256 internal rate; mapping(address => mapping(address => uint256)) internal _allowances; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); TOKEN = _token; CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; rate = _initialRate; } function approve(address _spender, uint256 _amount) public virtual override returns (bool) { _allowances[msg.sender][_spender] = _amount; return true; } /// @dev Overriden `allowance` function, give the integratee infinite approval by default function allowance(address _owner, address _spender) public view override returns (uint256) { if (_spender == address(this) || _owner == _spender) { return 2**256 - 1; } else { return _allowances[_owner][_spender]; } } /// @dev Necessary as this contract doesn't directly inherit from MockToken function mintFor(address _who, uint256 _amount) external onlyOwner { _mint(_who, _amount); } /// @dev Necessary to allow updates on persistent deployments (e.g Kovan) function setRate(uint256 _rate) public onlyOwner { rate = _rate; } function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual override returns (bool) { _transfer(_sender, _recipient, _amount); return true; } // INTERNAL FUNCTIONS /// @dev Calculates the cTokenAmount given a tokenAmount /// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) { uint256 tokenDecimals = ERC20(TOKEN).decimals(); uint256 cTokenDecimals = decimals(); // Result in Token Decimals uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN); // Result in cToken decimals uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div( tokenPerCTokenUnit ); // Amount in token decimals, result in cToken decimals cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Part of ICERC20 token interface function underlying() public view returns (address) { return TOKEN; } /// @dev Part of ICERC20 token interface. /// Called from CompoundPriceFeed, returns the actual Rate cToken/Token function exchangeRateStored() public view returns (uint256) { return rate; } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCTokenIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate) {} function mint(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN, _amount, address(this) ); __swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount); return _amount; } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCEtherIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _weth, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate) {} function mint() external payable { uint256 amount = msg.value; uint256 destAmount = __calcCTokenAmount(amount); __swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount); } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveSwapsERC20.sol"; import "../../../../interfaces/ICurveSwapsEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CurveExchangeAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for swapping assets on Curve <https://www.curve.fi/> contract CurveExchangeAdapter is AdapterBase { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address private immutable ADDRESS_PROVIDER; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _addressProvider, address _wethToken ) public AdapterBase(_integrationManager) { ADDRESS_PROVIDER = _addressProvider; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_EXCHANGE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require(pool != address(0), "parseAssetsForMethod: No pool address provided"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Curve /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2); __takeOrder( _vaultProxy, swaps, pool, outgoingAsset, outgoingAssetAmount, incomingAsset, minIncomingAssetAmount ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the take order encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address pool_, address outgoingAsset_, uint256 outgoingAssetAmount_, address incomingAsset_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256)); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, address _swaps, address _pool, address _outgoingAsset, uint256 _outgoingAssetAmount, address _incomingAsset, uint256 _minIncomingAssetAmount ) private { if (_outgoingAsset == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount); ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}( _pool, ETH_ADDRESS, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } else if (_incomingAsset == WETH_TOKEN) { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, ETH_ADDRESS, _outgoingAssetAmount, _minIncomingAssetAmount, address(this) ); // wrap received ETH and send back to the vault uint256 receivedAmount = payable(address(this)).balance; IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}(); ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount); } else { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsERC20 Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsERC20 { function exchange( address, address, address, uint256, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsEther Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsEther { function exchange( address, address, address, uint256, uint256, address ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; import "./SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title PeggedDerivativesPriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings, /// and have the same decimals as their underlying abstract contract PeggedDerivativesPriceFeedBase is IDerivativePriceFeed, SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address underlying = getUnderlyingForDerivative(_derivative); require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = underlying; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return getUnderlyingForDerivative(_asset) != address(0); } /// @dev Provides validation that the derivative and underlying have the same decimals. /// Can be overrode by the inheriting price feed using super() to implement further validation. function __validateDerivative(address _derivative, address _underlying) internal virtual override { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "__validateDerivative: Unequal decimals" ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../utils/DispatcherOwnerMixin.sol"; /// @title SingleUnderlyingDerivativeRegistryMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin for derivative price feeds that handle multiple derivatives /// that each have a single underlying asset abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address indexed underlying); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToUnderlying; constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {} /// @notice Adds derivatives with corresponding underlyings to the price feed /// @param _derivatives The derivatives to add /// @param _underlyings The corresponding underlyings to add function addDerivatives(address[] memory _derivatives, address[] memory _underlyings) external virtual onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require(_underlyings[i] != address(0), "addDerivatives: Empty underlying"); require( getUnderlyingForDerivative(_derivatives[i]) == address(0), "addDerivatives: Value already set" ); __validateDerivative(_derivatives[i], _underlyings[i]); derivativeToUnderlying[_derivatives[i]] = _underlyings[i]; emit DerivativeAdded(_derivatives[i], _underlyings[i]); } } /// @notice Removes derivatives from the price feed /// @param _derivatives The derivatives to remove function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require( getUnderlyingForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Value not set" ); delete derivativeToUnderlying[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair function __validateDerivative(address, address) internal virtual { // UNIMPLEMENTED } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the underlying asset for a given derivative /// @param _derivative The derivative for which to get the underlying asset /// @return underlying_ The underlying asset function getUnderlyingForDerivative(address _derivative) public view returns (address underlying_) { return derivativeToUnderlying[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of PeggedDerivativesPriceFeedBase contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase { constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAaveProtocolDataProvider.sol"; import "./utils/PeggedDerivativesPriceFeedBase.sol"; /// @title AavePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Aave contract AavePriceFeed is PeggedDerivativesPriceFeedBase { address private immutable PROTOCOL_DATA_PROVIDER; constructor(address _dispatcher, address _protocolDataProvider) public PeggedDerivativesPriceFeedBase(_dispatcher) { PROTOCOL_DATA_PROVIDER = _protocolDataProvider; } function __validateDerivative(address _derivative, address _underlying) internal override { super.__validateDerivative(_derivative, _underlying); (address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER) .getReserveTokensAddresses(_underlying); require( aTokenAddress == _derivative, "__validateDerivative: Invalid aToken or token provided" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value /// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value function getProtocolDataProvider() external view returns (address protocolDataProvider_) { return PROTOCOL_DATA_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveProtocolDataProvider interface /// @author Enzyme Council <[email protected]> interface IAaveProtocolDataProvider { function getReserveTokensAddresses(address) external view returns ( address, address, address ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol"; import "../../../../interfaces/IAaveLendingPool.sol"; import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol"; import "../utils/AdapterBase.sol"; /// @title AaveAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Aave Lending <https://aave.com/> contract AaveAdapter is AdapterBase { address private immutable AAVE_PRICE_FEED; address private immutable LENDING_POOL_ADDRESS_PROVIDER; uint16 private constant REFERRAL_CODE = 158; constructor( address _integrationManager, address _lendingPoolAddressProvider, address _aavePriceFeed ) public AdapterBase(_integrationManager) { LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider; AAVE_PRICE_FEED = _aavePriceFeed; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "AAVE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = aToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else if (_selector == REDEEM_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = aToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).deposit( spendAssets[0], spendAssetAmounts[0], _vaultProxy, REFERRAL_CODE ); } /// @notice Redeems an amount of aTokens from AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).withdraw( incomingAssets[0], spendAssetAmounts[0], _vaultProxy ); } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address aToken, uint256 amount) { return abi.decode(_encodedCallArgs, (address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AAVE_PRICE_FEED` variable /// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value function getAavePriceFeed() external view returns (address aavePriceFeed_) { return AAVE_PRICE_FEED; } /// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable /// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value function getLendingPoolAddressProvider() external view returns (address lendingPoolAddressProvider_) { return LENDING_POOL_ADDRESS_PROVIDER; } /// @notice Gets the `REFERRAL_CODE` variable /// @return referralCode_ The `REFERRAL_CODE` variable value function getReferralCode() external pure returns (uint16 referralCode_) { return REFERRAL_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPool interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPool { function deposit( address, uint256, address, uint16 ) external; function withdraw( address, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPoolAddressProvider interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPoolAddressProvider { function getLendingPool() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Non-whitelisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Must whitelist denominationAsset" ); __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (!isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /// @title AddressListPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice An abstract mixin contract for policies that use an address list abstract contract AddressListPolicyMixin { using EnumerableSet for EnumerableSet.AddressSet; event AddressesAdded(address indexed comptrollerProxy, address[] items); event AddressesRemoved(address indexed comptrollerProxy, address[] items); mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList; // EXTERNAL FUNCTIONS /// @notice Get all addresses in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @return list_ The addresses in the fund's list function getList(address _comptrollerProxy) external view returns (address[] memory list_) { list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length()); for (uint256 i = 0; i < list_.length; i++) { list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i); } return list_; } // PUBLIC FUNCTIONS /// @notice Check if an address is in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _item The address to check against the list /// @return isInList_ True if the address is in the list function isInList(address _comptrollerProxy, address _item) public view returns (bool isInList_) { return comptrollerProxyToList[_comptrollerProxy].contains(_item); } // INTERNAL FUNCTIONS /// @dev Helper to add addresses to the calling fund's list function __addToList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__addToList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].add(_items[i]), "__addToList: Address already exists in list" ); } emit AddressesAdded(_comptrollerProxy, _items); } /// @dev Helper to remove addresses from the calling fund's list function __removeFromList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__removeFromList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].remove(_items[i]), "__removeFromList: Address does not exist in list" ); } emit AddressesRemoved(_comptrollerProxy, _items); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Blacklisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( !assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Cannot blacklist denominationAsset" ); __addToList(_comptrollerProxy, assets); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of adapters for use by a fund contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPreValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns (address adapter_, bytes4 selector_) { return abi.decode(_encodedRuleArgs, (address, bytes4)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title GuaranteedRedemption Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that guarantees that shares will either be continuously redeemable or /// redeemable within a predictable daily window by preventing trading during a configurable daily period contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin { using SafeMath for uint256; event AdapterAdded(address adapter); event AdapterRemoved(address adapter); event FundSettingsSet( address indexed comptrollerProxy, uint256 startTimestamp, uint256 duration ); event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer); struct RedemptionWindow { uint256 startTimestamp; uint256 duration; } uint256 private constant ONE_DAY = 24 * 60 * 60; mapping(address => bool) private adapterToCanBlockRedemption; mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow; uint256 private redemptionWindowBuffer; constructor( address _policyManager, address _fundDeployer, uint256 _redemptionWindowBuffer, address[] memory _redemptionBlockingAdapters ) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) { redemptionWindowBuffer = _redemptionWindowBuffer; __addRedemptionBlockingAdapters(_redemptionBlockingAdapters); } // EXTERNAL FUNCTIONS /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { (uint256 startTimestamp, uint256 duration) = abi.decode( _encodedSettings, (uint256, uint256) ); if (startTimestamp == 0) { require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0"); return; } // Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer require( duration > 0 && duration <= 23 hours, "addFundSettings: duration must be between 1 second and 23 hours" ); comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp; comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration; emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "GUARANTEED_REDEMPTION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { if (!adapterCanBlockRedemption(_adapter)) { return true; } RedemptionWindow memory redemptionWindow = comptrollerProxyToRedemptionWindow[_comptrollerProxy]; // If no RedemptionWindow is set, the fund can never use redemption-blocking adapters if (redemptionWindow.startTimestamp == 0) { return false; } uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart( redemptionWindow.startTimestamp ); // A fund can't trade during its redemption window, nor in the buffer beforehand. // The lower bound is only relevant when the startTimestamp is in the future, // so we check it last. if ( block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) || block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer) ) { return true; } return false; } /// @notice Sets a new value for the redemptionWindowBuffer variable /// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer /// @dev The redemptionWindowBuffer is added to the beginning of the redemption window, /// and should always be >= the longest potential block on redemption amongst all adapters. /// (e.g., Synthetix blocks token transfers during a timelock after trading synths) function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer) external onlyFundDeployerOwner { uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer; require( _nextRedemptionWindowBuffer != prevRedemptionWindowBuffer, "setRedemptionWindowBuffer: Value already set" ); redemptionWindowBuffer = _nextRedemptionWindowBuffer; emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } // PUBLIC FUNCTIONS /// @notice Calculates the start of the most recent redemption window /// @param _startTimestamp The initial startTimestamp for the redemption window /// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window function calcLatestRedemptionWindowStart(uint256 _startTimestamp) public view returns (uint256 latestRedemptionWindowStart_) { if (block.timestamp <= _startTimestamp) { return _startTimestamp; } uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp); uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY); return block.timestamp.sub(timeSincePeriodStart); } /////////////////////////////////////////// // REDEMPTION-BLOCKING ADAPTERS REGISTRY // /////////////////////////////////////////// /// @notice Add adapters which can block shares redemption /// @param _adapters The addresses of adapters to be added function addRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "__addRedemptionBlockingAdapters: _adapters cannot be empty" ); __addRedemptionBlockingAdapters(_adapters); } /// @notice Remove adapters which can block shares redemption /// @param _adapters The addresses of adapters to be removed function removeRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "removeRedemptionBlockingAdapters: _adapters cannot be empty" ); for (uint256 i; i < _adapters.length; i++) { require( adapterCanBlockRedemption(_adapters[i]), "removeRedemptionBlockingAdapters: adapter is not added" ); adapterToCanBlockRedemption[_adapters[i]] = false; emit AdapterRemoved(_adapters[i]); } } /// @dev Helper to mark adapters that can block shares redemption function __addRedemptionBlockingAdapters(address[] memory _adapters) private { for (uint256 i; i < _adapters.length; i++) { require( _adapters[i] != address(0), "__addRedemptionBlockingAdapters: adapter cannot be empty" ); require( !adapterCanBlockRedemption(_adapters[i]), "__addRedemptionBlockingAdapters: adapter already added" ); adapterToCanBlockRedemption[_adapters[i]] = true; emit AdapterAdded(_adapters[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `redemptionWindowBuffer` variable /// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) { return redemptionWindowBuffer; } /// @notice Gets the RedemptionWindow settings for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return redemptionWindow_ The RedemptionWindow settings function getRedemptionWindowForFund(address _comptrollerProxy) external view returns (RedemptionWindow memory redemptionWindow_) { return comptrollerProxyToRedemptionWindow[_comptrollerProxy]; } /// @notice Checks whether an adapter can block shares redemption /// @param _adapter The address of the adapter to check /// @return canBlockRedemption_ True if the adapter can block shares redemption function adapterCanBlockRedemption(address _adapter) public view returns (bool canBlockRedemption_) { return adapterToCanBlockRedemption[_adapter]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of adapters from use by a fund contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return !isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title InvestorWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "INVESTOR_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investor The investor for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _investor) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _investor); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address buyer, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, buyer); } /// @dev Helper to update the investor whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreBuyShares policy hook abstract contract PreBuySharesValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256, uint256, uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title MinMaxInvestment Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that restricts the amount of the fund's denomination asset that a user can /// send in a single call to buy shares in a fund contract MinMaxInvestment is PreBuySharesValidatePolicyBase { event FundSettingsSet( address indexed comptrollerProxy, uint256 minInvestmentAmount, uint256 maxInvestmentAmount ); struct FundSettings { uint256 minInvestmentAmount; uint256 maxInvestmentAmount; } mapping(address => FundSettings) private comptrollerProxyToFundSettings; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MIN_MAX_INVESTMENT"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investmentAmount The investment amount for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, uint256 _investmentAmount) public view returns (bool isValid_) { uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount; uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount; // Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund // temporarily if (minInvestmentAmount == 0) { return _investmentAmount <= maxInvestmentAmount; } else if (maxInvestmentAmount == 0) { return _investmentAmount >= minInvestmentAmount; } return _investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, investmentAmount); } /// @dev Helper to set the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private { (uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode( _encodedSettings, (uint256, uint256) ); require( maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount, "__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount" ); comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount = minInvestmentAmount; comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount = maxInvestmentAmount; emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the min and max investment amount for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return fundSettings_ The fund settings function getFundSettings(address _comptrollerProxy) external view returns (FundSettings memory fundSettings_) { return comptrollerProxyToFundSettings[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/BuySharesSetupPolicyBase.sol"; /// @title BuySharesCallerWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "BUY_SHARES_CALLER_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _buySharesCaller The buyShares caller for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _buySharesCaller) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _buySharesCaller); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address caller, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, caller); } /// @dev Helper to update the whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesSetupPolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook abstract contract BuySharesSetupPolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address caller_, uint256[] memory investmentAmounts_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/vault/VaultLib.sol"; import "../utils/AdapterBase.sol"; /// @title TrackedAssetsAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops) contract TrackedAssetsAdapter is AdapterBase { constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @notice Add multiple assets to the Vault's list of tracked assets /// @dev No need to perform any validation or implement any logic function addTrackedAssets( address, bytes calldata, bytes calldata ) external view {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "TRACKED_ASSETS"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require( _selector == ADD_TRACKED_ASSETS_SELECTOR, "parseAssetsForMethod: _selector invalid" ); incomingAssets_ = __decodeCallArgs(_encodedCallArgs); minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length); for (uint256 i; i < minIncomingAssetAmounts_.length; i++) { minIncomingAssetAmounts_[i] = 1; } return ( spendAssetsHandleType_, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address[] memory incomingAssets_) { return abi.decode(_encodedCallArgs, (address[])); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/ProxiableVaultLib.sol"; /// @title VaultProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822 /// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract VaultProxy { constructor(bytes memory _constructData, address _vaultLib) public { // "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to // `bytes32(keccak256('mln.proxiable.vaultlib'))` require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_vaultLib).proxiableUUID(), "constructor: _vaultLib not compatible" ); assembly { // solium-disable-line sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib) } (bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line require(success, string(returnData)); } fallback() external payable { assembly { // solium-disable-line let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigrationHookHandler.sol"; import "../utils/IMigratableVault.sol"; import "../vault/VaultProxy.sol"; import "./IDispatcher.sol"; /// @title Dispatcher Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract linking multiple releases. /// It handles the deployment of new VaultProxy instances, /// and the regulation of fund migration from a previous release to the current one. /// It can also be referred to for access-control based on this contract's owner. /// @dev DO NOT EDIT CONTRACT contract Dispatcher is IDispatcher { event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer); event MigrationCancelled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationExecuted( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationSignaled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock); event NominatedOwnerSet(address indexed nominatedOwner); event NominatedOwnerRemoved(address indexed nominatedOwner); event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner); event MigrationInCancelHookFailed( bytes failureReturnData, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event MigrationOutHookFailed( bytes failureReturnData, IMigrationHookHandler.MigrationOutHook hook, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event SharesTokenSymbolSet(string _nextSymbol); event VaultProxyDeployed( address indexed fundDeployer, address indexed owner, address vaultProxy, address indexed vaultLib, address vaultAccessor, string fundName ); struct MigrationRequest { address nextFundDeployer; address nextVaultAccessor; address nextVaultLib; uint256 executableTimestamp; } address private currentFundDeployer; address private nominatedOwner; address private owner; uint256 private migrationTimelock; string private sharesTokenSymbol; mapping(address => address) private vaultProxyToFundDeployer; mapping(address => MigrationRequest) private vaultProxyToMigrationRequest; modifier onlyCurrentFundDeployer() { require( msg.sender == currentFundDeployer, "Only the current FundDeployer can call this function" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only the contract owner can call this function"); _; } constructor() public { migrationTimelock = 2 days; owner = msg.sender; sharesTokenSymbol = "ENZF"; } ///////////// // GENERAL // ///////////// /// @notice Sets a new `symbol` value for VaultProxy instances /// @param _nextSymbol The symbol value to set function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner { sharesTokenSymbol = _nextSymbol; emit SharesTokenSymbolSet(_nextSymbol); } //////////////////// // ACCESS CONTROL // //////////////////// /// @notice Claim ownership of the contract function claimOwnership() external override { address nextOwner = nominatedOwner; require( msg.sender == nextOwner, "claimOwnership: Only the nominatedOwner can call this function" ); delete nominatedOwner; address prevOwner = owner; owner = nextOwner; emit OwnershipTransferred(prevOwner, nextOwner); } /// @notice Revoke the nomination of a new contract owner function removeNominatedOwner() external override onlyOwner { address removedNominatedOwner = nominatedOwner; require( removedNominatedOwner != address(0), "removeNominatedOwner: There is no nominated owner" ); delete nominatedOwner; emit NominatedOwnerRemoved(removedNominatedOwner); } /// @notice Set a new FundDeployer for use within the contract /// @param _nextFundDeployer The address of the FundDeployer contract function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner { require( _nextFundDeployer != address(0), "setCurrentFundDeployer: _nextFundDeployer cannot be empty" ); require( __isContract(_nextFundDeployer), "setCurrentFundDeployer: Non-contract _nextFundDeployer" ); address prevFundDeployer = currentFundDeployer; require( _nextFundDeployer != prevFundDeployer, "setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer" ); currentFundDeployer = _nextFundDeployer; emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer); } /// @notice Nominate a new contract owner /// @param _nextNominatedOwner The account to nominate /// @dev Does not prohibit overwriting the current nominatedOwner function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner { require( _nextNominatedOwner != address(0), "setNominatedOwner: _nextNominatedOwner cannot be empty" ); require( _nextNominatedOwner != owner, "setNominatedOwner: _nextNominatedOwner is already the owner" ); require( _nextNominatedOwner != nominatedOwner, "setNominatedOwner: _nextNominatedOwner is already nominated" ); nominatedOwner = _nextNominatedOwner; emit NominatedOwnerSet(_nextNominatedOwner); } /// @dev Helper to check whether an address is a deployed contract function __isContract(address _who) private view returns (bool isContract_) { uint256 size; assembly { size := extcodesize(_who) } return size > 0; } //////////////// // DEPLOYMENT // //////////////// /// @notice Deploys a VaultProxy /// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy /// @param _owner The account to set as the VaultProxy's owner /// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor /// @param _fundName The name of the fund /// @dev Input validation should be handled by the VaultProxy during deployment function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external override onlyCurrentFundDeployer returns (address vaultProxy_) { require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor"); bytes memory constructData = abi.encodeWithSelector( IMigratableVault.init.selector, _owner, _vaultAccessor, _fundName ); vaultProxy_ = address(new VaultProxy(constructData, _vaultLib)); address fundDeployer = msg.sender; vaultProxyToFundDeployer[vaultProxy_] = fundDeployer; emit VaultProxyDeployed( fundDeployer, _owner, vaultProxy_, _vaultLib, _vaultAccessor, _fundName ); return vaultProxy_; } //////////////// // MIGRATIONS // //////////////// /// @notice Cancels a pending migration request /// @param _vaultProxy The VaultProxy contract for which to cancel the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored /// @dev Because this function must also be callable by a permissioned migrator, it has an /// extra migration hook to the nextFundDeployer for the case where cancelMigration() /// is called directly (rather than via the nextFundDeployer). function cancelMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require(nextFundDeployer != address(0), "cancelMigration: No migration request exists"); // TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works. require( msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender), "cancelMigration: Not an allowed caller" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; uint256 executableTimestamp = request.executableTimestamp; delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostCancel, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); __invokeMigrationInCancelHook( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationCancelled( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Executes a pending migration request /// @param _vaultProxy The VaultProxy contract for which to execute the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored function executeMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require( nextFundDeployer != address(0), "executeMigration: No migration request exists for _vaultProxy" ); require( msg.sender == nextFundDeployer, "executeMigration: Only the target FundDeployer can call this function" ); require( nextFundDeployer == currentFundDeployer, "executeMigration: The target FundDeployer is no longer the current FundDeployer" ); uint256 executableTimestamp = request.executableTimestamp; require( block.timestamp >= executableTimestamp, "executeMigration: The migration timelock has not elapsed" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); // Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib); IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor); // Update the FundDeployer that migrated the VaultProxy vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer; // Remove the migration request delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationExecuted( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Sets a new migration timelock /// @param _nextTimelock The number of seconds for the new timelock function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner { uint256 prevTimelock = migrationTimelock; require( _nextTimelock != prevTimelock, "setMigrationTimelock: _nextTimelock is the current timelock" ); migrationTimelock = _nextTimelock; emit MigrationTimelockSet(prevTimelock, _nextTimelock); } /// @notice Signals a migration by creating a migration request /// @param _vaultProxy The VaultProxy contract for which to signal migration /// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy /// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy /// @param _bypassFailure True if a failure in either migration hook should be ignored function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external override onlyCurrentFundDeployer { require( __isContract(_nextVaultAccessor), "signalMigration: Non-contract _nextVaultAccessor" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist"); address nextFundDeployer = msg.sender; require( nextFundDeployer != prevFundDeployer, "signalMigration: Can only migrate to a new FundDeployer" ); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); uint256 executableTimestamp = block.timestamp + migrationTimelock; vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({ nextFundDeployer: nextFundDeployer, nextVaultAccessor: _nextVaultAccessor, nextVaultLib: _nextVaultLib, executableTimestamp: executableTimestamp }); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); emit MigrationSignaled( _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, executableTimestamp ); } /// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to, /// which can optionally be implemented on the FundDeployer function __invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _nextFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationInCancelHook.selector, _vaultProxy, _prevFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked("MigrationOutCancelHook: ", returnData)) ); emit MigrationInCancelHookFailed( returnData, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of, /// which can optionally be implemented on the FundDeployer function __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook _hook, address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _prevFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationOutHook.selector, _hook, _vaultProxy, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData)) ); emit MigrationOutHookFailed( returnData, _hook, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to return a revert reason string prefix for a given MigrationOutHook function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook) private pure returns (string memory failureReasonPrefix_) { if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) { return "MigrationOutHook.PreSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) { return "MigrationOutHook.PostSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) { return "MigrationOutHook.PreMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) { return "MigrationOutHook.PostMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) { return "MigrationOutHook.PostCancel: "; } return ""; } /////////////////// // STATE GETTERS // /////////////////// // Provides several potentially helpful getters that are not strictly necessary /// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds /// @return currentFundDeployer_ The current FundDeployer contract address function getCurrentFundDeployer() external view override returns (address currentFundDeployer_) { return currentFundDeployer; } /// @notice Gets the FundDeployer with which a given VaultProxy is associated /// @param _vaultProxy The VaultProxy instance /// @return fundDeployer_ The FundDeployer contract address function getFundDeployerForVaultProxy(address _vaultProxy) external view override returns (address fundDeployer_) { return vaultProxyToFundDeployer[_vaultProxy]; } /// @notice Gets the details of a pending migration request for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return nextFundDeployer_ The FundDeployer contract address from which the migration /// request was made /// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy /// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy /// @return executableTimestamp_ The timestamp at which the migration request can be executed function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view override returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ) { MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy]; if (r.executableTimestamp > 0) { return ( r.nextFundDeployer, r.nextVaultAccessor, r.nextVaultLib, r.executableTimestamp ); } } /// @notice Gets the amount of time that must pass between signaling and executing a migration /// @return migrationTimelock_ The timelock value (in seconds) function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) { return migrationTimelock; } /// @notice Gets the account that is nominated to be the next owner of this contract /// @return nominatedOwner_ The account that is nominated to be the owner function getNominatedOwner() external view override returns (address nominatedOwner_) { return nominatedOwner; } /// @notice Gets the owner of this contract /// @return owner_ The account that is the owner function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the shares token `symbol` value for use in VaultProxy instances /// @return sharesTokenSymbol_ The `symbol` value function getSharesTokenSymbol() external view override returns (string memory sharesTokenSymbol_) { return sharesTokenSymbol; } /// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed /// @param _vaultProxy The VaultProxy instance /// @return secondsRemaining_ The number of seconds remaining on the timelock function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view override returns (uint256 secondsRemaining_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; if (executableTimestamp == 0) { return 0; } if (block.timestamp >= executableTimestamp) { return 0; } return executableTimestamp - block.timestamp; } /// @notice Checks whether a migration request that is executable exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasExecutableRequest_ True if a migration request exists and is executable function hasExecutableMigrationRequest(address _vaultProxy) external view override returns (bool hasExecutableRequest_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; return executableTimestamp > 0 && block.timestamp >= executableTimestamp; } /// @notice Checks whether a migration request exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasMigrationRequest_ True if a migration request exists function hasMigrationRequest(address _vaultProxy) external view override returns (bool hasMigrationRequest_) { return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../persistent/vault/VaultLibBaseCore.sol"; /// @title MockVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A mock VaultLib implementation that only extends VaultLibBaseCore contract MockVaultLib is VaultLibBaseCore { function getAccessor() external view returns (address) { return accessor; } function getCreator() external view returns (address) { return creator; } function getMigrator() external view returns (address) { return migrator; } function getOwner() external view returns (address) { return owner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title ICERC20 Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound tokens (cTokens) interface ICERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256) external returns (uint256); function redeem(uint256) external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CompoundPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Compound Tokens (cTokens) contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event CTokenAdded(address indexed cToken, address indexed token); uint256 private constant CTOKEN_RATE_DIVISOR = 10**18; mapping(address => address) private cTokenToToken; constructor( address _dispatcher, address _weth, address _ceth, address[] memory cERC20Tokens ) public DispatcherOwnerMixin(_dispatcher) { // Set cEth cTokenToToken[_ceth] = _weth; emit CTokenAdded(_ceth, _weth); // Set any other cTokens if (cERC20Tokens.length > 0) { __addCERC20Tokens(cERC20Tokens); } } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = cTokenToToken[_derivative]; require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative"); underlyingAmounts_ = new uint256[](1); // Returns a rate scaled to 10^18 underlyingAmounts_[0] = _derivativeAmount .mul(ICERC20(_derivative).exchangeRateStored()) .div(CTOKEN_RATE_DIVISOR); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return cTokenToToken[_asset] != address(0); } ////////////////////// // CTOKENS REGISTRY // ////////////////////// /// @notice Adds cTokens to the price feed /// @param _cTokens cTokens to add /// @dev Only allows CERC20 tokens. CEther is set in the constructor. function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner { __addCERC20Tokens(_cTokens); } /// @dev Helper to add cTokens function __addCERC20Tokens(address[] memory _cTokens) private { require(_cTokens.length > 0, "__addCTokens: Empty _cTokens"); for (uint256 i; i < _cTokens.length; i++) { require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set"); address token = ICERC20(_cTokens[i]).underlying(); cTokenToToken[_cTokens[i]] = token; emit CTokenAdded(_cTokens[i], token); } } //////////////////// // STATE GETTERS // /////////////////// /// @notice Returns the underlying asset of a given cToken /// @param _cToken The cToken for which to get the underlying asset /// @return token_ The underlying token function getTokenFromCToken(address _cToken) public view returns (address token_) { return cTokenToToken[_cToken]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../../interfaces/ICEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CompoundAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Compound <https://compound.finance/> contract CompoundAdapter is AdapterBase { address private immutable COMPOUND_PRICE_FEED; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _compoundPriceFeed, address _wethToken ) public AdapterBase(_integrationManager) { COMPOUND_PRICE_FEED = _compoundPriceFeed; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during cEther lend/redeem receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "COMPOUND"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = tokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = cToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minCTokenAmount; } else if (_selector == REDEEM_SELECTOR) { (address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = cToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = cTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); if (spendAssets[0] == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]); ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}(); } else { __approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]); ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]); } } /// @notice Redeems an amount of cTokens from Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]); if (incomingAssets[0] == WETH_TOKEN) { IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address cToken_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `COMPOUND_PRICE_FEED` variable /// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) { return COMPOUND_PRICE_FEED; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; /// @title ICEther Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound Ether interface ICEther { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title IChai Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Chai contract interface IChai is IERC20 { function exit(address, uint256) external; function join(address, uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IChai.sol"; import "../utils/AdapterBase.sol"; /// @title ChaiAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Chai <https://github.com/dapphub/chai> contract ChaiAdapter is AdapterBase { address private immutable CHAI; address private immutable DAI; constructor( address _integrationManager, address _chai, address _dai ) public AdapterBase(_integrationManager) { CHAI = _chai; DAI = _dai; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "CHAI"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = DAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = daiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = CHAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minChaiAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = CHAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = chaiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = DAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minDaiAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lend Dai for Chai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(DAI, CHAI, daiAmount); // Execute Lend on Chai // Chai.join allows specifying the vaultProxy as the destination of Chai tokens IChai(CHAI).join(_vaultProxy, daiAmount); } /// @notice Redeem Chai for Dai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs); // Execute redeem on Chai // Chai.exit sends Dai back to the adapter IChai(CHAI).exit(address(this), chaiAmount); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/SwapperBase.sol"; contract MockGenericIntegratee is SwapperBase { function swap( address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( msg.sender, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } function swapOnBehalf( address payable _trader, address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( _trader, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; import "../utils/SwapperBase.sol"; contract MockChaiIntegratee is MockToken, SwapperBase { address private immutable CENTRALIZED_RATE_PROVIDER; address public immutable DAI; constructor( address _dai, address _centralizedRateProvider, uint8 _decimals ) public MockToken("Chai", "CHAI", _decimals) { _setupDecimals(_decimals); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; DAI = _dai; } function join(address, uint256 _daiAmount) external { uint256 tokenDecimals = ERC20(DAI).decimals(); uint256 chaiDecimals = decimals(); // Calculate the amount of tokens per one unit of DAI uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI); // Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div( daiPerChaiUnit ); // Mint and send those CHAI to sender uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals); _mint(address(this), destAmount); __swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount); } function exit(address payable _trader, uint256 _chaiAmount) external { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _chaiAmount, DAI ); // Burn CHAI of the trader. _burn(_trader, _chaiAmount); // Release DAI to the trader. ERC20(DAI).transfer(msg.sender, destAmount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title AlphaHomoraV1Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/> contract AlphaHomoraV1Adapter is AdapterBase { address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _ibethToken, address _wethToken ) public AdapterBase(_integrationManager) { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during redemption receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "ALPHA_HOMORA_V1"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = wethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = IBETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIbethAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = IBETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = ibethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minWethAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends WETH for ibETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs); IWETH(payable(WETH_TOKEN)).withdraw(wethAmount); IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}(); } /// @notice Redeems ibETH for WETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs); IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAlphaHomoraV1Bank interface /// @author Enzyme Council <[email protected]> interface IAlphaHomoraV1Bank { function deposit() external payable; function totalETH() external view returns (uint256); function totalSupply() external view returns (uint256); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../IDerivativePriceFeed.sol"; /// @title AlphaHomoraV1PriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Alpha Homora v1 ibETH contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed { using SafeMath for uint256; address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor(address _ibethToken, address _wethToken) public { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH_TOKEN; underlyingAmounts_ = new uint256[](1); IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN); underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div( alphaHomoraBankContract.totalSupply() ); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == IBETH_TOKEN; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IMakerDaoPot.sol"; import "../IDerivativePriceFeed.sol"; /// @title ChaiPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Chai contract ChaiPriceFeed is IDerivativePriceFeed { using SafeMath for uint256; uint256 private constant CHI_DIVISOR = 10**27; address private immutable CHAI; address private immutable DAI; address private immutable DSR_POT; constructor( address _chai, address _dai, address _dsrPot ) public { CHAI = _chai; DAI = _dai; DSR_POT = _dsrPot; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount /// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported"); underlyings_ = new address[](1); underlyings_[0] = DAI; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div( CHI_DIVISOR ); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == CHAI; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } /// @notice Gets the `DSR_POT` variable value /// @return dsrPot_ The `DSR_POT` variable value function getDsrPot() external view returns (address dsrPot_) { return DSR_POT; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @notice Limited interface for Maker DSR's Pot contract /// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md interface IMakerDaoPot { function chi() external view returns (uint256); function rho() external view returns (uint256); function drip() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeBase.sol"; /// @title EntranceRateFeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund abstract contract EntranceRateFeeBase is FeeBase { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate); event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity); uint256 private constant RATE_DIVISOR = 10**18; IFeeManager.SettlementType private immutable SETTLEMENT_TYPE; mapping(address => uint256) private comptrollerProxyToRate; constructor(address _feeManager, IFeeManager.SettlementType _settlementType) public FeeBase(_feeManager) { require( _settlementType == IFeeManager.SettlementType.Burn || _settlementType == IFeeManager.SettlementType.Direct, "constructor: Invalid _settlementType" ); SETTLEMENT_TYPE = _settlementType; } // EXTERNAL FUNCTIONS /// @notice Add the fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 rate = abi.decode(_settingsData, (uint256)); require(rate > 0, "addFundSettings: Fee rate must be >0"); comptrollerProxyToRate[_comptrollerProxy] = rate; emit FundSettingsAdded(_comptrollerProxy, rate); } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](1); implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settles the fee /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settlementData Encoded args to use in calculating the settlement /// @return settlementType_ The type of settlement /// @return payer_ The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address, IFeeManager.FeeHook, bytes calldata _settlementData, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ) { uint256 sharesBought; (payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData); uint256 rate = comptrollerProxyToRate[_comptrollerProxy]; sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate)); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } emit Settled(_comptrollerProxy, payer_, sharesDue_); return (SETTLEMENT_TYPE, payer_, sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `rate` variable for a fund /// @param _comptrollerProxy The ComptrollerProxy contract for the fund /// @return rate_ The `rate` variable value function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) { return comptrollerProxyToRate[_comptrollerProxy]; } /// @notice Gets the `SETTLEMENT_TYPE` variable /// @return settlementType_ The `SETTLEMENT_TYPE` variable value function getSettlementType() external view returns (IFeeManager.SettlementType settlementType_) { return SETTLEMENT_TYPE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateDirectFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that transfers the fee shares to the fund manager contract EntranceRateDirectFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_DIRECT"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateBurnFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that burns the fee shares contract EntranceRateBurnFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_BURN"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract MockChaiPriceSource { using SafeMath for uint256; uint256 private chiStored = 10**27; uint256 private rhoStored = now; function drip() external returns (uint256) { require(now >= rhoStored, "drip: invalid now"); rhoStored = now; chiStored = chiStored.mul(99).div(100); return chi(); } //////////////////// // STATE GETTERS // /////////////////// function chi() public view returns (uint256) { return chiStored; } function rho() public view returns (uint256) { return rhoStored; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/DispatcherOwnerMixin.sol"; import "./IAggregatedDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); event DerivativeUpdated( address indexed derivative, address prevPriceFeed, address nextPriceFeed ); mapping(address => address) private derivativeToPriceFeed; constructor( address _dispatcher, address[] memory _derivatives, address[] memory _priceFeeds ) public DispatcherOwnerMixin(_dispatcher) { if (_derivatives.length > 0) { __addDerivatives(_derivatives, _priceFeeds); } } /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = derivativeToPriceFeed[_derivative]; require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative /// @dev This should be as low-cost and simple as possible function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return derivativeToPriceFeed[_asset] != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty"); __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty"); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty"); require( _derivatives.length == _priceFeeds.length, "updateDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]]; require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added"); require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set"); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]); } } /// @dev Helper to add derivative-feed pairs function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) private { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative"); require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed"); require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) external view override returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } }
@notice Gets the account that is nominated to be the next owner of this contract @return nominatedOwner_ The account that is nominated to be the owner
function getNominatedOwner() external view override returns (address nominatedOwner_) { return nominatedOwner; }
1,698,195
[ 1, 3002, 326, 2236, 716, 353, 12457, 7458, 358, 506, 326, 1024, 3410, 434, 333, 6835, 327, 12457, 7458, 5541, 67, 1021, 2236, 716, 353, 12457, 7458, 358, 506, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 11069, 362, 7458, 5541, 1435, 3903, 1476, 3849, 1135, 261, 2867, 12457, 7458, 5541, 67, 13, 288, 203, 3639, 327, 12457, 7458, 5541, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/82/0x406a4AD5E9F9D82f41a1C9afeDED61e8F6c4A351/sources/flattened/XCAmple.sol
* @dev XCAmpleController notifies this contract about a new rebase cycle. @param epoch The rebase epoch number. @param newGlobalAMPLSupply The new total supply of AMPL from the base chain. @return The new total AMPL supply./
function rebase(uint256 epoch, uint256 newGlobalAMPLSupply) external onlyController returns (uint256) { uint256 prevGlobalAMPLSupply = globalAMPLSupply; if (newGlobalAMPLSupply == prevGlobalAMPLSupply) { emit LogRebase(epoch, prevGlobalAMPLSupply); return prevGlobalAMPLSupply; } emit LogRebase(epoch, newGlobalAMPLSupply); return newGlobalAMPLSupply; }
16,896,349
[ 1, 60, 3587, 1291, 298, 2933, 19527, 333, 6835, 2973, 279, 394, 283, 1969, 8589, 18, 225, 7632, 1021, 283, 1969, 7632, 1300, 18, 225, 394, 5160, 8900, 3045, 416, 1283, 1021, 394, 2078, 14467, 434, 432, 4566, 48, 628, 326, 1026, 2687, 18, 327, 1021, 394, 2078, 432, 4566, 48, 14467, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 283, 1969, 12, 11890, 5034, 7632, 16, 2254, 5034, 394, 5160, 8900, 3045, 416, 1283, 13, 203, 3639, 3903, 203, 3639, 1338, 2933, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 2807, 5160, 8900, 3045, 416, 1283, 273, 2552, 8900, 3045, 416, 1283, 31, 203, 3639, 309, 261, 2704, 5160, 8900, 3045, 416, 1283, 422, 2807, 5160, 8900, 3045, 416, 1283, 13, 288, 203, 5411, 3626, 1827, 426, 1969, 12, 12015, 16, 2807, 5160, 8900, 3045, 416, 1283, 1769, 203, 5411, 327, 2807, 5160, 8900, 3045, 416, 1283, 31, 203, 3639, 289, 203, 203, 203, 203, 203, 3639, 3626, 1827, 426, 1969, 12, 12015, 16, 394, 5160, 8900, 3045, 416, 1283, 1769, 203, 203, 3639, 327, 394, 5160, 8900, 3045, 416, 1283, 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 ]
./full_match/97/0x1c4eA5BBC27d20Fd4a7B6aEc21C109fE24eDA9e8/sources/contracts/protocol/libraries/logic/BorrowLogic.sol
* @notice Implements the borrow feature. Borrowing allows users that provided collateral to draw liquidity from the Aave protocol proportionally to their collateralization power. For isolated positions, it also increases the isolated debt. @dev Emits the `Borrow()` event @param reservesData The state of all the reserves @param reservesList The addresses of all the active reserves @param eModeCategories The configuration of all the efficiency mode categories @param userConfig The user configuration mapping that tracks the supplied/borrowed assets @param params The additional parameters needed to execute the borrow function/
) public { DataTypes.ReserveData storage reserve = reservesData[params.asset]; DataTypes.ReserveCache memory reserveCache = reserve.cache(); reserve.updateState(reserveCache); ( bool isolationModeActive, address isolationModeCollateralAddress, uint256 isolationModeDebtCeiling ) = userConfig.getIsolationModeState(reservesData, reservesList); ValidationLogic.validateBorrow( reservesData, reservesList, eModeCategories, DataTypes.ValidateBorrowParams({ reserveCache: reserveCache, userConfig: userConfig, asset: params.asset, userAddress: params.onBehalfOf, amount: params.amount, interestRateMode: params.interestRateMode, maxStableLoanPercent: params.maxStableRateBorrowSizePercent, reservesCount: params.reservesCount, oracle: params.oracle, userEModeCategory: params.userEModeCategory, priceOracleSentinel: params.priceOracleSentinel, isolationModeActive: isolationModeActive, isolationModeCollateralAddress: isolationModeCollateralAddress, isolationModeDebtCeiling: isolationModeDebtCeiling }) ); uint256 currentStableRate = 0; bool isFirstBorrowing = false; if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) { currentStableRate = reserve.currentStableBorrowRate; ( isFirstBorrowing, reserveCache.nextTotalStableDebt, reserveCache.nextAvgStableBorrowRate ) = IStableDebtToken(reserveCache.stableDebtTokenAddress).mint( params.user, params.onBehalfOf, params.amount, currentStableRate ); (isFirstBorrowing, reserveCache.nextScaledVariableDebt) = IVariableDebtToken( reserveCache.variableDebtTokenAddress ).mint(params.user, params.onBehalfOf, params.amount, reserveCache.nextVariableBorrowIndex); } if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } if (isolationModeActive) { uint256 nextIsolationModeTotalDebt = reservesData[isolationModeCollateralAddress] .isolationModeTotalDebt += (params.amount / 10 ** (reserveCache.reserveConfiguration.getDecimals() - ReserveConfiguration.DEBT_CEILING_DECIMALS)).toUint128(); emit IsolationModeTotalDebtUpdated( isolationModeCollateralAddress, nextIsolationModeTotalDebt ); } reserve.updateInterestRates( reserveCache, params.asset, 0, params.releaseUnderlying ? params.amount : 0 ); if (params.releaseUnderlying) { IAToken(reserveCache.aTokenAddress).transferUnderlyingTo(params.user, params.amount); } emit Borrow( params.asset, params.user, params.onBehalfOf, params.amount, params.interestRateMode, params.interestRateMode == DataTypes.InterestRateMode.STABLE ? currentStableRate : reserve.currentVariableBorrowRate, params.referralCode ); }
3,271,281
[ 1, 17516, 326, 29759, 2572, 18, 605, 15318, 310, 5360, 3677, 716, 2112, 4508, 2045, 287, 358, 3724, 4501, 372, 24237, 628, 326, 432, 836, 1771, 23279, 1230, 358, 3675, 4508, 2045, 287, 1588, 7212, 18, 2457, 25790, 6865, 16, 518, 2546, 7033, 3304, 326, 25790, 18202, 88, 18, 282, 7377, 1282, 326, 1375, 38, 15318, 20338, 871, 225, 400, 264, 3324, 751, 1021, 919, 434, 777, 326, 400, 264, 3324, 225, 400, 264, 3324, 682, 1021, 6138, 434, 777, 326, 2695, 400, 264, 3324, 225, 425, 2309, 10487, 1021, 1664, 434, 777, 326, 30325, 1965, 6477, 225, 729, 809, 1021, 729, 1664, 2874, 716, 13933, 326, 4580, 19, 70, 15318, 329, 7176, 225, 859, 1021, 3312, 1472, 3577, 358, 1836, 326, 29759, 445, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 262, 1071, 288, 203, 565, 1910, 2016, 18, 607, 6527, 751, 2502, 20501, 273, 400, 264, 3324, 751, 63, 2010, 18, 9406, 15533, 203, 565, 1910, 2016, 18, 607, 6527, 1649, 3778, 20501, 1649, 273, 20501, 18, 2493, 5621, 203, 203, 565, 20501, 18, 2725, 1119, 12, 455, 6527, 1649, 1769, 203, 203, 565, 261, 203, 1377, 1426, 25155, 2309, 3896, 16, 203, 1377, 1758, 25155, 2309, 13535, 2045, 287, 1887, 16, 203, 1377, 2254, 5034, 25155, 2309, 758, 23602, 39, 73, 4973, 203, 565, 262, 273, 729, 809, 18, 588, 22982, 2309, 1119, 12, 455, 264, 3324, 751, 16, 400, 264, 3324, 682, 1769, 203, 203, 565, 5684, 20556, 18, 5662, 38, 15318, 12, 203, 1377, 400, 264, 3324, 751, 16, 203, 1377, 400, 264, 3324, 682, 16, 203, 1377, 425, 2309, 10487, 16, 203, 1377, 1910, 2016, 18, 4270, 38, 15318, 1370, 12590, 203, 3639, 20501, 1649, 30, 20501, 1649, 16, 203, 3639, 729, 809, 30, 729, 809, 16, 203, 3639, 3310, 30, 859, 18, 9406, 16, 203, 3639, 729, 1887, 30, 859, 18, 265, 1919, 20222, 951, 16, 203, 3639, 3844, 30, 859, 18, 8949, 16, 203, 3639, 16513, 4727, 2309, 30, 859, 18, 2761, 395, 4727, 2309, 16, 203, 3639, 943, 30915, 1504, 304, 8410, 30, 859, 18, 1896, 30915, 4727, 38, 15318, 1225, 8410, 16, 203, 3639, 400, 264, 3324, 1380, 30, 859, 18, 455, 264, 3324, 1380, 16, 203, 3639, 20865, 30, 859, 18, 280, 16066, 16, 203, 3639, 729, 41, 2309, 4457, 30, 859, 18, 1355, 2 ]
./partial_match/1/0x99373AE646ed89b9A466c4256b09b10dbCC07B40/sources/contracts/concentrator/AladdinConvexVault.sol
The address of cvxCRV token.
address internal constant CVXCRV = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7;
9,294,014
[ 1, 1986, 1758, 434, 8951, 92, 5093, 58, 1147, 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, 225, 1758, 2713, 5381, 385, 58, 60, 5093, 58, 273, 374, 92, 8898, 38, 29, 71, 9036, 4313, 37, 22, 40, 71, 1105, 69, 3657, 8148, 73, 3657, 39, 4366, 73, 24, 74, 25, 7235, 42, 10689, 2163, 37, 69, 27, 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 ]
pragma solidity ^0.5.0; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/access/Roles.sol /** * @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(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: contracts/controller/Permissions/RootPlatformAdministratorRole.sol /* Copyright 2018, CONDA 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 RootPlatformAdministratorRole root user role mainly to manage other roles. */ contract RootPlatformAdministratorRole { using Roles for Roles.Role; /////////////////// // Events /////////////////// event RootPlatformAdministratorAdded(address indexed account); event RootPlatformAdministratorRemoved(address indexed account); /////////////////// // Variables /////////////////// Roles.Role private rootPlatformAdministrators; /////////////////// // Constructor /////////////////// constructor() internal { _addRootPlatformAdministrator(msg.sender); } /////////////////// // Modifiers /////////////////// modifier onlyRootPlatformAdministrator() { require(isRootPlatformAdministrator(msg.sender), "no root PFadmin"); _; } /////////////////// // Functions /////////////////// function isRootPlatformAdministrator(address account) public view returns (bool) { return rootPlatformAdministrators.has(account); } function addRootPlatformAdministrator(address account) public onlyRootPlatformAdministrator { _addRootPlatformAdministrator(account); } function renounceRootPlatformAdministrator() public { _removeRootPlatformAdministrator(msg.sender); } function _addRootPlatformAdministrator(address account) internal { rootPlatformAdministrators.add(account); emit RootPlatformAdministratorAdded(account); } function _removeRootPlatformAdministrator(address account) internal { rootPlatformAdministrators.remove(account); emit RootPlatformAdministratorRemoved(account); } } // File: contracts/controller/Permissions/AssetTokenAdministratorRole.sol /* Copyright 2018, CONDA 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 AssetTokenAdministratorRole of AssetToken administrators. */ contract AssetTokenAdministratorRole is RootPlatformAdministratorRole { /////////////////// // Events /////////////////// event AssetTokenAdministratorAdded(address indexed account); event AssetTokenAdministratorRemoved(address indexed account); /////////////////// // Variables /////////////////// Roles.Role private assetTokenAdministrators; /////////////////// // Constructor /////////////////// constructor() internal { _addAssetTokenAdministrator(msg.sender); } /////////////////// // Modifiers /////////////////// modifier onlyAssetTokenAdministrator() { require(isAssetTokenAdministrator(msg.sender), "no ATadmin"); _; } /////////////////// // Functions /////////////////// function isAssetTokenAdministrator(address _account) public view returns (bool) { return assetTokenAdministrators.has(_account); } function addAssetTokenAdministrator(address _account) public onlyRootPlatformAdministrator { _addAssetTokenAdministrator(_account); } function renounceAssetTokenAdministrator() public { _removeAssetTokenAdministrator(msg.sender); } function _addAssetTokenAdministrator(address _account) internal { assetTokenAdministrators.add(_account); emit AssetTokenAdministratorAdded(_account); } function removeAssetTokenAdministrator(address _account) public onlyRootPlatformAdministrator { _removeAssetTokenAdministrator(_account); } function _removeAssetTokenAdministrator(address _account) internal { assetTokenAdministrators.remove(_account); emit AssetTokenAdministratorRemoved(_account); } } // File: contracts/controller/Permissions/At2CsConnectorRole.sol /* Copyright 2018, CONDA 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 At2CsConnectorRole AssetToken to Crowdsale connector role. */ contract At2CsConnectorRole is RootPlatformAdministratorRole { /////////////////// // Events /////////////////// event At2CsConnectorAdded(address indexed account); event At2CsConnectorRemoved(address indexed account); /////////////////// // Variables /////////////////// Roles.Role private at2csConnectors; /////////////////// // Constructor /////////////////// constructor() internal { _addAt2CsConnector(msg.sender); } /////////////////// // Modifiers /////////////////// modifier onlyAt2CsConnector() { require(isAt2CsConnector(msg.sender), "no at2csAdmin"); _; } /////////////////// // Functions /////////////////// function isAt2CsConnector(address _account) public view returns (bool) { return at2csConnectors.has(_account); } function addAt2CsConnector(address _account) public onlyRootPlatformAdministrator { _addAt2CsConnector(_account); } function renounceAt2CsConnector() public { _removeAt2CsConnector(msg.sender); } function _addAt2CsConnector(address _account) internal { at2csConnectors.add(_account); emit At2CsConnectorAdded(_account); } function removeAt2CsConnector(address _account) public onlyRootPlatformAdministrator { _removeAt2CsConnector(_account); } function _removeAt2CsConnector(address _account) internal { at2csConnectors.remove(_account); emit At2CsConnectorRemoved(_account); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } // File: contracts/controller/0_library/DSMathL.sol // fork from ds-math specifically my librarization fork: https://raw.githubusercontent.com/JohannesMayerConda/ds-math/master/contracts/DSMathL.sol /// math.sol -- mixin for inline numerical wizardry // 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/>. library DSMathL { function ds_add(uint x, uint y) public pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function ds_sub(uint x, uint y) public pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function ds_mul(uint x, uint y) public pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function ds_min(uint x, uint y) public pure returns (uint z) { return x <= y ? x : y; } function ds_max(uint x, uint y) public pure returns (uint z) { return x >= y ? x : y; } function ds_imin(int x, int y) public pure returns (int z) { return x <= y ? x : y; } function ds_imax(int x, int y) public pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function ds_wmul(uint x, uint y) public pure returns (uint z) { z = ds_add(ds_mul(x, y), WAD / 2) / WAD; } function ds_rmul(uint x, uint y) public pure returns (uint z) { z = ds_add(ds_mul(x, y), RAY / 2) / RAY; } function ds_wdiv(uint x, uint y) public pure returns (uint z) { z = ds_add(ds_mul(x, WAD), y / 2) / y; } function ds_rdiv(uint x, uint y) public pure returns (uint z) { z = ds_add(ds_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 ds_rpow(uint x, uint n) public pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = ds_rmul(x, x); if (n % 2 != 0) { z = ds_rmul(z, x); } } } } // File: contracts/controller/Permissions/YourOwnable.sol // 1:1 copy of https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.1/contracts/ownership/Ownable.sol // except constructor that can instantly transfer ownership contract YourOwnable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor (address newOwner) public { _transferOwnership(newOwner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/controller/FeeTable/StandardFeeTable.sol /* Copyright 2018, CONDA 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 StandardFeeTable contract to store fees via name (fees per platform for certain name). */ contract StandardFeeTable is YourOwnable { using SafeMath for uint256; /////////////////// // Constructor /////////////////// constructor (address newOwner) YourOwnable(newOwner) public {} /////////////////// // Variables /////////////////// uint256 public defaultFee; mapping (bytes32 => uint256) public feeFor; mapping (bytes32 => bool) public isFeeDisabled; /////////////////// // Functions /////////////////// /// @notice Set default fee (when nothing else applies). /// @param _defaultFee default fee value. Unit is WAD so fee 1 means value=1e18. function setDefaultFee(uint256 _defaultFee) public onlyOwner { defaultFee = _defaultFee; } /// @notice Set fee by name. /// @param _feeName fee name. /// @param _feeValue fee value. Unit is WAD so fee 1 means value=1e18. function setFee(bytes32 _feeName, uint256 _feeValue) public onlyOwner { feeFor[_feeName] = _feeValue; } /// @notice Enable or disable fee by name. /// @param _feeName fee name. /// @param _feeDisabled true if fee should be disabled. function setFeeMode(bytes32 _feeName, bool _feeDisabled) public onlyOwner { isFeeDisabled[_feeName] = _feeDisabled; } /// @notice Get standard fee (not overriden by special fee for specific AssetToken). /// @param _feeName fee name. /// @return fee value. Unit is WAD so fee 1 means value=1e18. function getStandardFee(bytes32 _feeName) public view returns (uint256 _feeValue) { if (isFeeDisabled[_feeName]) { return 0; } if(feeFor[_feeName] == 0) { return defaultFee; } return feeFor[_feeName]; } /// @notice Get standard fee for amount in base unit. /// @param _feeName fee name. /// @param _amountInFeeBaseUnit amount in fee base unit (currently in unit tokens). /// @return fee value. Unit is WAD (converted it). function getStandardFeeFor(bytes32 _feeName, uint256 _amountInFeeBaseUnit) public view returns (uint256) { //1000000000000000 is 0,001 as WAD //example fee 0.001 for amount 3: 3 tokens * 1000000000000000 fee = 3000000000000000 (0.003) return _amountInFeeBaseUnit.mul(getStandardFee(_feeName)); } } // File: contracts/controller/FeeTable/FeeTable.sol /* Copyright 2018, CONDA 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 FeeTable contract to store fees via name (fees per platform per assettoken for certain name). */ contract FeeTable is StandardFeeTable { /////////////////// // Constructor /////////////////// constructor (address newOwner) StandardFeeTable(newOwner) public {} /////////////////// // Mappings /////////////////// // specialfee mapping feeName -> token -> fee mapping (bytes32 => mapping (address => uint256)) public specialFeeFor; // specialfee mapping feeName -> token -> isSet mapping (bytes32 => mapping (address => bool)) public isSpecialFeeEnabled; /////////////////// // Functions /////////////////// /// @notice Set a special fee specifically for an AssetToken (higher or lower than normal fee). /// @param _feeName fee name. /// @param _regardingAssetToken regarding AssetToken. /// @param _feeValue fee value. Unit is WAD so fee 1 means value=1e18. function setSpecialFee(bytes32 _feeName, address _regardingAssetToken, uint256 _feeValue) public onlyOwner { specialFeeFor[_feeName][_regardingAssetToken] = _feeValue; } /// @notice Enable or disable special fee. /// @param _feeName fee name. /// @param _regardingAssetToken regarding AssetToken. /// @param _feeEnabled true to enable fee. function setSpecialFeeMode(bytes32 _feeName, address _regardingAssetToken, bool _feeEnabled) public onlyOwner { isSpecialFeeEnabled[_feeName][_regardingAssetToken] = _feeEnabled; } /// @notice Get fee by name. /// @param _feeName fee name. /// @param _regardingAssetToken regarding AssetToken. /// @return fee value. Unit is WAD so fee 11 means value=1e18. function getFee(bytes32 _feeName, address _regardingAssetToken) public view returns (uint256) { if (isFeeDisabled[_feeName]) { return 0; } if (isSpecialFeeEnabled[_feeName][_regardingAssetToken]) { return specialFeeFor[_feeName][_regardingAssetToken]; } return super.getStandardFee(_feeName); } /// @notice Get fee for amount in base unit. /// @param _feeName fee name. /// @param _regardingAssetToken regarding AssetToken. /// @param _amountInFeeBaseUnit amount in fee base unit (currently in unit tokens). /// @return fee value. Unit is WAD (converted it). function getFeeFor(bytes32 _feeName, address _regardingAssetToken, uint256 _amountInFeeBaseUnit, address /*oracle*/) public view returns (uint256) { uint256 fee = getFee(_feeName, _regardingAssetToken); //1000000000000000 is 0,001 as WAD //example fee 0.001 for amount 3: 3 tokens * 1000000000000000 fee = 3000000000000000 (0.003) return _amountInFeeBaseUnit.mul(fee); } } // File: contracts/controller/Permissions/WhitelistControlRole.sol /* Copyright 2018, CONDA 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 WhitelistControlRole role to administrate whitelist and KYC. */ contract WhitelistControlRole is RootPlatformAdministratorRole { /////////////////// // Events /////////////////// event WhitelistControlAdded(address indexed account); event WhitelistControlRemoved(address indexed account); /////////////////// // Variables /////////////////// Roles.Role private whitelistControllers; /////////////////// // Constructor /////////////////// constructor() internal { _addWhitelistControl(msg.sender); } /////////////////// // Modifiers /////////////////// modifier onlyWhitelistControl() { require(isWhitelistControl(msg.sender), "no WLcontrol"); _; } /////////////////// // Functions /////////////////// function isWhitelistControl(address account) public view returns (bool) { return whitelistControllers.has(account); } function addWhitelistControl(address account) public onlyRootPlatformAdministrator { _addWhitelistControl(account); } function _addWhitelistControl(address account) internal { whitelistControllers.add(account); emit WhitelistControlAdded(account); } function removeWhitelistControl(address account) public onlyRootPlatformAdministrator { whitelistControllers.remove(account); emit WhitelistControlRemoved(account); } } // File: contracts/controller/interface/IWhitelistAutoExtendExpirationExecutor.sol interface IWhitelistAutoExtendExpirationExecutor { function recheckIdentity(address _wallet, address _investorKey, address _issuer) external; } // File: contracts/controller/interface/IWhitelistAutoExtendExpirationCallback.sol interface IWhitelistAutoExtendExpirationCallback { function updateIdentity(address _wallet, bool _isWhitelisted, address _investorKey, address _issuer) external; } // File: contracts/controller/Whitelist/Whitelist.sol /** @title Whitelist stores whitelist information of investors like if and when they were KYC checked. */ contract Whitelist is WhitelistControlRole, IWhitelistAutoExtendExpirationCallback { using SafeMath for uint256; /////////////////// // Variables /////////////////// uint256 public expirationBlocks; bool public expirationEnabled; bool public autoExtendExpiration; address public autoExtendExpirationContract; mapping (address => bool) whitelistedWallet; mapping (address => uint256) lastIdentityVerificationDate; mapping (address => address) whitelistedWalletIssuer; mapping (address => address) walletToInvestorKey; /////////////////// // Events /////////////////// event WhitelistChanged(address indexed wallet, bool whitelisted, address investorKey, address issuer); event ExpirationBlocksChanged(address initiator, uint256 addedBlocksSinceWhitelisting); event ExpirationEnabled(address initiator, bool expirationEnabled); event UpdatedIdentity(address initiator, address indexed wallet, bool whitelisted, address investorKey, address issuer); event SetAutoExtendExpirationContract(address initiator, address expirationContract); event UpdatedAutoExtendExpiration(address initiator, bool autoExtendEnabled); /////////////////// // Functions /////////////////// function getIssuer(address _whitelistedWallet) public view returns (address) { return whitelistedWalletIssuer[_whitelistedWallet]; } function getInvestorKey(address _wallet) public view returns (address) { return walletToInvestorKey[_wallet]; } function setWhitelisted(address _wallet, bool _isWhitelisted, address _investorKey, address _issuer) public onlyWhitelistControl { whitelistedWallet[_wallet] = _isWhitelisted; lastIdentityVerificationDate[_wallet] = block.number; whitelistedWalletIssuer[_wallet] = _issuer; assignWalletToInvestorKey(_wallet, _investorKey); emit WhitelistChanged(_wallet, _isWhitelisted, _investorKey, _issuer); } function assignWalletToInvestorKey(address _wallet, address _investorKey) public onlyWhitelistControl { walletToInvestorKey[_wallet] = _investorKey; } //note: no view keyword here because IWhitelistAutoExtendExpirationExecutor could change state via callback function checkWhitelistedWallet(address _wallet) public returns (bool) { if(autoExtendExpiration && isExpired(_wallet)) { address investorKey = walletToInvestorKey[_wallet]; address issuer = whitelistedWalletIssuer[_wallet]; require(investorKey != address(0), "expired, unknown identity"); //IMPORTANT: reentrance hook. make sure calling contract is safe IWhitelistAutoExtendExpirationExecutor(autoExtendExpirationContract).recheckIdentity(_wallet, investorKey, issuer); } require(!isExpired(_wallet), "whitelist expired"); require(whitelistedWallet[_wallet], "not whitelisted"); return true; } function isWhitelistedWallet(address _wallet) public view returns (bool) { if(isExpired(_wallet)) { return false; } return whitelistedWallet[_wallet]; } function isExpired(address _wallet) private view returns (bool) { return expirationEnabled && block.number > lastIdentityVerificationDate[_wallet].add(expirationBlocks); } function blocksLeftUntilExpired(address _wallet) public view returns (uint256) { require(expirationEnabled, "expiration disabled"); return lastIdentityVerificationDate[_wallet].add(expirationBlocks).sub(block.number); } function setExpirationBlocks(uint256 _addedBlocksSinceWhitelisting) public onlyRootPlatformAdministrator { expirationBlocks = _addedBlocksSinceWhitelisting; emit ExpirationBlocksChanged(msg.sender, _addedBlocksSinceWhitelisting); } function setExpirationEnabled(bool _isEnabled) public onlyRootPlatformAdministrator { expirationEnabled = _isEnabled; emit ExpirationEnabled(msg.sender, expirationEnabled); } function setAutoExtendExpirationContract(address _autoExtendContract) public onlyRootPlatformAdministrator { autoExtendExpirationContract = _autoExtendContract; emit SetAutoExtendExpirationContract(msg.sender, _autoExtendContract); } function setAutoExtendExpiration(bool _autoExtendEnabled) public onlyRootPlatformAdministrator { autoExtendExpiration = _autoExtendEnabled; emit UpdatedAutoExtendExpiration(msg.sender, _autoExtendEnabled); } function updateIdentity(address _wallet, bool _isWhitelisted, address _investorKey, address _issuer) public onlyWhitelistControl { setWhitelisted(_wallet, _isWhitelisted, _investorKey, _issuer); emit UpdatedIdentity(msg.sender, _wallet, _isWhitelisted, _investorKey, _issuer); } } // File: contracts/controller/interface/IExchangeRateOracle.sol contract IExchangeRateOracle { function resetCurrencyPair(address _currencyA, address _currencyB) public; function configureCurrencyPair(address _currencyA, address _currencyB, uint256 maxNextUpdateInBlocks) public; function setExchangeRate(address _currencyA, address _currencyB, uint256 _rateFromTo, uint256 _rateToFrom) public; function getExchangeRate(address _currencyA, address _currencyB) public view returns (uint256); function convert(address _currencyA, address _currencyB, uint256 _amount) public view returns (uint256); function convertTT(bytes32 _currencyAText, bytes32 _currencyBText, uint256 _amount) public view returns (uint256); function convertTA(bytes32 _currencyAText, address _currencyB, uint256 _amount) public view returns (uint256); function convertAT(address _currencyA, bytes32 _currencyBText, uint256 _amount) public view returns (uint256); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: contracts/controller/interfaces/IBasicAssetToken.sol interface IBasicAssetToken { //AssetToken specific function isTokenAlive() external view returns (bool); //Mintable function mint(address _to, uint256 _amount) external returns (bool); function finishMinting() external returns (bool); } // File: contracts/controller/Permissions/StorageAdministratorRole.sol /* Copyright 2018, CONDA 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 StorageAdministratorRole role to administrate generic storage. */ contract StorageAdministratorRole is RootPlatformAdministratorRole { /////////////////// // Events /////////////////// event StorageAdministratorAdded(address indexed account); event StorageAdministratorRemoved(address indexed account); /////////////////// // Variables /////////////////// Roles.Role private storageAdministrators; /////////////////// // Constructor /////////////////// constructor() internal { _addStorageAdministrator(msg.sender); } /////////////////// // Modifiers /////////////////// modifier onlyStorageAdministrator() { require(isStorageAdministrator(msg.sender), "no SAdmin"); _; } /////////////////// // Functions /////////////////// function isStorageAdministrator(address account) public view returns (bool) { return storageAdministrators.has(account); } function addStorageAdministrator(address account) public onlyRootPlatformAdministrator { _addStorageAdministrator(account); } function _addStorageAdministrator(address account) internal { storageAdministrators.add(account); emit StorageAdministratorAdded(account); } function removeStorageAdministrator(address account) public onlyRootPlatformAdministrator { storageAdministrators.remove(account); emit StorageAdministratorRemoved(account); } } // File: contracts/controller/Storage/storagetypes/UintStorage.sol /* Copyright 2018, CONDA 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 UintStorage uint storage. */ contract UintStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => uint256) private uintStorage; /////////////////// // Functions /////////////////// function setUint(bytes32 _name, uint256 _value) public onlyStorageAdministrator { return _setUint(_name, _value); } function getUint(bytes32 _name) public view returns (uint256) { return _getUint(_name); } function _setUint(bytes32 _name, uint256 _value) private { if(_name != "") { uintStorage[_name] = _value; } } function _getUint(bytes32 _name) private view returns (uint256) { return uintStorage[_name]; } function get2Uint( bytes32 _name1, bytes32 _name2) public view returns (uint256, uint256) { return (_getUint(_name1), _getUint(_name2)); } function get3Uint( bytes32 _name1, bytes32 _name2, bytes32 _name3) public view returns (uint256, uint256, uint256) { return (_getUint(_name1), _getUint(_name2), _getUint(_name3)); } function get4Uint( bytes32 _name1, bytes32 _name2, bytes32 _name3, bytes32 _name4) public view returns (uint256, uint256, uint256, uint256) { return (_getUint(_name1), _getUint(_name2), _getUint(_name3), _getUint(_name4)); } function get5Uint( bytes32 _name1, bytes32 _name2, bytes32 _name3, bytes32 _name4, bytes32 _name5) public view returns (uint256, uint256, uint256, uint256, uint256) { return (_getUint(_name1), _getUint(_name2), _getUint(_name3), _getUint(_name4), _getUint(_name5)); } function set2Uint( bytes32 _name1, uint256 _value1, bytes32 _name2, uint256 _value2) public onlyStorageAdministrator { _setUint(_name1, _value1); _setUint(_name2, _value2); } function set3Uint( bytes32 _name1, uint256 _value1, bytes32 _name2, uint256 _value2, bytes32 _name3, uint256 _value3) public onlyStorageAdministrator { _setUint(_name1, _value1); _setUint(_name2, _value2); _setUint(_name3, _value3); } function set4Uint( bytes32 _name1, uint256 _value1, bytes32 _name2, uint256 _value2, bytes32 _name3, uint256 _value3, bytes32 _name4, uint256 _value4) public onlyStorageAdministrator { _setUint(_name1, _value1); _setUint(_name2, _value2); _setUint(_name3, _value3); _setUint(_name4, _value4); } function set5Uint( bytes32 _name1, uint256 _value1, bytes32 _name2, uint256 _value2, bytes32 _name3, uint256 _value3, bytes32 _name4, uint256 _value4, bytes32 _name5, uint256 _value5) public onlyStorageAdministrator { _setUint(_name1, _value1); _setUint(_name2, _value2); _setUint(_name3, _value3); _setUint(_name4, _value4); _setUint(_name5, _value5); } } // File: contracts/controller/Storage/storagetypes/AddrStorage.sol /* Copyright 2018, CONDA 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 AddrStorage address storage. */ contract AddrStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => address) private addrStorage; /////////////////// // Functions /////////////////// function setAddr(bytes32 _name, address _value) public onlyStorageAdministrator { return _setAddr(_name, _value); } function getAddr(bytes32 _name) public view returns (address) { return _getAddr(_name); } function _setAddr(bytes32 _name, address _value) private { if(_name != "") { addrStorage[_name] = _value; } } function _getAddr(bytes32 _name) private view returns (address) { return addrStorage[_name]; } function get2Address( bytes32 _name1, bytes32 _name2) public view returns (address, address) { return (_getAddr(_name1), _getAddr(_name2)); } function get3Address( bytes32 _name1, bytes32 _name2, bytes32 _name3) public view returns (address, address, address) { return (_getAddr(_name1), _getAddr(_name2), _getAddr(_name3)); } function set2Address( bytes32 _name1, address _value1, bytes32 _name2, address _value2) public onlyStorageAdministrator { _setAddr(_name1, _value1); _setAddr(_name2, _value2); } function set3Address( bytes32 _name1, address _value1, bytes32 _name2, address _value2, bytes32 _name3, address _value3) public onlyStorageAdministrator { _setAddr(_name1, _value1); _setAddr(_name2, _value2); _setAddr(_name3, _value3); } } // File: contracts/controller/Storage/storagetypes/Addr2UintStorage.sol /* Copyright 2018, CONDA 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 Addr2UintStorage address to uint mapping storage. */ contract Addr2UintStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => mapping (address => uint256)) private addr2UintStorage; /////////////////// // Functions /////////////////// function setAddr2Uint(bytes32 _name, address _address, uint256 _value) public onlyStorageAdministrator { return _setAddr2Uint(_name, _address, _value); } function getAddr2Uint(bytes32 _name, address _address) public view returns (uint256) { return _getAddr2Uint(_name, _address); } function _setAddr2Uint(bytes32 _name, address _address, uint256 _value) private { if(_name != "") { addr2UintStorage[_name][_address] = _value; } } function _getAddr2Uint(bytes32 _name, address _address) private view returns (uint256) { return addr2UintStorage[_name][_address]; } function get2Addr2Uint( bytes32 _name1, address _address1, bytes32 _name2, address _address2) public view returns (uint256, uint256) { return (_getAddr2Uint(_name1, _address1), _getAddr2Uint(_name2, _address2)); } function get3Addr2Addr2Uint( bytes32 _name1, address _address1, bytes32 _name2, address _address2, bytes32 _name3, address _address3) public view returns (uint256, uint256, uint256) { return (_getAddr2Uint(_name1, _address1), _getAddr2Uint(_name2, _address2), _getAddr2Uint(_name3, _address3)); } function set2Addr2Uint( bytes32 _name1, address _address1, uint256 _value1, bytes32 _name2, address _address2, uint256 _value2) public onlyStorageAdministrator { _setAddr2Uint(_name1, _address1, _value1); _setAddr2Uint(_name2, _address2, _value2); } function set3Addr2Uint( bytes32 _name1, address _address1, uint256 _value1, bytes32 _name2, address _address2, uint256 _value2, bytes32 _name3, address _address3, uint256 _value3) public onlyStorageAdministrator { _setAddr2Uint(_name1, _address1, _value1); _setAddr2Uint(_name2, _address2, _value2); _setAddr2Uint(_name3, _address3, _value3); } } // File: contracts/controller/Storage/storagetypes/Addr2AddrStorage.sol /* Copyright 2018, CONDA 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 Addr2AddrStorage address to address mapping storage. */ contract Addr2AddrStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => mapping (address => address)) private addr2AddrStorage; /////////////////// // Functions /////////////////// function setAddr2Addr(bytes32 _name, address _address, address _value) public onlyStorageAdministrator { return _setAddr2Addr(_name, _address, _value); } function getAddr2Addr(bytes32 _name, address _address) public view returns (address) { return _getAddr2Addr(_name, _address); } function _setAddr2Addr(bytes32 _name, address _address, address _value) private { if(_name != "") { addr2AddrStorage[_name][_address] = _value; } } function _getAddr2Addr(bytes32 _name, address _address) private view returns (address) { return addr2AddrStorage[_name][_address]; } function get2Addr2Addr( bytes32 _name1, address _address1, bytes32 _name2, address _address2) public view returns (address, address) { return (_getAddr2Addr(_name1, _address1), _getAddr2Addr(_name2, _address2)); } function get3Addr2Addr2Addr( bytes32 _name1, address _address1, bytes32 _name2, address _address2, bytes32 _name3, address _address3) public view returns (address, address, address) { return (_getAddr2Addr(_name1, _address1), _getAddr2Addr(_name2, _address2), _getAddr2Addr(_name3, _address3)); } function set2Addr2Addr( bytes32 _name1, address _address1, address _value1, bytes32 _name2, address _address2, address _value2) public onlyStorageAdministrator { _setAddr2Addr(_name1, _address1, _value1); _setAddr2Addr(_name2, _address2, _value2); } function set3Addr2Addr( bytes32 _name1, address _address1, address _value1, bytes32 _name2, address _address2, address _value2, bytes32 _name3, address _address3, address _value3) public onlyStorageAdministrator { _setAddr2Addr(_name1, _address1, _value1); _setAddr2Addr(_name2, _address2, _value2); _setAddr2Addr(_name3, _address3, _value3); } } // File: contracts/controller/Storage/storagetypes/Addr2BoolStorage.sol /* Copyright 2018, CONDA 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 Addr2BoolStorage address to address mapping storage. */ contract Addr2BoolStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => mapping (address => bool)) private addr2BoolStorage; /////////////////// // Functions /////////////////// function setAddr2Bool(bytes32 _name, address _address, bool _value) public onlyStorageAdministrator { return _setAddr2Bool(_name, _address, _value); } function getAddr2Bool(bytes32 _name, address _address) public view returns (bool) { return _getAddr2Bool(_name, _address); } function _setAddr2Bool(bytes32 _name, address _address, bool _value) private { if(_name != "") { addr2BoolStorage[_name][_address] = _value; } } function _getAddr2Bool(bytes32 _name, address _address) private view returns (bool) { return addr2BoolStorage[_name][_address]; } function get2Addr2Bool( bytes32 _name1, address _address1, bytes32 _name2, address _address2) public view returns (bool, bool) { return (_getAddr2Bool(_name1, _address1), _getAddr2Bool(_name2, _address2)); } function get3Address2Address2Bool( bytes32 _name1, address _address1, bytes32 _name2, address _address2, bytes32 _name3, address _address3) public view returns (bool, bool, bool) { return (_getAddr2Bool(_name1, _address1), _getAddr2Bool(_name2, _address2), _getAddr2Bool(_name3, _address3)); } function set2Address2Bool( bytes32 _name1, address _address1, bool _value1, bytes32 _name2, address _address2, bool _value2) public onlyStorageAdministrator { _setAddr2Bool(_name1, _address1, _value1); _setAddr2Bool(_name2, _address2, _value2); } function set3Address2Bool( bytes32 _name1, address _address1, bool _value1, bytes32 _name2, address _address2, bool _value2, bytes32 _name3, address _address3, bool _value3) public onlyStorageAdministrator { _setAddr2Bool(_name1, _address1, _value1); _setAddr2Bool(_name2, _address2, _value2); _setAddr2Bool(_name3, _address3, _value3); } } // File: contracts/controller/Storage/storagetypes/BytesStorage.sol /* Copyright 2018, CONDA 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 BytesStorage bytes storage. */ contract BytesStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => bytes32) private bytesStorage; /////////////////// // Functions /////////////////// function setBytes(bytes32 _name, bytes32 _value) public onlyStorageAdministrator { return _setBytes(_name, _value); } function getBytes(bytes32 _name) public view returns (bytes32) { return _getBytes(_name); } function _setBytes(bytes32 _name, bytes32 _value) private { if(_name != "") { bytesStorage[_name] = _value; } } function _getBytes(bytes32 _name) private view returns (bytes32) { return bytesStorage[_name]; } function get2Bytes( bytes32 _name1, bytes32 _name2) public view returns (bytes32, bytes32) { return (_getBytes(_name1), _getBytes(_name2)); } function get3Bytes( bytes32 _name1, bytes32 _name2, bytes32 _name3) public view returns (bytes32, bytes32, bytes32) { return (_getBytes(_name1), _getBytes(_name2), _getBytes(_name3)); } function set2Bytes( bytes32 _name1, bytes32 _value1, bytes32 _name2, bytes32 _value2) public onlyStorageAdministrator { _setBytes(_name1, _value1); _setBytes(_name2, _value2); } function set3Bytes( bytes32 _name1, bytes32 _value1, bytes32 _name2, bytes32 _value2, bytes32 _name3, bytes32 _value3) public onlyStorageAdministrator { _setBytes(_name1, _value1); _setBytes(_name2, _value2); _setBytes(_name3, _value3); } } // File: contracts/controller/Storage/storagetypes/Addr2AddrArrStorage.sol /* Copyright 2018, CONDA 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 Addr2AddrArrStorage address to address array mapping storage. */ contract Addr2AddrArrStorage is StorageAdministratorRole { /////////////////// // Mappings /////////////////// mapping (bytes32 => mapping (address => address[])) private addr2AddrArrStorage; /////////////////// // Functions /////////////////// function addToAddr2AddrArr(bytes32 _name, address _address, address _value) public onlyStorageAdministrator { addr2AddrArrStorage[_name][_address].push(_value); } function getAddr2AddrArr(bytes32 _name, address _address) public view returns (address[] memory) { return addr2AddrArrStorage[_name][_address]; } } // File: contracts/controller/Storage/storagetypes/StorageHolder.sol /* Copyright 2018, CONDA 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 StorageHolder holds the fine-grained generic storage functions. */ contract StorageHolder is UintStorage, BytesStorage, AddrStorage, Addr2UintStorage, Addr2BoolStorage, Addr2AddrStorage, Addr2AddrArrStorage { /////////////////// // Functions /////////////////// function getMixedUBA(bytes32 _uintName, bytes32 _bytesName, bytes32 _addressName) public view returns (uint256, bytes32, address) { return (getUint(_uintName), getBytes(_bytesName), getAddr(_addressName)); } function getMixedMapA2UA2BA2A( bytes32 _a2uName, address _a2uAddress, bytes32 _a2bName, address _a2bAddress, bytes32 _a2aName, address _a2aAddress) public view returns (uint256, bool, address) { return (getAddr2Uint(_a2uName, _a2uAddress), getAddr2Bool(_a2bName, _a2bAddress), getAddr2Addr(_a2aName, _a2aAddress)); } } // File: contracts/controller/Storage/AT2CSStorage.sol /* Copyright 2018, CONDA 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 AT2CSStorage AssetToken to Crowdsale storage (that is upgradeable). */ contract AT2CSStorage is StorageAdministratorRole { /////////////////// // Constructor /////////////////// constructor(address controllerStorage) public { storageHolder = StorageHolder(controllerStorage); } /////////////////// // Variables /////////////////// StorageHolder storageHolder; /////////////////// // Functions /////////////////// function getAssetTokenOfCrowdsale(address _crowdsale) public view returns (address) { return storageHolder.getAddr2Addr("cs2at", _crowdsale); } function getRateFromCrowdsale(address _crowdsale) public view returns (uint256) { address assetToken = storageHolder.getAddr2Addr("cs2at", _crowdsale); return getRateFromAssetToken(assetToken); } function getRateFromAssetToken(address _assetToken) public view returns (uint256) { require(_assetToken != address(0), "rate assetTokenIs0"); return storageHolder.getAddr2Uint("rate", _assetToken); } function getAssetTokenOwnerWalletFromCrowdsale(address _crowdsale) public view returns (address) { address assetToken = storageHolder.getAddr2Addr("cs2at", _crowdsale); return getAssetTokenOwnerWalletFromAssetToken(assetToken); } function getAssetTokenOwnerWalletFromAssetToken(address _assetToken) public view returns (address) { return storageHolder.getAddr2Addr("at2wallet", _assetToken); } function getAssetTokensOf(address _wallet) public view returns (address[] memory) { return storageHolder.getAddr2AddrArr("wallet2AT", _wallet); } function isAssignedCrowdsale(address _crowdsale) public view returns (bool) { return storageHolder.getAddr2Bool("isCS", _crowdsale); } function isTrustedAssetTokenRegistered(address _assetToken) public view returns (bool) { return storageHolder.getAddr2Bool("trustedAT", _assetToken); } function isTrustedAssetTokenActive(address _assetToken) public view returns (bool) { return storageHolder.getAddr2Bool("ATactive", _assetToken); } function checkTrustedAssetToken(address _assetToken) public view returns (bool) { require(storageHolder.getAddr2Bool("ATactive", _assetToken), "not trusted AT"); return true; } function checkTrustedCrowdsaleInternal(address _crowdsale) public view returns (bool) { address _assetTokenAddress = storageHolder.getAddr2Addr("cs2at", _crowdsale); require(storageHolder.getAddr2Bool("isCS", _crowdsale), "not registered CS"); require(checkTrustedAssetToken(_assetTokenAddress), "not trusted AT"); return true; } function changeActiveTrustedAssetToken(address _assetToken, bool _active) public onlyStorageAdministrator { storageHolder.setAddr2Bool("ATactive", _assetToken, _active); } function addTrustedAssetTokenInternal(address _ownerWallet, address _assetToken, uint256 _rate) public onlyStorageAdministrator { require(!storageHolder.getAddr2Bool("trustedAT", _assetToken), "exists"); require(ERC20Detailed(_assetToken).decimals() == 0, "decimal not 0"); storageHolder.setAddr2Bool("trustedAT", _assetToken, true); storageHolder.setAddr2Bool("ATactive", _assetToken, true); storageHolder.addToAddr2AddrArr("wallet2AT", _ownerWallet, _assetToken); storageHolder.setAddr2Addr("at2wallet", _assetToken, _ownerWallet); storageHolder.setAddr2Uint("rate", _assetToken, _rate); } function assignCrowdsale(address _assetToken, address _crowdsale) public onlyStorageAdministrator { require(storageHolder.getAddr2Bool("trustedAT", _assetToken), "no AT"); require(!storageHolder.getAddr2Bool("isCS", _crowdsale), "is assigned"); require(IBasicAssetToken(_assetToken).isTokenAlive(), "not alive"); require(ERC20Detailed(_assetToken).decimals() == 0, "decimal not 0"); storageHolder.setAddr2Bool("isCS", _crowdsale, true); storageHolder.setAddr2Addr("cs2at", _crowdsale, _assetToken); } function setAssetTokenRate(address _assetToken, uint256 _rate) public onlyStorageAdministrator { storageHolder.setAddr2Uint("rate", _assetToken, _rate); } } // File: contracts/controller/0_library/ControllerL.sol /* Copyright 2018, CONDA 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 ControllerL library. */ library ControllerL { using SafeMath for uint256; /////////////////// // Structs /////////////////// struct Data { // global flag fees enabled bool feesEnabled; // global flag whitelist enabled bool whitelistEnabled; // address of the crwd token (for fees etc.) address crwdToken; // root platform wallet (receives fees according to it's FeeTable) address rootPlatformAddress; // address of ExchangeRateOracle (converts e.g. ETH to EUR and vice versa) address exchangeRateOracle; // the address of the whitelist contract address whitelist; // the generic storage contract AT2CSStorage store; // global flag to prevent new AssetToken or crowdsales to be accepted (e.g. after upgrade). bool blockNew; // mapping of platform addresses that are trusted mapping ( address => bool ) trustedPlatform; //note: not easily upgradeable // mapping of platform addresses that are trusted mapping ( address => bool ) onceTrustedPlatform; //note: not easily upgradeable // mapping of crowdsale to platform wallet mapping ( address => address ) crowdsaleToPlatform; //note: not easily upgradeable // mapping from platform address to FeeTable mapping ( address => address ) platformToFeeTable; //note: not easily upgradeable } /////////////////// // Functions /////////////////// /// @dev Contant point multiplier because no decimals. function pointMultiplier() private pure returns (uint256) { return 1e18; } /// @notice Address of generic storage (for upgradability). function getStorageAddress(Data storage _self) public view returns (address) { return address(_self.store); } /// @notice Assign generic storage (for upgradability). /// @param _storage storage address. function assignStore(Data storage _self, address _storage) public { _self.store = AT2CSStorage(_storage); } /// @notice Get FeeTable for platform. /// @param _platform platform to find FeeTable for. /// @return address of FeeTable of platform. function getFeeTableAddressForPlatform(Data storage _self, address _platform) public view returns (address) { return _self.platformToFeeTable[_platform]; } /// @notice Get FeeTable for platform. /// @param _platform platform to find FeeTable for. /// @return address of FeeTable of platform. function getFeeTableForPlatform(Data storage _self, address _platform) private view returns (FeeTable) { return FeeTable(_self.platformToFeeTable[_platform]); } /// @notice Set exchange rate oracle address. /// @param _oracleAddress the address of the ExchangeRateOracle. function setExchangeRateOracle(Data storage _self, address _oracleAddress) public { _self.exchangeRateOracle = _oracleAddress; emit ExchangeRateOracleSet(msg.sender, _oracleAddress); } /// @notice Check if a wallet is whitelisted or fail. Also considers auto extend (if enabled). /// @param _wallet the wallet to check. function checkWhitelistedWallet(Data storage _self, address _wallet) public returns (bool) { require(Whitelist(_self.whitelist).checkWhitelistedWallet(_wallet), "not whitelist"); return true; } /// @notice Check if a wallet is whitelisted. /// @param _wallet the wallet to check. /// @return true if whitelisted. function isWhitelistedWallet(Data storage _self, address _wallet) public view returns (bool) { return Whitelist(_self.whitelist).isWhitelistedWallet(_wallet); } /// @notice Convert eth amount into base currency (EUR), apply exchange rate via oracle, apply rate for AssetToken. /// @param _crowdsale the crowdsale address. /// @param _amountInWei the amount desired to be converted into tokens. function convertEthToEurApplyRateGetTokenAmountFromCrowdsale( Data storage _self, address _crowdsale, uint256 _amountInWei) public view returns (uint256 _effectiveTokensNoDecimals, uint256 _overpaidEthWhenZeroDecimals) { uint256 amountInEur = convertEthToEur(_self, _amountInWei); uint256 tokens = DSMathL.ds_wmul(amountInEur, _self.store.getRateFromCrowdsale(_crowdsale)); _effectiveTokensNoDecimals = tokens.div(pointMultiplier()); _overpaidEthWhenZeroDecimals = convertEurToEth(_self, DSMathL.ds_wdiv(tokens.sub(_effectiveTokensNoDecimals.mul(pointMultiplier())), _self.store.getRateFromCrowdsale(_crowdsale))); return (_effectiveTokensNoDecimals, _overpaidEthWhenZeroDecimals); } /// @notice Checks if a crowdsale is trusted or fail. /// @param _crowdsale the address of the crowdsale. /// @return true if trusted. function checkTrustedCrowdsale(Data storage _self, address _crowdsale) public view returns (bool) { require(checkTrustedPlatform(_self, _self.crowdsaleToPlatform[_crowdsale]), "not trusted PF0"); require(_self.store.checkTrustedCrowdsaleInternal(_crowdsale), "not trusted CS1"); return true; } /// @notice Checks if a AssetToken is trusted or fail. /// @param _assetToken the address of the AssetToken. /// @return true if trusted. function checkTrustedAssetToken(Data storage _self, address _assetToken) public view returns (bool) { //here just a minimal check for active (simple check on transfer). require(_self.store.checkTrustedAssetToken(_assetToken), "untrusted AT"); return true; } /// @notice Checks if a platform is certified or fail. /// @param _platformWallet wallet of platform. /// @return true if trusted. function checkTrustedPlatform(Data storage _self, address _platformWallet) public view returns (bool) { require(isTrustedPlatform(_self, _platformWallet), "not trusted PF3"); return true; } /// @notice Checks if a platform is certified. /// @param _platformWallet wallet of platform. /// @return true if certified. function isTrustedPlatform(Data storage _self, address _platformWallet) public view returns (bool) { return _self.trustedPlatform[_platformWallet]; } /// @notice Add trusted AssetToken. /// @param _ownerWallet requires CRWD for fees, receives ETH on successful campaign. /// @param _rate the rate of tokens per basecurrency (currently EUR). function addTrustedAssetToken(Data storage _self, address _ownerWallet, address _assetToken, uint256 _rate) public { require(!_self.blockNew, "blocked. newest version?"); _self.store.addTrustedAssetTokenInternal(_ownerWallet, _assetToken, _rate); emit AssetTokenAdded(msg.sender, _ownerWallet, _assetToken, _rate); } /// @notice assign a crowdsale to an AssetToken. /// @param _assetToken the AssetToken being sold. /// @param _crowdsale the crowdsale that takes ETH (if enabled) and triggers assignment of tokens. /// @param _platformWallet the wallet of the platform. Fees are paid to this address. function assignCrowdsale(Data storage _self, address _assetToken, address _crowdsale, address _platformWallet) public { require(!_self.blockNew, "blocked. newest version?"); checkTrustedPlatform(_self, _platformWallet); _self.store.assignCrowdsale(_assetToken, _crowdsale); _self.crowdsaleToPlatform[_crowdsale] = _platformWallet; emit CrowdsaleAssigned(msg.sender, _assetToken, _crowdsale, _platformWallet); } /// @notice Can change the state of an AssetToken (e.g. blacklist for legal reasons) /// @param _assetToken the AssetToken to change state. /// @param _active the state. True means active. /// @return True if successful. function changeActiveTrustedAssetToken(Data storage _self, address _assetToken, bool _active) public returns (bool) { _self.store.changeActiveTrustedAssetToken(_assetToken, _active); emit AssetTokenChangedActive(msg.sender, _assetToken, _active); } /// @notice Function to call on buy request. /// @param _to beneficiary of tokens. /// @param _amountInWei the invested ETH amount (unit WEI). function buyFromCrowdsale( Data storage _self, address _to, uint256 _amountInWei) public returns (uint256 _tokensCreated, uint256 _overpaidRefund) { (uint256 effectiveTokensNoDecimals, uint256 overpaidEth) = convertEthToEurApplyRateGetTokenAmountFromCrowdsale( _self, msg.sender, _amountInWei); checkValidTokenAssignmentFromCrowdsale(_self, _to); payFeeFromCrowdsale(_self, effectiveTokensNoDecimals); _tokensCreated = doTokenAssignment(_self, _to, effectiveTokensNoDecimals, msg.sender); return (_tokensCreated, overpaidEth); } /// @notice Assign tokens. /// @dev Pure assignment without e.g. rate calculation. /// @param _to beneficiary of tokens. /// @param _tokensToMint amount of tokens beneficiary receives. /// @return amount of tokens being created. function assignFromCrowdsale(Data storage _self, address _to, uint256 _tokensToMint) public returns (uint256 _tokensCreated) { checkValidTokenAssignmentFromCrowdsale(_self, _to); payFeeFromCrowdsale(_self, _tokensToMint); _tokensCreated = doTokenAssignment(_self, _to, _tokensToMint, msg.sender); return _tokensCreated; } /// @dev Token assignment logic. /// @param _to beneficiary of tokens. /// @param _tokensToMint amount of tokens beneficiary receives. /// @param _crowdsale being used. /// @return amount of tokens being created. function doTokenAssignment( Data storage _self, address _to, uint256 _tokensToMint, address _crowdsale) private returns (uint256 _tokensCreated) { address assetToken = _self.store.getAssetTokenOfCrowdsale(_crowdsale); require(assetToken != address(0), "assetTokenIs0"); ERC20Mintable(assetToken).mint(_to, _tokensToMint); return _tokensToMint; } /// @notice Pay fee on calls from crowdsale. /// @param _tokensToMint tokens being created. function payFeeFromCrowdsale(Data storage _self, uint256 _tokensToMint) private { if (_self.feesEnabled) { address ownerAssetTokenWallet = _self.store.getAssetTokenOwnerWalletFromCrowdsale(msg.sender); payFeeKnowingCrowdsale(_self, msg.sender, ownerAssetTokenWallet, _tokensToMint, "investorInvests"); } } /// @notice Check if token assignment is valid and e.g. crowdsale is trusted and investor KYC checked. /// @param _to beneficiary. function checkValidTokenAssignmentFromCrowdsale(Data storage _self, address _to) private { require(checkTrustedCrowdsale(_self, msg.sender), "untrusted source1"); if (_self.whitelistEnabled) { checkWhitelistedWallet(_self, _to); } } /// @notice Pay fee on controller call from Crowdsale. /// @param _crowdsale the calling Crowdsale contract. /// @param _ownerAssetToken the AssetToken of the owner. /// @param _tokensToMint the tokens being created. /// @param _feeName the name of the fee (key in mapping). function payFeeKnowingCrowdsale( Data storage _self, address _crowdsale, address _ownerAssetToken, uint256 _tokensToMint, //tokensToMint requires precalculations and is base for fees bytes32 _feeName) private { address platform = _self.crowdsaleToPlatform[_crowdsale]; uint256 feePromilleRootPlatform = getFeeKnowingCrowdsale( _self, _crowdsale, getFeeTableAddressForPlatform(_self, _self.rootPlatformAddress), _tokensToMint, false, _feeName); payWithCrwd(_self, _ownerAssetToken, _self.rootPlatformAddress, feePromilleRootPlatform); if(platform != _self.rootPlatformAddress) { address feeTable = getFeeTableAddressForPlatform(_self, platform); require(feeTable != address(0), "FeeTbl 0 addr"); uint256 feePromillePlatform = getFeeKnowingCrowdsale(_self, _crowdsale, feeTable, _tokensToMint, false, _feeName); payWithCrwd(_self, _ownerAssetToken, platform, feePromillePlatform); } } /// @notice Pay fee on controller call from AssetToken. /// @param _assetToken the calling AssetToken contract. /// @param _initiator the initiator passed through as parameter by AssetToken. /// @param _tokensToMint the tokens being handled. /// @param _feeName the name of the fee (key in mapping). function payFeeKnowingAssetToken( Data storage _self, address _assetToken, address _initiator, uint256 _tokensToMint, //tokensToMint requires precalculations and is base for fees bytes32 _feeName) public { uint256 feePromille = getFeeKnowingAssetToken( _self, _assetToken, _initiator, _tokensToMint, _feeName); payWithCrwd(_self, _initiator, _self.rootPlatformAddress, feePromille); } /// @dev this function in the end does the fee payment in CRWD. function payWithCrwd(Data storage _self, address _from, address _to, uint256 _value) private { if(_value > 0 && _from != _to) { ERC20Mintable(_self.crwdToken).transferFrom(_from, _to, _value); emit FeesPaid(_from, _to, _value); } } /// @notice Current conversion of ETH to EUR via oracle. /// @param _weiAmount the ETH amount (uint WEI). /// @return amount converted in euro. function convertEthToEur(Data storage _self, uint256 _weiAmount) public view returns (uint256) { require(_self.exchangeRateOracle != address(0), "no oracle"); return IExchangeRateOracle(_self.exchangeRateOracle).convertTT("ETH", "EUR", _weiAmount); } /// @notice Current conversion of EUR to ETH via oracle. /// @param _eurAmount the EUR amount /// @return amount converted in eth (formatted like WEI) function convertEurToEth(Data storage _self, uint256 _eurAmount) public view returns (uint256) { require(_self.exchangeRateOracle != address(0), "no oracle"); return IExchangeRateOracle(_self.exchangeRateOracle).convertTT("EUR", "ETH", _eurAmount); } /// @notice Get fee that needs to be paid for certain Crowdsale and FeeName. /// @param _crowdsale the Crowdsale being used. /// @param _feeTableAddr the address of the feetable. /// @param _amountInTokensOrEth the amount in tokens or pure ETH when conversion parameter true. /// @param _amountRequiresConversion when true amount parameter is converted from ETH into tokens. /// @param _feeName the name of the fee being paid. /// @return amount of fees that would/will be paid. function getFeeKnowingCrowdsale( Data storage _self, address _crowdsale, address _feeTableAddr, uint256 _amountInTokensOrEth, bool _amountRequiresConversion, bytes32 _feeName) public view returns (uint256) { uint256 tokens = _amountInTokensOrEth; if(_amountRequiresConversion) { (tokens, ) = convertEthToEurApplyRateGetTokenAmountFromCrowdsale(_self, _crowdsale, _amountInTokensOrEth); } FeeTable feeTable = FeeTable(_feeTableAddr); address assetTokenOfCrowdsale = _self.store.getAssetTokenOfCrowdsale(_crowdsale); return feeTable.getFeeFor(_feeName, assetTokenOfCrowdsale, tokens, _self.exchangeRateOracle); } /// @notice Get fee that needs to be paid for certain AssetToken and FeeName. /// @param _assetToken the AssetToken being used. /// @param _tokenAmount the amount in tokens. /// @param _feeName the name of the fee being paid. /// @return amount of fees that would/will be paid. function getFeeKnowingAssetToken( Data storage _self, address _assetToken, address /*_from*/, uint256 _tokenAmount, bytes32 _feeName) public view returns (uint256) { FeeTable feeTable = getFeeTableForPlatform(_self, _self.rootPlatformAddress); return feeTable.getFeeFor(_feeName, _assetToken, _tokenAmount, _self.exchangeRateOracle); } /// @notice Set CRWD token address (e.g. for fees). /// @param _crwdToken the CRWD token address. function setCrwdTokenAddress(Data storage _self, address _crwdToken) public { _self.crwdToken = _crwdToken; emit CrwdTokenAddressChanged(_crwdToken); } /// @notice set platform address to trusted. A platform can receive fees. /// @param _platformWallet the wallet that will receive fees. /// @param _trusted true means trusted and false means not (=default). function setTrustedPlatform(Data storage _self, address _platformWallet, bool _trusted) public { setTrustedPlatformInternal(_self, _platformWallet, _trusted, false); } /// @dev set trusted platform logic /// @param _platformWallet the wallet that will receive fees. /// @param _trusted true means trusted and false means not (=default). /// @param _isRootPlatform true means that the given address is the root platform (here mainly used to save info into event). function setTrustedPlatformInternal(Data storage _self, address _platformWallet, bool _trusted, bool _isRootPlatform) private { require(_self.rootPlatformAddress != address(0), "no rootPF"); _self.trustedPlatform[_platformWallet] = _trusted; if(_trusted && !_self.onceTrustedPlatform[msg.sender]) { _self.onceTrustedPlatform[_platformWallet] = true; FeeTable ft = new FeeTable(_self.rootPlatformAddress); _self.platformToFeeTable[_platformWallet] = address(ft); } emit PlatformTrustChanged(_platformWallet, _trusted, _isRootPlatform); } /// @notice Set root platform address. Root platform address can receive fees (independent of which Crowdsale/AssetToken). /// @param _rootPlatformWallet wallet of root platform. function setRootPlatform(Data storage _self, address _rootPlatformWallet) public { _self.rootPlatformAddress = _rootPlatformWallet; emit RootPlatformChanged(_rootPlatformWallet); setTrustedPlatformInternal(_self, _rootPlatformWallet, true, true); } /// @notice Set rate of AssetToken. /// @dev Rate is from BaseCurrency (currently EUR). E.g. rate 2 means 2 tokens per 1 EUR. /// @param _assetToken the regarding AssetToken the rate should be applied on. /// @param _rate the rate. function setAssetTokenRate(Data storage _self, address _assetToken, uint256 _rate) public { _self.store.setAssetTokenRate(_assetToken, _rate); emit AssetTokenRateChanged(_assetToken, _rate); } /// @notice If this contract gets a balance in some other ERC20 contract - or even iself - then we can rescue it. /// @param _foreignTokenAddress token where contract has balance. /// @param _to the beneficiary. function rescueToken(Data storage /*_self*/, address _foreignTokenAddress, address _to) public { ERC20Mintable(_foreignTokenAddress).transfer(_to, ERC20(_foreignTokenAddress).balanceOf(address(this))); } /////////////////// // Events /////////////////// event AssetTokenAdded(address indexed initiator, address indexed wallet, address indexed assetToken, uint256 rate); event AssetTokenChangedActive(address indexed initiator, address indexed assetToken, bool active); event PlatformTrustChanged(address indexed platformWallet, bool trusted, bool isRootPlatform); event CrwdTokenAddressChanged(address indexed crwdToken); event AssetTokenRateChanged(address indexed assetToken, uint256 rate); event RootPlatformChanged(address indexed _rootPlatformWalletAddress); event CrowdsaleAssigned(address initiator, address indexed assetToken, address indexed crowdsale, address platformWallet); event ExchangeRateOracleSet(address indexed initiator, address indexed oracleAddress); event FeesPaid(address indexed from, address indexed to, uint256 value); } // File: contracts/controller/0_library/LibraryHolder.sol /** @title LibraryHolder holds libraries used in inheritance bellow. */ contract LibraryHolder { using ControllerL for ControllerL.Data; /////////////////// // Variables /////////////////// ControllerL.Data internal controllerData; } // File: contracts/controller/1_permissions/PermissionHolder.sol /* Copyright 2018, CONDA 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 PermissionHolder role permissions used in inheritance bellow. */ contract PermissionHolder is AssetTokenAdministratorRole, At2CsConnectorRole, LibraryHolder { } // File: contracts/controller/2_provider/MainInfoProvider.sol /* Copyright 2018, CONDA 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 MainInfoProvider holding simple getters and setters and events without much logic. */ contract MainInfoProvider is PermissionHolder { /////////////////// // Events /////////////////// event AssetTokenAdded(address indexed initiator, address indexed wallet, address indexed assetToken, uint256 rate); event AssetTokenChangedActive(address indexed initiator, address indexed assetToken, bool active); event CrwdTokenAddressChanged(address indexed crwdToken); event ExchangeRateOracleSet(address indexed initiator, address indexed oracleAddress); event AssetTokenRateChanged(address indexed assetToken, uint256 rate); event RootPlatformChanged(address indexed _rootPlatformWalletAddress); event PlatformTrustChanged(address indexed platformWallet, bool trusted, bool isRootPlatform); event WhitelistSet(address indexed initiator, address indexed whitelistAddress); event CrowdsaleAssigned(address initiator, address indexed assetToken, address indexed crowdsale, address platformWallet); event FeesPaid(address indexed from, address indexed to, uint256 value); event TokenAssignment(address indexed to, uint256 tokensToMint, address indexed crowdsale, bytes8 tag); /////////////////// // Methods (simple getters/setters ONLY) /////////////////// /// @notice Set CRWD token address (e.g. for fees). /// @param _crwdToken the CRWD token address. function setCrwdTokenAddress(address _crwdToken) public onlyRootPlatformAdministrator { controllerData.setCrwdTokenAddress(_crwdToken); } /// @notice Set exchange rate oracle address. /// @param _oracleAddress the address of the ExchangeRateOracle. function setOracle(address _oracleAddress) public onlyRootPlatformAdministrator { controllerData.setExchangeRateOracle(_oracleAddress); } /// @notice Get FeeTable for platform. /// @param _platform platform to find FeeTable for. /// @return address of FeeTable of platform. function getFeeTableAddressForPlatform(address _platform) public view returns (address) { return controllerData.getFeeTableAddressForPlatform(_platform); } /// @notice Set rate of AssetToken. /// @dev Rate is from BaseCurrency (currently EUR). E.g. rate 2 means 2 tokens per 1 EUR. /// @param _assetToken the regarding AssetToken the rate should be applied on. /// @param _rate the rate. Unit is WAD (decimal number with 18 digits, so rate of x WAD is x*1e18). function setAssetTokenRate(address _assetToken, uint256 _rate) public onlyRootPlatformAdministrator { controllerData.setAssetTokenRate(_assetToken, _rate); } /// @notice Set root platform address. Root platform address can receive fees (independent of which Crowdsale/AssetToken). /// @param _rootPlatformWallet wallet of root platform. function setRootPlatform(address _rootPlatformWallet) public onlyRootPlatformAdministrator { controllerData.setRootPlatform(_rootPlatformWallet); } /// @notice Root platform wallet (receives fees according to it's FeeTable regardless of which Crowdsale/AssetToken) function getRootPlatform() public view returns (address) { return controllerData.rootPlatformAddress; } /// @notice Set platform address to trusted. A platform can receive fees. /// @param _platformWallet the wallet that will receive fees. /// @param _trusted true means trusted and false means not (=default). function setTrustedPlatform(address _platformWallet, bool _trusted) public onlyRootPlatformAdministrator { controllerData.setTrustedPlatform(_platformWallet, _trusted); } /// @notice Is trusted platform. /// @param _platformWallet platform wallet that recieves fees. /// @return true if trusted. function isTrustedPlatform(address _platformWallet) public view returns (bool) { return controllerData.trustedPlatform[_platformWallet]; } /// @notice Get platform of crowdsale. /// @param _crowdsale the crowdsale to get platfrom from. /// @return address of owning platform. function getPlatformOfCrowdsale(address _crowdsale) public view returns (address) { return controllerData.crowdsaleToPlatform[_crowdsale]; } /// @notice Set whitelist contrac address. /// @param _whitelistAddress the whitelist address. function setWhitelistContract(address _whitelistAddress) public onlyRootPlatformAdministrator { controllerData.whitelist = _whitelistAddress; emit WhitelistSet(msg.sender, _whitelistAddress); } /// @notice Get address of generic storage that survives an upgrade. /// @return address of storage. function getStorageAddress() public view returns (address) { return controllerData.getStorageAddress(); } /// @notice Block new connections between AssetToken and Crowdsale (e.g. on upgrade) /// @param _isBlockNewActive true if no new AssetTokens or Crowdsales can be added to controller. function setBlockNewState(bool _isBlockNewActive) public onlyRootPlatformAdministrator { controllerData.blockNew = _isBlockNewActive; } /// @notice Gets state of block new. /// @return true if no new AssetTokens or Crowdsales can be added to controller. function getBlockNewState() public view returns (bool) { return controllerData.blockNew; } } // File: contracts/controller/3_manage/ManageAssetToken.sol /* Copyright 2018, CONDA 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 ManageAssetToken holds logic functions managing AssetTokens. */ contract ManageAssetToken is MainInfoProvider { using SafeMath for uint256; /////////////////// // Functions /////////////////// /// @notice Add trusted AssetToken. /// @param _ownerWallet requires CRWD for fees, receives ETH on successful campaign. /// @param _rate the rate of tokens per basecurrency (currently EUR). function addTrustedAssetToken(address _ownerWallet, address _assetToken, uint256 _rate) public onlyAssetTokenAdministrator { controllerData.addTrustedAssetToken(_ownerWallet, _assetToken, _rate); } /// @notice Checks if a AssetToken is trusted. /// @param _assetToken the address of the AssetToken. function checkTrustedAssetToken(address _assetToken) public view returns (bool) { return controllerData.checkTrustedAssetToken(_assetToken); } /// @notice Can change the state of an AssetToken (e.g. blacklist for legal reasons) /// @param _assetToken the AssetToken to change state. /// @param _active the state. True means active. /// @return True if successful. function changeActiveTrustedAssetToken(address _assetToken, bool _active) public onlyRootPlatformAdministrator returns (bool) { return controllerData.changeActiveTrustedAssetToken(_assetToken, _active); } /// @notice Get fee that needs to be paid for certain AssetToken and FeeName. /// @param _assetToken the AssetToken being used. /// @param _tokenAmount the amount in tokens. /// @param _feeName the name of the fee being paid. /// @return amount of fees that would/will be paid. function getFeeKnowingAssetToken( address _assetToken, address _from, uint256 _tokenAmount, bytes32 _feeName) public view returns (uint256) { return controllerData.getFeeKnowingAssetToken(_assetToken, _from, _tokenAmount, _feeName); } /// @notice Convert eth amount into base currency (EUR), apply exchange rate via oracle, apply rate for AssetToken. /// @param _crowdsale the crowdsale address. /// @param _amountInWei the amount desired to be converted into tokens. function convertEthToTokenAmount(address _crowdsale, uint256 _amountInWei) public view returns (uint256 _tokens) { (uint256 tokens, ) = controllerData.convertEthToEurApplyRateGetTokenAmountFromCrowdsale(_crowdsale, _amountInWei); return tokens; } } // File: contracts/controller/3_manage/ManageFee.sol /* Copyright 2018, CONDA 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 ManageAssetToken holds logic functions managing Fees. */ contract ManageFee is MainInfoProvider { /////////////////// // Functions /////////////////// /// @notice Pay fee on controller call from AssetToken. /// @param _assetToken the calling AssetToken contract. /// @param _from the initiator passed through as parameter by AssetToken. /// @param _amount the tokens being handled. /// @param _feeName the name of the fee (key in mapping). function payFeeKnowingAssetToken(address _assetToken, address _from, uint256 _amount, bytes32 _feeName) internal { controllerData.payFeeKnowingAssetToken(_assetToken, _from, _amount, _feeName); } } // File: contracts/controller/3_manage/ManageCrowdsale.sol /* Copyright 2018, CONDA 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 ManageAssetToken holds logic functions managing Crowdsales. */ contract ManageCrowdsale is MainInfoProvider { /////////////////// // Functions /////////////////// /// @notice assign a crowdsale to an AssetToken. /// @param _assetToken the AssetToken being sold. /// @param _crowdsale the crowdsale that takes ETH (if enabled) and triggers assignment of tokens. /// @param _platformWallet the wallet of the platform. Fees are paid to this address. function assignCrowdsale(address _assetToken, address _crowdsale, address _platformWallet) public onlyAt2CsConnector { controllerData.assignCrowdsale(_assetToken, _crowdsale, _platformWallet); } /// @notice Checks if a crowdsale is trusted. /// @param _crowdsale the address of the crowdsale. function checkTrustedCrowdsale(address _crowdsale) public view returns (bool) { return controllerData.checkTrustedCrowdsale(_crowdsale); } /// @notice Get fee that needs to be paid for certain Crowdsale and FeeName. /// @param _crowdsale the Crowdsale being used. /// @param _feeTableAddr the address of the feetable. /// @param _amountInTokensOrEth the amount in tokens or pure ETH when conversion parameter true. /// @param _amountRequiresConversion when true amount parameter is converted from ETH into tokens. /// @param _feeName the name of the fee being paid. /// @return amount of fees that would/will be paid. function getFeeKnowingCrowdsale( address _crowdsale, address _feeTableAddr, uint256 _amountInTokensOrEth, bool _amountRequiresConversion, bytes32 _feeName) public view returns (uint256) { return controllerData.getFeeKnowingCrowdsale(_crowdsale, _feeTableAddr, _amountInTokensOrEth, _amountRequiresConversion, _feeName); } } // File: contracts/controller/3_manage/ManagePlatform.sol /* Copyright 2018, CONDA 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 ManageAssetToken holds logic functions managing platforms. */ contract ManagePlatform is MainInfoProvider { /////////////////// // Functions /////////////////// /// @notice Checks if a crowdsale is trusted or fail. /// @param _platformWallet the platform wallet. /// @return true if trusted. function checkTrustedPlatform(address _platformWallet) public view returns (bool) { return controllerData.checkTrustedPlatform(_platformWallet); } /// @notice Is a platform wallet trusted. /// @return true if trusted. function isTrustedPlatform(address _platformWallet) public view returns (bool) { return controllerData.trustedPlatform[_platformWallet]; } } // File: contracts/controller/3_manage/ManageWhitelist.sol /* Copyright 2018, CONDA 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 ManageAssetToken holds logic functions managing Whitelist and KYC. */ contract ManageWhitelist is MainInfoProvider { /////////////////// // Functions /////////////////// /// @notice Check if a wallet is whitelisted or fail. Also considers auto extend (if enabled). /// @param _wallet the wallet to check. function checkWhitelistedWallet(address _wallet) public returns (bool) { controllerData.checkWhitelistedWallet(_wallet); } /// @notice Check if a wallet is whitelisted. /// @param _wallet the wallet to check. /// @return true if whitelisted. function isWhitelistedWallet(address _wallet) public view returns (bool) { controllerData.isWhitelistedWallet(_wallet); } } // File: contracts/controller/3_manage/ManagerHolder.sol /* Copyright 2018, CONDA 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 ManagerHolder combining all managers into single contract to be inherited. */ contract ManagerHolder is ManageAssetToken, ManageFee, ManageCrowdsale, ManagePlatform, ManageWhitelist { } // File: contracts/controller/interface/ICRWDController.sol interface ICRWDController { function transferParticipantsVerification(address _underlyingCurrency, address _from, address _to, uint256 _tokenAmount) external returns (bool); //from AssetToken function buyFromCrowdsale(address _to, uint256 _amountInWei) external returns (uint256 _tokensCreated, uint256 _overpaidRefund); //from Crowdsale function assignFromCrowdsale(address _to, uint256 _tokenAmount, bytes8 _tag) external returns (uint256 _tokensCreated); //from Crowdsale function calcTokensForEth(uint256 _amountInWei) external view returns (uint256 _tokensWouldBeCreated); //from Crowdsale } // File: contracts/controller/CRWDController.sol /** @title CRWDController main contract and n-th child of multi-level inheritance. */ contract CRWDController is ManagerHolder, ICRWDController { /////////////////// // Events /////////////////// event GlobalConfigurationChanged(bool feesEnabled, bool whitelistEnabled); /////////////////// // Constructor /////////////////// constructor(bool _feesEnabled, bool _whitelistEnabled, address _rootPlatformAddress, address _storage) public { controllerData.assignStore(_storage); setRootPlatform(_rootPlatformAddress); configure(_feesEnabled, _whitelistEnabled); } /////////////////// // Functions /////////////////// /// @notice configure global flags. /// @param _feesEnabled global flag fees enabled. /// @param _whitelistEnabled global flag whitelist check enabled. function configure(bool _feesEnabled, bool _whitelistEnabled) public onlyRootPlatformAdministrator { controllerData.feesEnabled = _feesEnabled; controllerData.whitelistEnabled = _whitelistEnabled; emit GlobalConfigurationChanged(_feesEnabled, _whitelistEnabled); } /// @notice Called from AssetToken on transfer for whitelist check. /// @param _from the original initiator passed through. /// @param _to the receiver of the tokens. /// @param _tokenAmount the amount of tokens to be transfered. function transferParticipantsVerification(address /*_underlyingCurrency*/, address _from, address _to, uint256 _tokenAmount) public returns (bool) { if (controllerData.whitelistEnabled) { checkWhitelistedWallet(_to); //receiver must be whitelisted } // Caller must be a trusted AssetToken. Otherwise anyone could make investor pay fees for no reason. require(checkTrustedAssetToken(msg.sender), "untrusted"); if (controllerData.feesEnabled) { payFeeKnowingAssetToken(msg.sender, _from, _tokenAmount, "clearTransferFunds"); } return true; } /// @notice Called from Crowdsale on buy token action (paid via Ether). /// @param _to the beneficiary of the tokens (passed through from Crowdsale). /// @param _amountInWei the ETH amount (unit WEI). function buyFromCrowdsale(address _to, uint256 _amountInWei) public returns (uint256 _tokensCreated, uint256 _overpaidRefund) { return controllerData.buyFromCrowdsale(_to, _amountInWei); } /// @notice Calculate how many tokens will be received per Ether. /// @param _amountInWei the ETH amount (unit WEI). /// @return tokens that would be created. function calcTokensForEth(uint256 _amountInWei) external view returns (uint256 _tokensWouldBeCreated) { require(checkTrustedCrowdsale(msg.sender), "untrusted source2"); return convertEthToTokenAmount(msg.sender, _amountInWei); } /// @notice Called from Crowdsale via (semi-)automatic process on off-chain payment. /// @param _to the beneficiary of the tokens. /// @param _tokenAmount the amount of tokens to be minted/assigned. /// @return tokens created. function assignFromCrowdsale(address _to, uint256 _tokenAmount, bytes8 _tag) external returns (uint256 _tokensCreated) { _tokensCreated = controllerData.assignFromCrowdsale(_to, _tokenAmount); emit TokenAssignment(_to, _tokenAmount, msg.sender, _tag); return _tokensCreated; } //////////////// // Rescue Tokens //////////////// /// @dev Can rescue tokens accidentally assigned to this contract /// @param _foreignTokenAddress The address from which the balance will be retrieved /// @param _to beneficiary function rescueToken(address _foreignTokenAddress, address _to) public onlyRootPlatformAdministrator { controllerData.rescueToken(_foreignTokenAddress, _to); } }
@notice Called from Crowdsale on buy token action (paid via Ether). @param _to the beneficiary of the tokens (passed through from Crowdsale). @param _amountInWei the ETH amount (unit WEI).
function buyFromCrowdsale(address _to, uint256 _amountInWei) public returns (uint256 _tokensCreated, uint256 _overpaidRefund) { return controllerData.buyFromCrowdsale(_to, _amountInWei); }
2,537,545
[ 1, 8185, 628, 385, 492, 2377, 5349, 603, 30143, 1147, 1301, 261, 29434, 3970, 512, 1136, 2934, 225, 389, 869, 326, 27641, 74, 14463, 814, 434, 326, 2430, 261, 23603, 3059, 628, 385, 492, 2377, 5349, 2934, 225, 389, 8949, 382, 3218, 77, 326, 512, 2455, 3844, 261, 4873, 13880, 45, 2934, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 30143, 1265, 39, 492, 2377, 5349, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 382, 3218, 77, 13, 1071, 1135, 261, 11890, 5034, 389, 7860, 6119, 16, 2254, 5034, 389, 1643, 29434, 21537, 13, 288, 203, 3639, 327, 2596, 751, 18, 70, 9835, 1265, 39, 492, 2377, 5349, 24899, 869, 16, 389, 8949, 382, 3218, 77, 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 ]
./full_match/100/0xF965f52046D7095d5080bD31459601F4Eb24f72D/sources/src/Facets/OFTWrapperFacet.sol
@notice Executes one or several swaps at src chain and bridges the resulting OFT V2 tokens via OFT Wrapper @param _bridgeData The core information needed for bridging @param _oftWrapperData Specific information required for bridging OFTs
function swapAndStartBridgeTokensViaOFTWrapperV2( ILiFi.BridgeData memory _bridgeData, LibSwap.SwapData[] calldata _swapData, OFTWrapperData calldata _oftWrapperData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) validateBridgeData(_bridgeData) containsSourceSwaps(_bridgeData) doesNotContainDestinationCalls(_bridgeData) noNativeAsset(_bridgeData) { _bridgeData.minAmount = _depositAndSwap( _bridgeData.transactionId, _bridgeData.minAmount, _swapData, payable(msg.sender), _oftWrapperData.lzFee ); _startBridgeOFTV2(_bridgeData, _oftWrapperData); }
14,273,316
[ 1, 9763, 1245, 578, 11392, 1352, 6679, 622, 1705, 2687, 471, 324, 1691, 2852, 326, 8156, 531, 4464, 776, 22, 2430, 3970, 531, 4464, 18735, 225, 389, 18337, 751, 1021, 2922, 1779, 3577, 364, 324, 1691, 1998, 225, 389, 4401, 3611, 751, 23043, 1779, 1931, 364, 324, 1691, 1998, 531, 4464, 87, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7720, 1876, 1685, 13691, 5157, 21246, 3932, 56, 3611, 58, 22, 12, 203, 3639, 467, 28762, 42, 77, 18, 13691, 751, 3778, 389, 18337, 751, 16, 203, 3639, 10560, 12521, 18, 12521, 751, 8526, 745, 892, 389, 22270, 751, 16, 203, 3639, 531, 4464, 3611, 751, 745, 892, 389, 4401, 3611, 751, 203, 565, 262, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 16255, 424, 614, 9220, 12, 10239, 429, 12, 3576, 18, 15330, 3719, 203, 3639, 1954, 13691, 751, 24899, 18337, 751, 13, 203, 3639, 1914, 1830, 6050, 6679, 24899, 18337, 751, 13, 203, 3639, 1552, 1248, 22928, 5683, 10125, 24899, 18337, 751, 13, 203, 3639, 1158, 9220, 6672, 24899, 18337, 751, 13, 203, 565, 288, 203, 3639, 389, 18337, 751, 18, 1154, 6275, 273, 389, 323, 1724, 1876, 12521, 12, 203, 5411, 389, 18337, 751, 18, 7958, 548, 16, 203, 5411, 389, 18337, 751, 18, 1154, 6275, 16, 203, 5411, 389, 22270, 751, 16, 203, 5411, 8843, 429, 12, 3576, 18, 15330, 3631, 203, 5411, 389, 4401, 3611, 751, 18, 80, 94, 14667, 203, 3639, 11272, 203, 203, 3639, 389, 1937, 13691, 3932, 15579, 22, 24899, 18337, 751, 16, 389, 4401, 3611, 751, 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 ]
pragma solidity ^0.4.2; contract Wolker { mapping (address => uint256) balances; mapping (address => uint256) allocations; mapping (address => mapping (address => uint256)) allowed; mapping (address => mapping (address => bool)) authorized; //trustee /// @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) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value, balances[msg.sender], balances[_to]); return true; } else { throw; } } /// @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) { var _allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value, balances[_from], balances[_to]); return true; } else { throw; } } /// @return total amount of tokens function totalSupply() external constant returns (uint256) { return generalTokens + reservedTokens; } /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of Wolk token to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @param _trustee Grant trustee permission to settle media spend /// @return Whether the authorization was successful or not function authorize(address _trustee) returns (bool success) { authorized[msg.sender][_trustee] = true; Authorization(msg.sender, _trustee); return true; } /// @param _trustee_to_remove Revoke trustee's permission on settle media spend /// @return Whether the deauthorization was successful or not function deauthorize(address _trustee_to_remove) returns (bool success) { authorized[msg.sender][_trustee_to_remove] = false; Deauthorization(msg.sender, _trustee_to_remove); return true; } // @param _owner // @param _trustee // @return authorization_status for platform settlement function check_authorization(address _owner, address _trustee) constant returns (bool authorization_status) { return authorized[_owner][_trustee]; } /// @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) { return allowed[_owner][_spender]; } //**** ERC20 TOK Events: event Transfer(address indexed _from, address indexed _to, uint256 _value, uint from_final_tok, uint to_final_tok); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Authorization(address indexed _owner, address indexed _trustee); event Deauthorization(address indexed _owner, address indexed _trustee_to_remove); event NewOwner(address _newOwner); event MintEvent(uint reward_tok, address recipient); event LogRefund(address indexed _to, uint256 _value); event CreateWolk(address indexed _to, uint256 _value); event Vested(address indexed _to, uint256 _value); modifier onlyOwner { assert(msg.sender == owner); _; } modifier isOperational() { assert(isFinalized); _; } //**** ERC20 TOK fields: string public constant name = 'Wolk'; string public constant symbol = "WOLK"; string public constant version = "0.2"; uint256 public constant decimals = 18; uint256 public constant wolkFund = 10 * 10**1 * 10**decimals; // 100 Wolk in operation Fund uint256 public constant tokenCreationMin = 20 * 10**1 * 10**decimals; // 200 Wolk Min uint256 public constant tokenCreationMax = 100 * 10**1 * 10**decimals; // 1000 Wolk Max uint256 public constant tokenExchangeRate = 10000; // 10000 Wolk per 1 ETH uint256 public generalTokens = wolkFund; // tokens in circulation uint256 public reservedTokens; //address public owner = msg.sender; address public owner = 0xC28dA4d42866758d0Fc49a5A3948A1f43de491e9; // michael - main address public multisig_owner = 0x6968a9b90245cB9bD2506B9460e3D13ED4B2FD1e; // new multi-sig bool public isFinalized = false; // after token sale success, this is true uint public constant dust = 1000000 wei; bool public fairsale_protection = true; // Actual crowdsale uint256 public start_block; // Starting block uint256 public end_block; // Ending block uint256 public unlockedAt; // Unlocking block uint256 public end_ts; // Unix End time // minting support //uint public max_creation_rate_per_second; // Maximum token creation rate per second //address public minter_address; // Has permission to mint // migration support //address migrationMaster; //**** Constructor: function Wolk() { // Actual crowdsale start_block = 3831300; end_block = 3831900; // wolkFund is 100 balances[msg.sender] = wolkFund; // Wolk Inc has 25MM Wolk, 5MM of which is allocated for Wolk Inc Founding staff, who vest at "unlockedAt" time reservedTokens = 25 * 10**decimals; allocations[0x564a3f7d98Eb5B1791132F8875fef582d528d5Cf] = 20; // unassigned allocations[0x7f512CCFEF05F651A70Fa322Ce27F4ad79b74ffe] = 1; // Sourabh allocations[0x9D203A36cd61b21B7C8c7Da1d8eeB13f04bb24D9] = 2; // Michael - Test allocations[0x5fcf700654B8062B709a41527FAfCda367daE7b1] = 1; // Michael - Main allocations[0xC28dA4d42866758d0Fc49a5A3948A1f43de491e9] = 1; // Urmi CreateWolk(msg.sender, wolkFund); } // ****** VESTING SUPPORT /// @notice Allow developer to unlock allocated tokens by transferring them to developer's address on vesting schedule of "vested 100% on 1 year) function unlock() external { if (now < unlockedAt) throw; uint256 vested = allocations[msg.sender] * 10**decimals; if (vested < 0 ) throw; // Will fail if allocation (and therefore toTransfer) is 0. allocations[msg.sender] = 0; reservedTokens = safeSub(reservedTokens, vested); balances[msg.sender] = safeAdd(balances[msg.sender], vested); Vested(msg.sender, vested); } // ******* CROWDSALE SUPPORT // Accepts ETH and creates WOLK function createTokens() payable external is_not_dust { if (isFinalized) throw; if (block.number < start_block) throw; if (block.number > end_block) throw; if (msg.value == 0) throw; if (tx.gasprice > 0.021 szabo && fairsale_protection) throw; if (msg.value > 0.04 ether && fairsale_protection) throw; uint256 tokens = safeMul(msg.value, tokenExchangeRate); // check that we're not over totals uint256 checkedSupply = safeAdd(generalTokens, tokens); if ( checkedSupply > tokenCreationMax) { throw; // they need to get their money back if something goes wrong } else { generalTokens = checkedSupply; balances[msg.sender] = safeAdd(balances[msg.sender], tokens); // safeAdd not needed; bad semantics to use here CreateWolk(msg.sender, tokens); // logs token creation } } // The value of the message must be sufficiently large to not be considered dust. modifier is_not_dust { if (msg.value < dust) throw; _; } // Disabling fairsale protection function fairsale_protectionOFF() external { if ( block.number - start_block < 200) throw; // fairsale window is strictly enforced if ( msg.sender != owner ) throw; fairsale_protection = false; } // Finalizing the crowdsale function finalize() external { if ( isFinalized ) throw; if ( msg.sender != owner ) throw; // locks finalize to ETH owner if ( generalTokens < tokenCreationMin ) throw; // have to sell tokenCreationMin to finalize if ( block.number < end_block ) throw; isFinalized = true; end_ts = now; unlockedAt = end_ts + 2 minutes; if ( ! multisig_owner.send(this.balance) ) throw; } function refund() external { if ( isFinalized ) throw; if ( block.number < end_block ) throw; if ( generalTokens >= tokenCreationMin ) throw; if ( msg.sender == owner ) throw; uint256 Val = balances[msg.sender]; balances[msg.sender] = 0; generalTokens = safeSub(generalTokens, Val); uint256 ethVal = safeDiv(Val, tokenExchangeRate); LogRefund(msg.sender, ethVal); if ( ! msg.sender.send(ethVal) ) throw; } // ****** Platform Settlement function settleFrom(address _from, address _to, uint256 _value) isOperational() external returns (bool success) { if ( msg.sender != owner ) throw; var _allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value && (allowed[_from][msg.sender] >= _value || authorized[_from][msg.sender] == true ) && _value > 0) { balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); if ( allowed[_from][msg.sender] < 0 ){ allowed[_from][msg.sender] = 0; } Transfer(_from, _to, _value, balances[_from], balances[_to]); return true; } else { throw; } } // ****** MINTING SUPPORT // Mint new tokens modifier only_minter { assert(msg.sender == minter_address); _; } address public minter_address = owner; // Has permission to mint function mintTokens(uint reward_tok, address recipient) external payable only_minter { balances[recipient] = safeAdd(balances[recipient], reward_tok); generalTokens = safeAdd(generalTokens, reward_tok); MintEvent(reward_tok, recipient); } function changeMintingAddress(address newAddress) onlyOwner returns (bool success) { minter_address = newAddress; return true; } //**** SafeMath: function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function assert(bool assertion) internal { if (!assertion) throw; } }
after token sale success, this is true
bool public isFinalized = false;
5,363,250
[ 1, 5205, 1147, 272, 5349, 2216, 16, 333, 353, 638, 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, 225, 1426, 1071, 29200, 1235, 273, 629, 31, 6647, 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/137/0xc6183a902FD287CC47b525a75C8d3381C6eae42f/sources/IGainBase.sol
burn no more than `max_lp` of liquidity provider share, withdraw `_a` of a and `_b` of b k = poolA * poolB _lp = ( 1 - sqrt(_k)/sqrt(k) ) * LP
function withdrawLP(uint256 _a, uint256 _b, uint256 max_lp) external returns (uint256 _lp) { require(canBuy, "cannot buy"); uint256 k = sqrt(poolA * poolB); uint256 _k = sqrt((poolA - _a) * (poolB - _b)); _lp = (1e18 - _k * 1e18 / k) * _totalSupply / 1e18; require(_lp <= max_lp, "SLIPPAGE_DETECTED"); poolA = poolA - _a; poolB = poolB - _b; a.mint(_msgSender(), _a); b.mint(_msgSender(), _b); _burn(_msgSender(), _lp); emit RemoveLP(_msgSender(), _a, _b, _lp); } |__________________________________*/
4,744,588
[ 1, 70, 321, 1158, 1898, 2353, 1375, 1896, 67, 9953, 68, 434, 4501, 372, 24237, 2893, 7433, 16, 598, 9446, 1375, 67, 69, 68, 434, 279, 471, 1375, 67, 70, 68, 434, 324, 417, 273, 2845, 37, 225, 2845, 38, 389, 9953, 273, 261, 404, 300, 5700, 24899, 79, 13176, 24492, 12, 79, 13, 262, 225, 511, 52, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 598, 9446, 14461, 12, 11890, 5034, 389, 69, 16, 2254, 5034, 389, 70, 16, 2254, 5034, 943, 67, 9953, 13, 3903, 1135, 261, 11890, 5034, 389, 9953, 13, 288, 203, 3639, 2583, 12, 4169, 38, 9835, 16, 315, 12892, 30143, 8863, 203, 3639, 2254, 5034, 417, 273, 5700, 12, 6011, 37, 380, 2845, 38, 1769, 203, 3639, 2254, 5034, 389, 79, 273, 5700, 12443, 6011, 37, 300, 389, 69, 13, 380, 261, 6011, 38, 300, 389, 70, 10019, 203, 3639, 389, 9953, 273, 261, 21, 73, 2643, 300, 389, 79, 380, 404, 73, 2643, 342, 417, 13, 380, 389, 4963, 3088, 1283, 342, 404, 73, 2643, 31, 203, 203, 3639, 2583, 24899, 9953, 1648, 943, 67, 9953, 16, 315, 55, 2053, 6584, 2833, 67, 1639, 26729, 8863, 203, 3639, 2845, 37, 273, 2845, 37, 300, 389, 69, 31, 203, 3639, 2845, 38, 273, 2845, 38, 300, 389, 70, 31, 203, 3639, 279, 18, 81, 474, 24899, 3576, 12021, 9334, 389, 69, 1769, 203, 3639, 324, 18, 81, 474, 24899, 3576, 12021, 9334, 389, 70, 1769, 203, 3639, 389, 70, 321, 24899, 3576, 12021, 9334, 389, 9953, 1769, 203, 3639, 3626, 3581, 14461, 24899, 3576, 12021, 9334, 389, 69, 16, 389, 70, 16, 389, 9953, 1769, 203, 565, 289, 203, 203, 203, 565, 571, 21157, 21157, 972, 5549, 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 ]
./partial_match/3/0xE05FDD0806CA346Ad792Bf0b4bb8d4b1b8acA7Fb/sources/Nexon.sol
function to Set the price of each token for ETH purchase
function setPriceToken(uint256 tokenPriceETH) external onlyOwner returns (bool){ require(tokenPriceETH >0,"Invalid Amount"); _tokenPriceETH = tokenPriceETH; return(true); }
5,115,187
[ 1, 915, 358, 1000, 326, 6205, 434, 1517, 1147, 364, 512, 2455, 23701, 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, 225, 445, 444, 5147, 1345, 12, 11890, 5034, 1147, 5147, 1584, 44, 13, 3903, 1338, 5541, 1135, 261, 6430, 15329, 203, 565, 2583, 12, 2316, 5147, 1584, 44, 405, 20, 10837, 1941, 16811, 8863, 203, 565, 389, 2316, 5147, 1584, 44, 273, 1147, 5147, 1584, 44, 31, 203, 565, 327, 12, 3767, 1769, 203, 225, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** #LUCK-INU #LUCK-INU features: 3% fee auto added to the liquidity pool 5% fee auto distributed to all holders 2% (5% when timer is under 10 minutes) fee auto added to the pot. Last 7 buyers before the timer runs out split 40% of the pot proportional to their buys. Absolute last buyer gets 30% of the pot. 30% carries over to next round. 50% Supply is burned at start. */ // SPDX-License-Identifier: BSD pragma solidity ^0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "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, "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, "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, "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, "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; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } } /** * @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); } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { 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); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract LUCKINU is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "LUCK-INU"; string private _symbol = "LUCK-INU"; uint8 private _decimals = 9; uint256 public _taxFee = 5; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 3; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _potFee = 2; uint256 private _previousPotFee = _potFee; uint256 public _potFeeExtra = 5; uint256 private _previousPotFeeExtra = _potFeeExtra; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap; struct GameSettings { uint256 maxTxAmount; // maximum number of tokens in one transfer uint256 tokenSwapThreshold; // number of tokens needed in contract to swap and sell uint256 minimumBuyForPotEligibility; //minimum buy to be eligible to win share of the pot uint256 tokensToAddOneSecond; //number of tokens that will add one second to the timer uint256 maxTimeLeft; //maximum number of seconds the timer can be uint256 potFeeExtraTimeLeftThreshold; //if timer is under this value, the potFeeExtra is used uint256 eliglblePlayers; //number of players eligible for winning share of the pot uint256 potPayoutPercent; // what percent of the pot is paid out, vs. carried over to next round uint256 lastBuyerPayoutPercent; //what percent of the paid-out-pot is paid to absolute last buyer } GameSettings public gameSettings; bool public gameIsActive = false; uint256 private roundNumber; uint256 private timeLeftAtLastBuy; uint256 private lastBuyBlock; uint256 private liquidityTokens; uint256 private potTokens; address private liquidityAddress; address private gameSettingsUpdaterAddress; address private presaleContractAddress; mapping (uint256 => Buyer[]) buyersByRound; modifier onlyGameSettingsUpdater() { require(_msgSender() == gameSettingsUpdaterAddress, "caller != game settings updater"); _; } event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event GameSettingsUpdated( uint256 maxTxAmount, uint256 tokenSwapThreshold, uint256 minimumBuyForPotEligibility, uint256 tokensToAddOneSecond, uint256 maxTimeLeft, uint256 potFeeExtraTimeLeftThreshold, uint256 eliglblePlayers, uint256 potPayoutPercent, uint256 lastBuyerPayoutPercent ); event GameSettingsUpdaterUpdated( address oldGameSettingsUpdater, address newGameSettingsUpdater ); event RoundStarted( uint256 number, uint256 potValue ); event Buy( bool indexed isEligible, address indexed buyer, uint256 amount, uint256 timeLeftBefore, uint256 timeLeftAfter, uint256 blockTime, uint256 blockNumber ); event RoundPayout( uint256 indexed roundNumber, address indexed buyer, uint256 amount, bool success ); event RoundEnded( uint256 number, address[] winners, uint256[] winnerAmountsRound ); enum TransferType { Normal, Buy, Sell, RemoveLiquidity } struct Buyer { address buyer; uint256 amount; uint256 timeLeftBefore; uint256 timeLeftAfter; uint256 blockTime; uint256 blockNumber; } constructor () public { gameSettings = GameSettings( 1000000 * 10**9, //maxTxAmount is 1 million tokens 200000 * 10**9, //tokenSwapThreshold is 200000 tokens 10000 * 10**9, //minimumBuyForPotEligibility is 10000 tokens 1000 * 10**9, //tokensToAddOneSecond is 1000 tokens 21600, //maxTimeLeft is 6 hours 600, //potFeeExtraTimeLeftThreshold is 10 minutes 7, //eliglblePlayers is 7 70, //potPayoutPercent is 70% 43 //lastBuyerPayoutPerent is 43% of the 70%, which is ~30% overall ); liquidityAddress = _msgSender(); gameSettingsUpdaterAddress = _msgSender(); _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[_msgSender()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } // for any non-zero value it updates the game settings to that value function updateGameSettings( uint256 maxTxAmount, uint256 tokenSwapThreshold, uint256 minimumBuyForPotEligibility, uint256 tokensToAddOneSecond, uint256 maxTimeLeft, uint256 potFeeExtraTimeLeftThreshold, uint256 eliglblePlayers, uint256 potPayoutPercent, uint256 lastBuyerPayoutPercent ) public onlyGameSettingsUpdater { if(maxTxAmount > 0) { require(maxTxAmount >= 1000000 * 10**9 && maxTxAmount <= 10000000 * 10**9); gameSettings.maxTxAmount = maxTxAmount; } if(tokenSwapThreshold > 0) { require(tokenSwapThreshold >= 100000 * 10**9 && tokenSwapThreshold <= 1000000 * 10**9); gameSettings.tokenSwapThreshold = tokenSwapThreshold; } if(minimumBuyForPotEligibility > 0) { require(minimumBuyForPotEligibility >= 1000 * 10**9 && minimumBuyForPotEligibility <= 100000 * 10**9); gameSettings.minimumBuyForPotEligibility = minimumBuyForPotEligibility; } if(tokensToAddOneSecond > 0) { require(tokensToAddOneSecond >= 100 * 10**9 && tokensToAddOneSecond <= 10000 * 10**9); gameSettings.tokensToAddOneSecond = tokensToAddOneSecond; } if(maxTimeLeft > 0) { require(maxTimeLeft >= 7200 && maxTimeLeft <= 86400); gameSettings.maxTimeLeft = maxTimeLeft; } if(potFeeExtraTimeLeftThreshold > 0) { require(potFeeExtraTimeLeftThreshold >= 60 && potFeeExtraTimeLeftThreshold <= 3600); gameSettings.potFeeExtraTimeLeftThreshold = potFeeExtraTimeLeftThreshold; } if(eliglblePlayers > 0) { require(eliglblePlayers >= 3 && eliglblePlayers <= 15); gameSettings.eliglblePlayers = eliglblePlayers; } if(potPayoutPercent > 0) { require(potPayoutPercent >= 30 && potPayoutPercent <= 99); gameSettings.potPayoutPercent = potPayoutPercent; } if(lastBuyerPayoutPercent > 0) { require(lastBuyerPayoutPercent >= 10 && lastBuyerPayoutPercent <= 60); gameSettings.lastBuyerPayoutPercent = lastBuyerPayoutPercent; } emit GameSettingsUpdated( maxTxAmount, tokenSwapThreshold, minimumBuyForPotEligibility, tokensToAddOneSecond, maxTimeLeft, potFeeExtraTimeLeftThreshold, eliglblePlayers, potPayoutPercent, lastBuyerPayoutPercent ); } function renounceGameSettingsUpdater() public virtual onlyGameSettingsUpdater { emit GameSettingsUpdaterUpdated(gameSettingsUpdaterAddress, address(0)); gameSettingsUpdaterAddress = address(0); } function setPresaleContractAddress(address _address) public onlyOwner { require(presaleContractAddress == address(0)); presaleContractAddress = _address; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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 > allowance")); return true; } 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 < zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be < supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be < total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidityAndPot(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function startGame() public onlyOwner { require(!gameIsActive); // start on round 1 roundNumber = roundNumber.add(1); timeLeftAtLastBuy = gameSettings.maxTimeLeft; lastBuyBlock = block.number; gameIsActive = true; emit RoundStarted( roundNumber, potValue() ); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidityAndPot) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidityAndPot, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidityAndPot); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidityAndPot = calculateLiquidityAndPotFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidityAndPot); return (tTransferAmount, tFee, tLiquidityAndPot); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidityAndPot, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidityAndPot = tLiquidityAndPot.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidityAndPot); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidityAndPot(uint256 tLiquidityAndPot) private { uint256 currentRate = _getRate(); uint256 rLiquidityAndPot = tLiquidityAndPot.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidityAndPot); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidityAndPot); //keep track of ratio of liquidity vs. pot uint256 potFee = currentPotFee(); uint256 totalFee = potFee.add(_liquidityFee); if(totalFee > 0) { potTokens = potTokens.add(tLiquidityAndPot.mul(potFee).div(totalFee)); liquidityTokens = liquidityTokens.add(tLiquidityAndPot.mul(_liquidityFee).div(totalFee)); } } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityAndPotFee(uint256 _amount) private view returns (uint256) { uint256 currentPotFee = currentPotFee(); return _amount.mul(_liquidityFee.add(currentPotFee)).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0 && _potFee == 0 && _potFeeExtra == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousPotFee = _potFee; _previousPotFeeExtra = _potFeeExtra; _taxFee = 0; _liquidityFee = 0; _potFee = 0; _potFeeExtra = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _potFee = _previousPotFee; _potFeeExtra = _previousPotFeeExtra; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function getTransferType( address from, address to) private view returns (TransferType) { if(from == uniswapV2Pair) { if(to == address(uniswapV2Router)) { return TransferType.RemoveLiquidity; } return TransferType.Buy; } if(to == uniswapV2Pair) { return TransferType.Sell; } if(from == address(uniswapV2Router)) { return TransferType.RemoveLiquidity; } return TransferType.Normal; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "transfer from the zero address"); require(to != address(0), "transfer to the zero address"); require(amount > 0, "Transfer amount must be > 0"); TransferType transferType = getTransferType(from, to); if( gameIsActive && !inSwap && transferType != TransferType.RemoveLiquidity && from != liquidityAddress && to != liquidityAddress && from != presaleContractAddress ) { require(amount <= gameSettings.maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } completeRoundWhenNoTimeLeft(); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= gameSettings.tokenSwapThreshold; if( gameIsActive && overMinTokenBalance && !inSwap && transferType != TransferType.Buy && from != liquidityAddress && to != liquidityAddress ) { inSwap = true; //Calculate how much to swap and liquify, and how much to just swap for the pot uint256 totalTokens = liquidityTokens.add(potTokens); if(totalTokens > 0) { uint256 swapTokens = contractTokenBalance.mul(liquidityTokens).div(totalTokens); //add liquidity swapAndLiquify(swapTokens); } //sell the rest uint256 sellTokens = balanceOf(address(this)); swapTokensForEth(sellTokens); liquidityTokens = 0; potTokens = 0; inSwap = false; } //indicates if fee should be deducted from transfer bool takeFee = gameIsActive; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); if( gameIsActive && transferType == TransferType.Buy ) { handleBuyer(to, amount); } } function handleBuyer(address buyer, uint256 amount) private { int256 oldTimeLeft = timeLeft(); if(oldTimeLeft < 0) { return; } int256 newTimeLeft = oldTimeLeft + int256(amount / gameSettings.tokensToAddOneSecond); bool isEligible = buyer != address(uniswapV2Router) && !_isExcludedFromFee[buyer] && amount >= gameSettings.minimumBuyForPotEligibility; if(isEligible) { Buyer memory newBuyer = Buyer( buyer, amount, uint256(oldTimeLeft), uint256(newTimeLeft), block.timestamp, block.number ); Buyer[] storage buyers = buyersByRound[roundNumber]; bool added = false; // check if buyer would have a 2nd entry in last 7, and remove old one for(int256 i = int256(buyers.length) - 1; i >= 0 && i > int256(buyers.length) - int256(gameSettings.eliglblePlayers); i--) { Buyer storage existingBuyer = buyers[uint256(i)]; if(existingBuyer.buyer == buyer) { // shift all buyers after back one, and put new buyer at end of array for(uint256 j = uint256(i).add(1); j < buyers.length; j = j.add(1)) { buyers[j.sub(1)] = buyers[j]; } buyers[buyers.length.sub(1)] = newBuyer; added = true; break; } } if(!added) { buyers.push(newBuyer); } } if(newTimeLeft < 0) { newTimeLeft = 0; } else if(newTimeLeft > int256(gameSettings.maxTimeLeft)) { newTimeLeft = int256(gameSettings.maxTimeLeft); } timeLeftAtLastBuy = uint256(newTimeLeft); lastBuyBlock = block.number; emit Buy( isEligible, buyer, amount, uint256(oldTimeLeft), uint256(newTimeLeft), block.timestamp, block.number ); } function swapAndLiquify(uint256 swapAmount) private { // split the value able to be liquified into halves uint256 half = swapAmount.div(2); uint256 otherHalf = swapAmount.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) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityAddress, block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidityAndPot) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidityAndPot(tLiquidityAndPot); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidityAndPot) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidityAndPot(tLiquidityAndPot); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidityAndPot) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidityAndPot(tLiquidityAndPot); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function potValue() public view returns (uint256) { return address(this).balance.mul(gameSettings.potPayoutPercent).div(100); } function timeLeft() public view returns (int256) { if(!gameIsActive) { return 0; } uint256 blocksSinceLastBuy = block.number.sub(lastBuyBlock); return int256(timeLeftAtLastBuy) - int256(blocksSinceLastBuy.mul(3)); } function currentPotFee() public view returns (uint256) { if(timeLeft() < int256(gameSettings.potFeeExtraTimeLeftThreshold)) { return _potFeeExtra; } return _potFee; } function completeRoundWhenNoTimeLeft() public { int256 secondsLeft = timeLeft(); if(secondsLeft >= 0) { return; } (address[] memory buyers, uint256[] memory payoutAmounts) = _getPayoutAmounts(); uint256 lastRoundNumber = roundNumber; roundNumber = roundNumber.add(1); timeLeftAtLastBuy = gameSettings.maxTimeLeft; lastBuyBlock = block.number; for(uint256 i = 0; i < buyers.length; i = i.add(1)) { uint256 amount = payoutAmounts[i]; if(amount > 0) { (bool success, ) = buyers[i].call { value: amount, gas: 5000 }(""); emit RoundPayout( lastRoundNumber, buyers[i], amount, success ); } } emit RoundEnded( lastRoundNumber, buyers, payoutAmounts ); emit RoundStarted( roundNumber, potValue() ); } function _getPayoutAmounts() internal view returns (address[] memory buyers, uint256[] memory payoutAmounts) { buyers = new address[](gameSettings.eliglblePlayers); payoutAmounts = new uint256[](gameSettings.eliglblePlayers); Buyer[] storage roundBuyers = buyersByRound[roundNumber]; if(roundBuyers.length > 0) { uint256 totalPayout = potValue(); uint256 lastBuyerPayout = totalPayout.mul(gameSettings.lastBuyerPayoutPercent).div(100); uint256 payoutLeft = totalPayout.sub(lastBuyerPayout); uint256 numberOfWinners = roundBuyers.length > gameSettings.eliglblePlayers ? gameSettings.eliglblePlayers : roundBuyers.length; uint256 amountLeft; for(int256 i = int256(roundBuyers.length) - 1; i >= int256(roundBuyers.length) - int256(numberOfWinners); i--) { amountLeft = amountLeft.add(roundBuyers[uint256(i)].amount); } uint256 returnIndex = 0; for(int256 i = int256(roundBuyers.length) - 1; i >= int256(roundBuyers.length) - int256(numberOfWinners); i--) { uint256 amount = roundBuyers[uint256(i)].amount; uint256 payout = 0; if(amountLeft > 0) { payout = payoutLeft.mul(amount).div(amountLeft); } amountLeft = amountLeft.sub(amount); payoutLeft = payoutLeft.sub(payout); buyers[returnIndex] = roundBuyers[uint256(i)].buyer; payoutAmounts[returnIndex] = payout; if(returnIndex == 0) { payoutAmounts[0] = payoutAmounts[0].add(lastBuyerPayout); } returnIndex = returnIndex.add(1); } } } function gameStats() external view returns (uint256 currentRoundNumber, int256 currentTimeLeft, uint256 currentPotValue, uint256 currentTimeLeftAtLastBuy, uint256 currentLastBuyBlock, uint256 currentBlockTime, uint256 currentBlockNumber, address[] memory lastBuyerAddress, uint256[] memory lastBuyerData) { currentRoundNumber = roundNumber; currentTimeLeft = timeLeft(); currentPotValue = potValue(); currentTimeLeftAtLastBuy = timeLeftAtLastBuy; currentLastBuyBlock = lastBuyBlock; currentBlockTime = block.timestamp; currentBlockNumber = block.number; lastBuyerAddress = new address[](gameSettings.eliglblePlayers); lastBuyerData = new uint256[](gameSettings.eliglblePlayers.mul(6)); Buyer[] storage buyers = buyersByRound[roundNumber]; uint256 iteration = 0; (, uint256[] memory payoutAmounts) = _getPayoutAmounts(); for(int256 i = int256(buyers.length) - 1; i >= 0; i--) { Buyer storage buyer = buyers[uint256(i)]; lastBuyerAddress[iteration] = buyer.buyer; lastBuyerData[iteration.mul(6).add(0)] = buyer.amount; lastBuyerData[iteration.mul(6).add(1)] = buyer.timeLeftBefore; lastBuyerData[iteration.mul(6).add(2)] = buyer.timeLeftAfter; lastBuyerData[iteration.mul(6).add(3)] = buyer.blockTime; lastBuyerData[iteration.mul(6).add(4)] = buyer.blockNumber; lastBuyerData[iteration.mul(6).add(5)] = payoutAmounts[iteration]; iteration = iteration.add(1); if(iteration == gameSettings.eliglblePlayers) { break; } } } }
* @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, "modulo by zero"); }
12,912,202
[ 1, 1356, 326, 10022, 434, 3739, 10415, 2795, 9088, 12321, 18, 261, 22297, 3571, 26109, 3631, 868, 31537, 1347, 3739, 10415, 635, 3634, 18, 9354, 2680, 358, 348, 7953, 560, 1807, 12430, 68, 3726, 18, 1220, 445, 4692, 279, 1375, 266, 1097, 68, 11396, 261, 12784, 15559, 4463, 16189, 640, 869, 19370, 13, 1323, 348, 7953, 560, 4692, 392, 2057, 11396, 358, 15226, 261, 17664, 310, 777, 4463, 16189, 2934, 29076, 30, 300, 1021, 15013, 2780, 506, 3634, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 681, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 681, 12, 69, 16, 324, 16, 315, 1711, 26478, 635, 3634, 8863, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@unification-com/xfund-router/contracts/lib/ConsumerBase.sol"; import "./interfaces/ILandRegistry.sol"; import "./LandAuction.sol"; contract LandAuctionV3 is ConsumerBase, Ownable, ReentrancyGuard { uint32 constant clearLow = 0xffff0000; uint32 constant clearHigh = 0x0000ffff; uint32 constant factor = 0x10000; int16 public constant xLow = -96; int16 public constant yLow = -99; int16 public constant xHigh = 96; int16 public constant yHigh = 99; enum Stage { Default, Inactive1, Inactive2, PublicSale } uint256 public ethToShib; bool public multiMintEnabled; LandAuction public auctionV1; LandAuction public auctionV2; ILandRegistry public landRegistry; IERC20 public immutable SHIB; Stage public currentStage; mapping(address => uint32[]) private _allMintsOf; event StageSet(uint256 stage); event multiMintToggled(bool newValue); event LandBoughtWithShib( address indexed user, uint32 indexed encXY, int16 x, int16 y, uint256 price, uint256 time, Stage saleStage ); constructor( IERC20 _shib, LandAuction _auctionV1, LandAuction _auctionV2, ILandRegistry _landRegistry, address _router, address _xfund ) ConsumerBase(_router, _xfund) { SHIB = _shib; auctionV1 = _auctionV1; auctionV2 = _auctionV2; landRegistry = _landRegistry; } modifier onlyValid(int16 x, int16 y) { require(xLow <= x && x <= xHigh, "ERR_X_OUT_OF_RANGE"); require(yLow <= y && y <= yHigh, "ERR_Y_OUT_OF_RANGE"); _; } modifier onlyStage(Stage s) { require(currentStage == s, "ERR_THIS_STAGE_NOT_LIVE_YET"); _; } function bidInfoOf(address user) external view returns (int16[] memory, int16[] memory) { (int16[] memory xsV1, int16[] memory ysV1) = auctionV2.bidInfoOf(user); uint256 lengthV1 = xsV1.length; uint256 bidCount = _allMintsOf[user].length; int16[] memory xs = new int16[](bidCount + lengthV1); int16[] memory ys = new int16[](bidCount + lengthV1); for (uint256 i = 0; i < lengthV1; i = _uncheckedInc(i)) { xs[i] = xsV1[i]; ys[i] = ysV1[i]; } uint256 ptr = lengthV1; uint32[] storage allMints = _allMintsOf[user]; uint256 length = allMints.length; for (uint256 i = 0; i < length; i = _uncheckedInc(i)) { (int16 x, int16 y) = _decodeXY(allMints[i]); xs[ptr] = x; ys[ptr] = y; ptr = _uncheckedInc(ptr); } return (xs, ys); } function getReservePriceShib(int16 x, int16 y) public view onlyValid(x, y) returns (uint256) { // this will revert if not up for sale uint256 reservePrice = auctionV1.getReservePrice(x, y); // to check if this was bid on, in the bidding stage (uint256 cAmount, ) = auctionV1.getCurrentBid(x, y); require(cAmount == 0, "ERR_ALREADY_BOUGHT"); uint256 reservePriceInShib = (ethToShib * reservePrice) / 1 ether; require(reservePriceInShib > 0, "ERR_BAD_PRICE"); return reservePriceInShib; } function mintPublicWithShib(int16 x, int16 y) external onlyStage(Stage.PublicSale) nonReentrant { // this will revert if not up for sale uint256 reservePriceInShib = getReservePriceShib(x, y); address user = msg.sender; SHIB.transferFrom(user, address(this), reservePriceInShib); uint32 encXY = _encodeXY(x, y); _allMintsOf[user].push(encXY); landRegistry.mint(user, x, y); emit LandBoughtWithShib( user, encXY, x, y, reservePriceInShib, block.timestamp, Stage.PublicSale ); } function mintPublicWithShibMulti( int16[] calldata xs, int16[] calldata ys, uint256[] calldata prices ) external onlyStage(Stage.PublicSale) nonReentrant { require(multiMintEnabled, "ERR_MULTI_BID_DISABLED"); uint256 length = xs.length; require(length != 0, "ERR_NO_INPUT"); require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH"); require(length == prices.length, "ERR_INPUT_LENGTH_MISMATCH"); uint256 total; for (uint256 i = 0; i < length; i = _uncheckedInc(i)) { total += prices[i]; } address user = msg.sender; SHIB.transferFrom(user, address(this), total); for (uint256 i = 0; i < length; i = _uncheckedInc(i)) { int16 x = xs[i]; int16 y = ys[i]; uint256 reservePriceInShib = getReservePriceShib(x, y); require( reservePriceInShib == prices[i], "ERR_INSUFFICIENT_SHIB_SENT" ); uint32 encXY = _encodeXY(x, y); _allMintsOf[user].push(encXY); landRegistry.mint(user, x, y); emit LandBoughtWithShib( user, encXY, x, y, prices[i], block.timestamp, Stage.PublicSale ); } } function setStage(uint256 stage) external onlyOwner { currentStage = Stage(stage); emit StageSet(stage); } function setLandRegistry(address _landRegistry) external onlyOwner { landRegistry = ILandRegistry(_landRegistry); } function setAuctionV1(LandAuction _auctionV1) external onlyOwner { auctionV1 = _auctionV1; } function setAuctionV2(LandAuction _auctionV2) external onlyOwner { auctionV2 = _auctionV2; } function setMultiMint(bool desiredValue) external onlyOwner { require(multiMintEnabled != desiredValue, "ERR_ALREADY_DESIRED_VALUE"); multiMintEnabled = desiredValue; emit multiMintToggled(desiredValue); } function increaseRouterAllowance(uint256 _amount) external onlyOwner { require(_increaseRouterAllowance(_amount), "ERR_FAILED_TO_INCREASE"); } function getData(address _provider, uint256 _fee) external onlyOwner returns (bytes32) { bytes32 data = 0x4554482e534849422e50522e4156430000000000000000000000000000000000; // ETH.SHIB.PR.AVC return _requestData(_provider, _fee, data); } function withdrawShib(address to, uint256 amount) external onlyOwner { SHIB.transfer(to, amount); } function withdrawAny( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } function receiveData(uint256 _price, bytes32) internal override { ethToShib = _price; } function _uncheckedInc(uint256 i) internal pure returns (uint256) { unchecked { return i + 1; } } function _encodeXY(int16 x, int16 y) internal pure returns (uint32) { return ((uint32(uint16(x)) * factor) & clearLow) | (uint32(uint16(y)) & clearHigh); } function _decodeXY(uint32 value) internal pure returns (int16 x, int16 y) { x = _expandNegative16BitCast((value & clearLow) >> 16); y = _expandNegative16BitCast(value & clearHigh); } function _expandNegative16BitCast(uint32 value) internal pure returns (int16) { if (value & (1 << 15) != 0) { return int16(int32(value | clearLow)); } return int16(int32(value)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, 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 // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../vendor/OOOSafeMath.sol"; import "../interfaces/IERC20_Ex.sol"; import "../interfaces/IRouter.sol"; import "./RequestIdBase.sol"; /** * @title ConsumerBase smart contract * * @dev This contract can be imported by any smart contract wishing to include * off-chain data or data from a different network within it. * * The consumer initiates a data request by forwarding the request to the Router * smart contract, from where the data provider(s) pick up and process the * data request, and forward it back to the specified callback function. * */ abstract contract ConsumerBase is RequestIdBase { using OOOSafeMath for uint256; /* * STATE VARIABLES */ // nonces for generating requestIds. Must be in sync with the // nonces defined in Router.sol. mapping(address => uint256) private nonces; IERC20_Ex internal immutable xFUND; IRouter internal router; /* * WRITE FUNCTIONS */ /** * @dev Contract constructor. Accepts the address for the router smart contract, * and a token allowance for the Router to spend on the consumer's behalf (to pay fees). * * The Consumer contract should have enough tokens allocated to it to pay fees * and the Router should be able to use the Tokens to forward fees. * * @param _router address of the deployed Router smart contract * @param _xfund address of the deployed xFUND smart contract */ constructor(address _router, address _xfund) { require(_router != address(0), "router cannot be the zero address"); require(_xfund != address(0), "xfund cannot be the zero address"); router = IRouter(_router); xFUND = IERC20_Ex(_xfund); } /** * @notice _setRouter is a helper function to allow changing the router contract address * Allows updating the router address. Future proofing for potential Router upgrades * NOTE: it is advisable to wrap this around a function that uses, for example, OpenZeppelin's * onlyOwner modifier * * @param _router address of the deployed Router smart contract */ function _setRouter(address _router) internal returns (bool) { require(_router != address(0), "router cannot be the zero address"); router = IRouter(_router); return true; } /** * @notice _increaseRouterAllowance is a helper function to increase token allowance for * the xFUND Router * Allows this contract to increase the xFUND allowance for the Router contract * enabling it to pay request fees on behalf of this contract. * NOTE: it is advisable to wrap this around a function that uses, for example, OpenZeppelin's * onlyOwner modifier * * @param _amount uint256 amount to increase allowance by */ function _increaseRouterAllowance(uint256 _amount) internal returns (bool) { // The context of msg.sender is this contract's address require(xFUND.increaseAllowance(address(router), _amount), "failed to increase allowance"); return true; } /** * @dev _requestData - initialises a data request. forwards the request to the deployed * Router smart contract. * * @param _dataProvider payable address of the data provider * @param _fee uint256 fee to be paid * @param _data bytes32 value of data being requested, e.g. PRICE.BTC.USD.AVG requests * average price for BTC/USD pair * @return requestId bytes32 request ID which can be used to track or cancel the request */ function _requestData(address _dataProvider, uint256 _fee, bytes32 _data) internal returns (bytes32) { bytes32 requestId = makeRequestId(address(this), _dataProvider, address(router), nonces[_dataProvider], _data); // call the underlying ConsumerLib.sol lib's submitDataRequest function require(router.initialiseRequest(_dataProvider, _fee, _data)); nonces[_dataProvider] = nonces[_dataProvider].safeAdd(1); return requestId; } /** * @dev rawReceiveData - Called by the Router's fulfillRequest function * in order to fulfil a data request. Data providers call the Router's fulfillRequest function * The request is validated to ensure it has indeed been sent via the Router. * * The Router will only call rawReceiveData once it has validated the origin of the data fulfillment. * rawReceiveData then calls the user defined receiveData function to finalise the fulfilment. * Contract developers will need to override the abstract receiveData function defined below. * * @param _price uint256 result being sent * @param _requestId bytes32 request ID of the request being fulfilled * has sent the data */ function rawReceiveData( uint256 _price, bytes32 _requestId) external { // validate it came from the router require(msg.sender == address(router), "only Router can call"); // call override function in end-user's contract receiveData(_price, _requestId); } /** * @dev receiveData - should be overridden by contract developers to process the * data fulfilment in their own contract. * * @param _price uint256 result being sent * @param _requestId bytes32 request ID of the request being fulfilled */ function receiveData( uint256 _price, bytes32 _requestId ) internal virtual; /* * READ FUNCTIONS */ /** * @dev getRouterAddress returns the address of the Router smart contract being used * * @return address */ function getRouterAddress() external view returns (address) { return address(router); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface ILandRegistry { function mint( address user, int16 x, int16 y ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/ILockShiboshi.sol"; import "./interfaces/ILockLeash.sol"; import "./interfaces/ILandRegistry.sol"; import "./interfaces/ILandAuction.sol"; contract LandAuction is ILandAuction, AccessControl, ReentrancyGuard { using ECDSA for bytes32; bytes32 public constant GRID_SETTER_ROLE = keccak256("GRID_SETTER_ROLE"); uint32 constant clearLow = 0xffff0000; uint32 constant clearHigh = 0x0000ffff; uint32 constant factor = 0x10000; uint16 public constant N = 194; // xHigh + 97 + 1 uint16 public constant M = 200; // yHigh + 100 + 1 /* xLow, yHigh gets mapped to 1,1 transform: x + 97, 100 - y y_mapped = 100 - y x_mapped = 97 + x */ int16 public constant xLow = -96; int16 public constant yLow = -99; int16 public constant xHigh = 96; int16 public constant yHigh = 99; enum Stage { Default, Bidding, PrivateSale, PublicSale } struct Bid { uint256 amount; address bidder; } address public immutable weth; ILandRegistry public landRegistry; ILockLeash public lockLeash; ILockShiboshi public lockShiboshi; bool public multiBidEnabled; address public signerAddress; Stage public currentStage; int8[N + 10][M + 10] private _categoryBIT; mapping(int16 => mapping(int16 => Bid)) public getCurrentBid; mapping(int8 => uint256) public priceOfCategory; mapping(address => uint256) public winningsBidsOf; mapping(address => uint32[]) private _allBidsOf; mapping(address => mapping(uint32 => uint8)) private _statusOfBidsOf; event CategoryPriceSet(int8 category, uint256 price); event StageSet(uint256 stage); event SignerSet(address signer); event multiBidToggled(bool newValue); event BidCreated( address indexed user, uint32 indexed encXY, int16 x, int16 y, uint256 price, uint256 time ); event LandBought( address indexed user, uint32 indexed encXY, int16 x, int16 y, uint256 price, Stage saleStage ); constructor( address _weth, ILandRegistry _landRegistry, ILockLeash _lockLeash, ILockShiboshi _lockShiboshi ) { _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(GRID_SETTER_ROLE, msg.sender); weth = _weth; landRegistry = _landRegistry; lockLeash = _lockLeash; lockShiboshi = _lockShiboshi; signerAddress = msg.sender; } modifier onlyValid(int16 x, int16 y) { require(xLow <= x && x <= xHigh, "ERR_X_OUT_OF_RANGE"); require(yLow <= y && y <= yHigh, "ERR_Y_OUT_OF_RANGE"); _; } modifier onlyStage(Stage s) { require(currentStage == s, "ERR_THIS_STAGE_NOT_LIVE_YET"); _; } function weightToCapacity(uint256 weightLeash, uint256 weightShiboshi) public pure returns (uint256) { uint256[10] memory QRangeLeash = [ uint256(9), uint256(30), uint256(60), uint256(100), uint256(130), uint256(180), uint256(220), uint256(300), uint256(370), uint256(419) ]; uint256[10] memory QRangeShiboshi = [ uint256(45), uint256(89), uint256(150), uint256(250), uint256(350), uint256(480), uint256(600), uint256(700), uint256(800), uint256(850) ]; uint256[10] memory buckets = [ uint256(1), uint256(5), uint256(10), uint256(20), uint256(50), uint256(80), uint256(100), uint256(140), uint256(180), uint256(200) ]; uint256 capacity; if (weightLeash > 0) { for (uint256 i = 9; i >= 0; i = _uncheckedDec(i)) { if (weightLeash > QRangeLeash[i] * 1e18) { capacity += buckets[i]; break; } } } if (weightShiboshi > 0) { for (uint256 i = 9; i >= 0; i = _uncheckedDec(i)) { if (weightShiboshi > QRangeShiboshi[i]) { capacity += buckets[i]; break; } } } return capacity; } function getOutbidPrice(uint256 bidPrice) public pure returns (uint256) { // 5% more than the current price return (bidPrice * 21) / 20; } function availableCapacityOf(address user) public view returns (uint256) { uint256 weightLeash = lockLeash.weightOf(user); uint256 weightShiboshi = lockShiboshi.weightOf(user); return weightToCapacity(weightLeash, weightShiboshi) - winningsBidsOf[user]; } function getReservePrice(int16 x, int16 y) public view returns (uint256) { uint256 price = priceOfCategory[getCategory(x, y)]; require(price != 0, "ERR_NOT_UP_FOR_SALE"); return price; } function getPriceOf(int16 x, int16 y) public view returns (uint256) { Bid storage currentBid = getCurrentBid[x][y]; if (currentBid.amount == 0) { return getReservePrice(x, y); } else { // attempt to outbid return getOutbidPrice(currentBid.amount); } } function getCategory(int16 x, int16 y) public view returns (int8) { (uint16 x_mapped, uint16 y_mapped) = _transformXY(x, y); int8 category; for (uint16 i = x_mapped; i > 0; i = _subLowbit(i)) { for (uint16 j = y_mapped; j > 0; j = _subLowbit(j)) { unchecked { category += _categoryBIT[i][j]; } } } return category; } function isShiboshiZone(int16 x, int16 y) public pure returns (bool) { /* (12,99) to (48, 65) (49, 99) to (77, 78) (76, 77) to (77, 50) (65, 50) to (75, 50) */ if (x >= 12 && x <= 48 && y <= 99 && y >= 65) { return true; } if (x >= 49 && x <= 77 && y <= 99 && y >= 78) { return true; } if (x >= 76 && x <= 77 && y <= 77 && y >= 50) { return true; } if (x >= 65 && x <= 75 && y == 50) { return true; } return false; } // List of currently winning bids of this user function bidInfoOf(address user) external view returns (int16[] memory, int16[] memory) { uint256 bidCount = winningsBidsOf[user]; int16[] memory xs = new int16[](bidCount); int16[] memory ys = new int16[](bidCount); uint256 ptr; uint32[] storage allBids = _allBidsOf[user]; uint256 length = allBids.length; for (uint256 i = 0; i < length; i = _uncheckedInc(i)) { if (_statusOfBidsOf[user][allBids[i]] == 1) { (int16 x, int16 y) = _decodeXY(allBids[i]); xs[ptr] = x; ys[ptr] = y; ptr = _uncheckedInc(ptr); } } return (xs, ys); } // List of all bids, ever done by this user function allBidInfoOf(address user) external view returns (int16[] memory, int16[] memory) { uint32[] storage allBids = _allBidsOf[user]; uint256 bidCount = allBids.length; int16[] memory xs = new int16[](bidCount); int16[] memory ys = new int16[](bidCount); for (uint256 i = 0; i < bidCount; i = _uncheckedInc(i)) { (int16 x, int16 y) = _decodeXY(allBids[i]); xs[i] = x; ys[i] = y; } return (xs, ys); } function setGridVal( int16 x1, int16 y1, int16 x2, int16 y2, int8 val ) external onlyRole(GRID_SETTER_ROLE) { (uint16 x1_mapped, uint16 y1_mapped) = _transformXY(x1, y1); (uint16 x2_mapped, uint16 y2_mapped) = _transformXY(x2, y2); _updateGrid(x2_mapped + 1, y2_mapped + 1, val); _updateGrid(x1_mapped, y1_mapped, val); _updateGrid(x1_mapped, y2_mapped + 1, -val); _updateGrid(x2_mapped + 1, y1_mapped, -val); } function setPriceOfCategory(int8 category, uint256 price) external onlyRole(GRID_SETTER_ROLE) { priceOfCategory[category] = price; emit CategoryPriceSet(category, price); } function setStage(uint256 stage) external onlyRole(DEFAULT_ADMIN_ROLE) { currentStage = Stage(stage); emit StageSet(stage); } function setSignerAddress(address signer) external onlyRole(DEFAULT_ADMIN_ROLE) { require(signer != address(0), "ERR_CANNOT_BE_ZERO_ADDRESS"); signerAddress = signer; emit SignerSet(signer); } function setLandRegistry(address _landRegistry) external onlyRole(DEFAULT_ADMIN_ROLE) { landRegistry = ILandRegistry(_landRegistry); } function setLockLeash(address _lockLeash) external onlyRole(DEFAULT_ADMIN_ROLE) { lockLeash = ILockLeash(_lockLeash); } function setLockShiboshi(address _lockShiboshi) external onlyRole(DEFAULT_ADMIN_ROLE) { lockShiboshi = ILockShiboshi(_lockShiboshi); } function setMultiBid(bool desiredValue) external onlyRole(DEFAULT_ADMIN_ROLE) { require(multiBidEnabled != desiredValue, "ERR_ALREADY_DESIRED_VALUE"); multiBidEnabled = desiredValue; emit multiBidToggled(desiredValue); } function withdraw(address to, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { payable(to).transfer(amount); } function bidOne(int16 x, int16 y) external payable onlyStage(Stage.Bidding) nonReentrant { address user = msg.sender; require(availableCapacityOf(user) != 0, "ERR_NO_BIDS_REMAINING"); require(!isShiboshiZone(x, y), "ERR_NO_MINT_IN_SHIBOSHI_ZONE"); _bid(user, x, y, msg.value); } function bidShiboshiZoneOne( int16 x, int16 y, bytes calldata signature ) external payable onlyStage(Stage.Bidding) nonReentrant { address user = msg.sender; require( _verifySigner(_hashMessage(user), signature), "ERR_SIGNATURE_INVALID" ); require(isShiboshiZone(x, y), "ERR_NOT_IN_SHIBOSHI_ZONE"); _bid(user, x, y, msg.value); } function bidMulti( int16[] calldata xs, int16[] calldata ys, uint256[] calldata prices ) external payable onlyStage(Stage.Bidding) nonReentrant { require(multiBidEnabled, "ERR_MULTI_BID_DISABLED"); address user = msg.sender; uint256 length = xs.length; require(length != 0, "ERR_NO_INPUT"); require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH"); require(length == prices.length, "ERR_INPUT_LENGTH_MISMATCH"); uint256 total; require( availableCapacityOf(user) >= length, "ERR_INSUFFICIENT_BIDS_REMAINING" ); for (uint256 i = 0; i < length; i = _uncheckedInc(i)) { total += prices[i]; } require(msg.value == total, "ERR_INSUFFICIENT_AMOUNT_SENT"); for (uint256 i = 0; i < length; i = _uncheckedInc(i)) { int16 x = xs[i]; int16 y = ys[i]; require(!isShiboshiZone(x, y), "ERR_NO_MINT_IN_SHIBOSHI_ZONE"); _bid(user, x, y, prices[i]); } } function bidShiboshiZoneMulti( int16[] calldata xs, int16[] calldata ys, uint256[] calldata prices, bytes calldata signature ) external payable onlyStage(Stage.Bidding) nonReentrant { require(multiBidEnabled, "ERR_MULTI_BID_DISABLED"); address user = msg.sender; require( _verifySigner(_hashMessage(user), signature), "ERR_SIGNATURE_INVALID" ); uint256 length = xs.length; require(length != 0, "ERR_NO_INPUT"); require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH"); require(length == prices.length, "ERR_INPUT_LENGTH_MISMATCH"); uint256 total; for (uint256 i = 0; i < length; i = _uncheckedInc(i)) { total += prices[i]; } require(msg.value == total, "ERR_INSUFFICIENT_AMOUNT_SENT"); for (uint256 i = 0; i < length; i = _uncheckedInc(i)) { int16 x = xs[i]; int16 y = ys[i]; require(isShiboshiZone(x, y), "ERR_NOT_IN_SHIBOSHI_ZONE"); _bid(user, x, y, prices[i]); } } function mintWinningBid(int16[] calldata xs, int16[] calldata ys) external { require( currentStage == Stage.PublicSale || currentStage == Stage.PrivateSale, "ERR_MUST_WAIT_FOR_BIDDING_TO_END" ); uint256 length = xs.length; require(length == ys.length, "ERR_INPUT_LENGTH_MISMATCH"); for (uint256 i = 0; i < length; i = _uncheckedInc(i)) { int16 x = xs[i]; int16 y = ys[i]; require(xLow <= x && x <= xHigh, "ERR_X_OUT_OF_RANGE"); require(yLow <= y && y <= yHigh, "ERR_Y_OUT_OF_RANGE"); address user = getCurrentBid[x][y].bidder; require(user != address(0), "ERR_NO_BID_FOUND"); landRegistry.mint(user, x, y); } } function mintPrivate(int16 x, int16 y) external payable onlyStage(Stage.PrivateSale) nonReentrant { require(availableCapacityOf(msg.sender) != 0, "ERR_NO_BIDS_REMAINING"); require(!isShiboshiZone(x, y), "ERR_NO_MINT_IN_SHIBOSHI_ZONE"); _mintPublicOrPrivate(msg.sender, x, y); emit LandBought( msg.sender, _encodeXY(x, y), x, y, msg.value, Stage.PrivateSale ); } function mintPrivateShiboshiZone( int16 x, int16 y, bytes calldata signature ) external payable onlyStage(Stage.PrivateSale) nonReentrant { require( _verifySigner(_hashMessage(msg.sender), signature), "ERR_SIGNATURE_INVALID" ); require(isShiboshiZone(x, y), "ERR_NOT_IN_SHIBOSHI_ZONE"); _mintPublicOrPrivate(msg.sender, x, y); emit LandBought( msg.sender, _encodeXY(x, y), x, y, msg.value, Stage.PrivateSale ); } function mintPublic(int16 x, int16 y) external payable onlyStage(Stage.PublicSale) nonReentrant { _mintPublicOrPrivate(msg.sender, x, y); emit LandBought( msg.sender, _encodeXY(x, y), x, y, msg.value, Stage.PublicSale ); } // transform: +97, +100 function _transformXY(int16 x, int16 y) internal pure onlyValid(x, y) returns (uint16, uint16) { return (uint16(x + 97), uint16(100 - y)); } function _bid( address user, int16 x, int16 y, uint256 price ) internal onlyValid(x, y) { uint32 encXY = _encodeXY(x, y); Bid storage currentBid = getCurrentBid[x][y]; if (currentBid.amount == 0) { // first bid on this land require( price >= getReservePrice(x, y), "ERR_INSUFFICIENT_AMOUNT_SENT" ); } else { // attempt to outbid require(user != currentBid.bidder, "ERR_CANNOT_OUTBID_YOURSELF"); require( price >= getOutbidPrice(currentBid.amount), "ERR_INSUFFICIENT_AMOUNT_SENT" ); _safeTransferETHWithFallback(currentBid.bidder, currentBid.amount); winningsBidsOf[currentBid.bidder] -= 1; _statusOfBidsOf[currentBid.bidder][encXY] = 2; } currentBid.bidder = user; currentBid.amount = price; winningsBidsOf[user] += 1; if (_statusOfBidsOf[user][encXY] == 0) { // user has never bid on this land earlier _allBidsOf[user].push(encXY); } _statusOfBidsOf[user][encXY] = 1; emit BidCreated(user, encXY, x, y, price, block.timestamp); } function _mintPublicOrPrivate( address user, int16 x, int16 y ) internal onlyValid(x, y) { Bid storage currentBid = getCurrentBid[x][y]; require(currentBid.amount == 0, "ERR_NOT_UP_FOR_SALE"); require( msg.value == getReservePrice(x, y), "ERR_INSUFFICIENT_AMOUNT_SENT" ); currentBid.bidder = user; currentBid.amount = msg.value; winningsBidsOf[user] += 1; uint32 encXY = _encodeXY(x, y); _allBidsOf[user].push(encXY); _statusOfBidsOf[user][encXY] = 1; landRegistry.mint(user, x, y); } function _hashMessage(address sender) private pure returns (bytes32) { return keccak256(abi.encodePacked(sender)); } function _verifySigner(bytes32 messageHash, bytes memory signature) private view returns (bool) { return signerAddress == messageHash.toEthSignedMessageHash().recover(signature); } /** * @notice Transfer ETH. If the ETH transfer fails, wrap the ETH and try send it as WETH. */ function _safeTransferETHWithFallback(address to, uint256 amount) internal { if (!_safeTransferETH(to, amount)) { IWETH(weth).deposit{value: amount}(); IERC20(weth).transfer(to, amount); } } /** * @notice Transfer ETH and return the success status. * @dev This function only forwards 30,000 gas to the callee. */ function _safeTransferETH(address to, uint256 value) internal returns (bool) { (bool success, ) = to.call{value: value, gas: 30_000}(new bytes(0)); return success; } function _uncheckedInc(uint256 i) internal pure returns (uint256) { unchecked { return i + 1; } } function _uncheckedDec(uint256 i) internal pure returns (uint256) { unchecked { return i - 1; } } function _encodeXY(int16 x, int16 y) internal pure returns (uint32) { return ((uint32(uint16(x)) * factor) & clearLow) | (uint32(uint16(y)) & clearHigh); } function _decodeXY(uint32 value) internal pure returns (int16 x, int16 y) { x = _expandNegative16BitCast((value & clearLow) >> 16); y = _expandNegative16BitCast(value & clearHigh); } function _expandNegative16BitCast(uint32 value) internal pure returns (int16) { if (value & (1 << 15) != 0) { return int16(int32(value | clearLow)); } return int16(int32(value)); } // Functions for BIT function _updateGrid( uint16 x, uint16 y, int8 val ) internal { for (uint16 i = x; i <= N; i = _addLowbit(i)) { for (uint16 j = y; j <= M; j = _addLowbit(j)) { unchecked { _categoryBIT[i][j] += val; } } } } function _addLowbit(uint16 i) internal pure returns (uint16) { unchecked { return i + uint16(int16(i) & (-int16(i))); } } function _subLowbit(uint16 i) internal pure returns (uint16) { unchecked { return i - uint16(int16(i) & (-int16(i))); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^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 OOOSafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function safeAdd(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 safeSub(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 safeMul(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 saveDiv(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 safeMod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20_Ex { /** * @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 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); /** * @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; interface IRouter { function initialiseRequest(address, uint256, bytes32) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title RequestIdBase * * @dev A contract used by ConsumerBase and Router to generate requestIds * */ contract RequestIdBase { /** * @dev makeRequestId generates a requestId * * @param _dataConsumer address of consumer contract * @param _dataProvider address of provider * @param _router address of Router contract * @param _requestNonce uint256 request nonce * @param _data bytes32 hex encoded data endpoint * * @return bytes32 requestId */ function makeRequestId( address _dataConsumer, address _dataProvider, address _router, uint256 _requestNonce, bytes32 _data) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_dataConsumer, _dataProvider, _router, _requestNonce, _data)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @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 virtual 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 virtual { 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 virtual 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 revoked `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}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ 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); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) 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 // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.13; interface IWETH { function deposit() external payable; function withdraw(uint256 wad) external; function transfer(address to, uint256 value) external returns (bool); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface ILockShiboshi { function lockInfoOf(address user) external view returns ( uint256[] memory ids, uint256 startTime, uint256 numDays, address ogUser ); function weightOf(address user) external view returns (uint256); function extraShiboshiNeeded(address user, uint256 targetWeight) external view returns (uint256); function extraDaysNeeded(address user, uint256 targetWeight) external view returns (uint256); function isWinner(address user) external view returns (bool); function unlockAt(address user) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface ILockLeash { function lockInfoOf(address user) external view returns ( uint256 amount, uint256 startTime, uint256 numDays, address ogUser ); function weightOf(address user) external view returns (uint256); function extraLeashNeeded(address user, uint256 targetWeight) external view returns (uint256); function extraDaysNeeded(address user, uint256 targetWeight) external view returns (uint256); function isWinner(address user) external view returns (bool); function unlockAt(address user) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface ILandAuction { function winningsBidsOf(address user) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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 makeRequestId generates a requestId @param _dataConsumer address of consumer contract @param _dataProvider address of provider @param _router address of Router contract @param _requestNonce uint256 request nonce @param _data bytes32 hex encoded data endpoint @return bytes32 requestId/
bytes32 _data) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_dataConsumer, _dataProvider, _router, _requestNonce, _data)); }
1,496,186
[ 1, 6540, 15493, 6026, 279, 14459, 225, 389, 892, 5869, 1758, 434, 4765, 6835, 225, 389, 892, 2249, 1758, 434, 2893, 225, 389, 10717, 1758, 434, 9703, 6835, 225, 389, 2293, 13611, 2254, 5034, 590, 7448, 225, 389, 892, 1731, 1578, 3827, 3749, 501, 2494, 327, 1731, 1578, 14459, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 1731, 1578, 389, 892, 13, 2713, 16618, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 327, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 892, 5869, 16, 389, 892, 2249, 16, 389, 10717, 16, 389, 2293, 13611, 16, 389, 892, 10019, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x1986A627F3c597A9EA6c1735974CfB43aBEA7953/sources/Users/riccardoperego/Desktop/Home/Coding/defi/BSCArbExecutor/contracts/ArbExecutorBSC.sol
SETUP OWNER ADDRESS VARIABLE
contract ArbExecutor { address public Uniswap_Router_Address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public Bakery_Router_Address = 0xCDe540d7eAFE93aC5fE6233Bee57E1270D3E330F; address public Pancake_Router_Address = 0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F; address public WETH_Address = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; Uniswap_Router_Interface Uniswap_Router; Pancakeswap_Router_Interface Pancakeswap_Router; Bakeryswap_Router_Interface Bakeryswap_Router; WETH_Interface WETH; address payable public owner; event Received(address, uint256); constructor() payable { Uniswap_Router = Uniswap_Router_Interface(Uniswap_Router_Address); Pancakeswap_Router = Pancakeswap_Router_Interface(Pancake_Router_Address); Bakeryswap_Router = Bakeryswap_Router_Interface(Bakery_Router_Address); WETH = WETH_Interface(WETH_Address); } receive() external payable { emit Received(msg.sender, msg.value); } function ST1OP1(address token, uint256 amountIn, uint256 amountMin1, uint256 amountMin2) public { uint256 out1 = Uniswap_EthToToken(token, amountIn, amountMin1); uint256 out2 = Uniswap_TokenToEth(token, out1, amountMin2); } function Uniswap_EthToToken(address token, uint256 amountIn, uint256 amountOutMin) public payable returns (uint256 amountOut) { address[] memory path = new address[](2); path[0] = Uniswap_Router.WETH(); path[1] = token; path, address(this), deadline ); return amounts[amounts.length-1]; } uint256[] memory amounts = Uniswap_Router.swapExactETHForTokens{value: amountIn}( function Uniswap_TokenToEth(address token, uint256 amountIn, uint256 amountOutMin) public payable returns (uint256 amountOut) { require( IERC20_Interface(token).approve(address(Uniswap_Router), (amountIn + 100000)), "Smart contract approval failed" ); address[] memory path = new address[](2); uint256 deadline = block.timestamp + 600; path[0] = token; path[1] = WETH_Address; uint256[] memory amounts = Uniswap_Router.swapExactTokensForETH( amountIn, path, address(this), deadline ); return amounts[amounts.length-1]; } function drain() external { owner.transfer(address(this).balance); } function byebye() public { require(msg.sender == owner); owner.transfer(address(this).balance); selfdestruct(msg.sender); } function transferToken(address token, uint256 amount, address recepient) public { require(msg.sender == owner); require(IERC20_Interface(token).transfer(recepient, amount)); } }
16,231,329
[ 1, 4043, 3079, 531, 22527, 11689, 10203, 22965, 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, 16351, 1201, 70, 6325, 288, 203, 565, 1758, 1071, 1351, 291, 91, 438, 67, 8259, 67, 1887, 273, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 31, 203, 565, 1758, 1071, 605, 581, 627, 67, 8259, 67, 1887, 273, 374, 14626, 758, 6564, 20, 72, 27, 73, 6799, 41, 11180, 69, 39, 25, 74, 41, 8898, 3707, 27997, 10321, 41, 2138, 7301, 40, 23, 41, 3707, 20, 42, 31, 203, 565, 1758, 1071, 12913, 23780, 67, 8259, 67, 1887, 273, 374, 92, 6260, 74, 42, 22, 38, 20, 2290, 8148, 7950, 28, 37, 8642, 3361, 70, 2486, 13459, 24, 74, 29, 73, 3437, 69, 40, 72, 4848, 28, 39, 27, 42, 31, 203, 565, 1758, 1071, 678, 1584, 44, 67, 1887, 273, 374, 7669, 20, 37, 21, 41, 4763, 10689, 2499, 1578, 22, 72, 10580, 2733, 21, 41, 4630, 74, 28, 4449, 69, 20, 39, 5082, 39, 22, 71, 42, 3103, 29, 39, 31, 203, 203, 565, 1351, 291, 91, 438, 67, 8259, 67, 1358, 1351, 291, 91, 438, 67, 8259, 31, 203, 565, 12913, 71, 3223, 91, 438, 67, 8259, 67, 1358, 12913, 71, 3223, 91, 438, 67, 8259, 31, 203, 565, 605, 581, 627, 22270, 67, 8259, 67, 1358, 605, 581, 627, 22270, 67, 8259, 31, 203, 203, 565, 678, 1584, 44, 67, 1358, 678, 1584, 44, 31, 203, 203, 565, 1758, 8843, 429, 1071, 3410, 31, 203, 2 ]
./full_match/100/0x62D007D4c4Db781C24FF6ac19279B9A9Ec32b344/sources/contracts/recover/recover.sol
* @dev Reimburse owner of the item if the finder fails to pay the fee. @param _claimID The index of the claim./
function timeOutByOwner(uint _claimID) public { Claim storage itemClaim = claims[_claimID]; require( itemClaim.status == Status.WaitingFinder, "The transaction of the item must waiting on the finder." ); require(block.timestamp - itemClaim.lastInteraction >= feeTimeout, "Timeout time has not passed yet."); if (itemClaim.finderFee != 0) { address payable finder = payable(itemClaim.finder); finder.send(itemClaim.finderFee); itemClaim.finderFee = 0; } executeRuling(_claimID, uint(RulingOptions.OwnerWins)); }
14,273,937
[ 1, 426, 381, 70, 295, 307, 3410, 434, 326, 761, 309, 326, 7532, 6684, 358, 8843, 326, 14036, 18, 282, 389, 14784, 734, 1021, 770, 434, 326, 7516, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 813, 1182, 858, 5541, 12, 11890, 389, 14784, 734, 13, 1071, 288, 203, 3639, 18381, 2502, 761, 9762, 273, 11955, 63, 67, 14784, 734, 15533, 203, 203, 3639, 2583, 12, 203, 5411, 761, 9762, 18, 2327, 422, 2685, 18, 15946, 8441, 16, 203, 5411, 315, 1986, 2492, 434, 326, 761, 1297, 7336, 603, 326, 7532, 1199, 203, 3639, 11272, 203, 3639, 2583, 12, 2629, 18, 5508, 300, 761, 9762, 18, 2722, 17419, 1545, 14036, 2694, 16, 315, 2694, 813, 711, 486, 2275, 4671, 1199, 1769, 203, 203, 3639, 309, 261, 1726, 9762, 18, 15356, 14667, 480, 374, 13, 288, 203, 5411, 1758, 8843, 429, 7532, 273, 8843, 429, 12, 1726, 9762, 18, 15356, 1769, 203, 203, 5411, 7532, 18, 4661, 12, 1726, 9762, 18, 15356, 14667, 1769, 203, 5411, 761, 9762, 18, 15356, 14667, 273, 374, 31, 203, 3639, 289, 203, 203, 3639, 1836, 54, 332, 310, 24899, 14784, 734, 16, 2254, 12, 54, 332, 310, 1320, 18, 5541, 59, 2679, 10019, 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 ]
pragma solidity ^0.4.24; /** * Easy Hold Contract * INVEST AND HOLD * NO COMMISSION NO FEES NO REFERRALS NO OWNER * !!! THE MORE YOU HOLD THE MORE YOU GET !!! * * ======== PAYAOUT TABLE ======== * DAYS PAYOUT * HOLD % * 1 0,16 * 2 0,64 * 3 1,44 * 4 2,56 * 5 4 * 6 5,76 * 7 7,84 * 8 10,24 * 9 12,96 * 10 16 * 11 19,36 * 12 23,04 * 13 27,04 * 14 31,36 * 15 36 * 16 40,96 * 17 46,24 * 18 51,84 * 19 57,76 * 20 64 * 21 70,56 * 22 77,44 * 23 84,64 * 24 92,16 * 25 100 <- YOU&#39;ll get 100% if you HOLD for 25 days * 26 108,16 * 27 116,64 * 28 125,44 * 29 134,56 * 30 144 * 31 153,76 * 32 163,84 * 33 174,24 * 34 184,96 * 35 196 <- YOU&#39;ll get 200% if you HOLD for 35 days * AND SO ON * * How to use: * 1. Send any amount of ether to make an investment * 2. Wait some time. The more you wait the more your proft is * 3. Claim your profit by sending 0 ether transaction * * RECOMMENDED GAS LIMIT: 70000 * */ contract EasyHOLD { mapping (address => uint256) invested; // records amounts invested mapping (address => uint256) atTime; // records time at which investments were made // this function called every time anyone sends a transaction to this contract function () external payable { // if sender (aka YOU) is invested more than 0 ether if (invested[msg.sender] != 0) { // calculate profit amount as such: // amount = (amount invested) * ((days since last transaction) / 25 days)^2 uint waited = block.timestamp - atTime[msg.sender]; uint256 amount = invested[msg.sender] * waited * waited / (25 days) / (25 days); msg.sender.send(amount);// send calculated amount to sender (aka YOU) } // record block number and invested amount (msg.value) of this transaction atTime[msg.sender] = block.timestamp; invested[msg.sender] += msg.value; } }
this function called every time anyone sends a transaction to this contract
contract EasyHOLD { function () external payable { if (invested[msg.sender] != 0) { uint waited = block.timestamp - atTime[msg.sender]; uint256 amount = invested[msg.sender] * waited * waited / (25 days) / (25 days); } invested[msg.sender] += msg.value; } function () external payable { if (invested[msg.sender] != 0) { uint waited = block.timestamp - atTime[msg.sender]; uint256 amount = invested[msg.sender] * waited * waited / (25 days) / (25 days); } invested[msg.sender] += msg.value; } atTime[msg.sender] = block.timestamp; }
10,523,459
[ 1, 2211, 445, 2566, 3614, 813, 1281, 476, 9573, 279, 2492, 358, 333, 6835, 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, 16351, 29442, 44, 11846, 288, 203, 203, 7010, 565, 445, 1832, 3903, 8843, 429, 288, 203, 3639, 309, 261, 5768, 3149, 63, 3576, 18, 15330, 65, 480, 374, 13, 288, 203, 5411, 2254, 2529, 329, 273, 1203, 18, 5508, 300, 622, 950, 63, 3576, 18, 15330, 15533, 203, 5411, 2254, 5034, 3844, 273, 2198, 3149, 63, 3576, 18, 15330, 65, 380, 2529, 329, 380, 2529, 329, 342, 261, 2947, 4681, 13, 342, 261, 2947, 4681, 1769, 203, 203, 3639, 289, 203, 203, 3639, 2198, 3149, 63, 3576, 18, 15330, 65, 1011, 1234, 18, 1132, 31, 203, 565, 289, 203, 565, 445, 1832, 3903, 8843, 429, 288, 203, 3639, 309, 261, 5768, 3149, 63, 3576, 18, 15330, 65, 480, 374, 13, 288, 203, 5411, 2254, 2529, 329, 273, 1203, 18, 5508, 300, 622, 950, 63, 3576, 18, 15330, 15533, 203, 5411, 2254, 5034, 3844, 273, 2198, 3149, 63, 3576, 18, 15330, 65, 380, 2529, 329, 380, 2529, 329, 342, 261, 2947, 4681, 13, 342, 261, 2947, 4681, 1769, 203, 203, 3639, 289, 203, 203, 3639, 2198, 3149, 63, 3576, 18, 15330, 65, 1011, 1234, 18, 1132, 31, 203, 565, 289, 203, 3639, 622, 950, 63, 3576, 18, 15330, 65, 273, 1203, 18, 5508, 31, 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 ]
pragma solidity ^0.4.13; interface IFlyDropTokenMgr { // Send tokens to other multi addresses in one function function prepare(uint256 _rand, address _from, address _token, uint256 _value) external returns (bool); // Send tokens to other multi addresses in one function function flyDrop(address[] _destAddrs, uint256[] _values) external returns (uint256); // getter to determine if address has poweruser role function isPoweruser(address _addr) external view returns (bool); } interface ILockedStorage { // get frozen status for the _wallet address function frozenAccounts(address _wallet) external view returns (bool); // get a wallet address by the account address and the index function isExisted(address _wallet) external view returns (bool); // get a wallet name by the account address and the index function walletName(address _wallet) external view returns (string); // get the frozen amount of the account address function frozenAmount(address _wallet) external view returns (uint256); // get the balance of the account address function balanceOf(address _wallet) external view returns (uint256); // get the account address by index function addressByIndex(uint256 _ind) external view returns (address); // get the number of the locked stage of the target address function lockedStagesNum(address _target) external view returns (uint256); // get the endtime of the locked stages of an account function endTimeOfStage(address _target, uint _ind) external view returns (uint256); // get the remain unrleased tokens of the locked stages of an account function remainOfStage(address _target, uint _ind) external view returns (uint256); // get the remain unrleased tokens of the locked stages of an account function amountOfStage(address _target, uint _ind) external view returns (uint256); // get the remain releasing period end time of an account function releaseEndTimeOfStage(address _target, uint _ind) external view returns (uint256); // get the frozen amount of the account address function size() external view returns (uint256); // add one account address for that wallet function addAccount(address _wallet, string _name, uint256 _value) external returns (bool); // add a time record of one account function addLockedTime(address _target, uint256 _value, uint256 _frozenEndTime, uint256 _releasePeriod) external returns (bool); // freeze or release the tokens that has been locked in the account address. function freezeTokens(address _wallet, bool _freeze, uint256 _value) external returns (bool); // increase balance of this account address function increaseBalance(address _wallet, uint256 _value) external returns (bool); // decrease balance of this account address function decreaseBalance(address _wallet, uint256 _value) external returns (bool); // remove account contract address from storage function removeAccount(address _wallet) external returns (bool); // remove a time records from the time records list of one account function removeLockedTime(address _target, uint _ind) external returns (bool); // set the new endtime of the released time of an account function changeEndTime(address _target, uint256 _ind, uint256 _newEndTime) external returns (bool); // set the new released period end time of an account function setNewReleaseEndTime(address _target, uint256 _ind, uint256 _newReleaseEndTime) external returns (bool); // decrease the remaining locked amount of an account function decreaseRemainLockedOf(address _target, uint256 _ind, uint256 _value) external returns (bool); // withdraw tokens from this contract function withdrawToken(address _token, address _to, uint256 _value) external returns (bool); } 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; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract DelayedClaimable is Claimable { uint256 public end; uint256 public start; /** * @dev Used to specify the time period during which a pending * owner can claim ownership. * @param _start The earliest time ownership can be claimed. * @param _end The latest time ownership can be claimed. */ function setLimits(uint256 _start, uint256 _end) public onlyOwner { require(_start <= _end); end = _end; start = _start; } /** * @dev Allows the pendingOwner address to finalize the transfer, as long as it is called within * the specified start and end time. */ function claimOwnership() public onlyPendingOwner { require((block.number <= end) && (block.number >= start)); emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); end = 0; } } contract OwnerContract is DelayedClaimable { Claimable public ownedContract; address public pendingOwnedOwner; // address internal origOwner; /** * @dev bind a contract as its owner * * @param _contract the contract address that will be binded by this Owner Contract */ function bindContract(address _contract) onlyOwner public returns (bool) { require(_contract != address(0)); ownedContract = Claimable(_contract); // origOwner = ownedContract.owner(); // take ownership of the owned contract if (ownedContract.owner() != address(this)) { ownedContract.claimOwnership(); } return true; } /** * @dev change the owner of the contract from this contract address to the original one. * */ // function transferOwnershipBack() onlyOwner public { // ownedContract.transferOwnership(origOwner); // ownedContract = Claimable(address(0)); // origOwner = address(0); // } /** * @dev change the owner of the contract from this contract address to another one. * * @param _nextOwner the contract address that will be next Owner of the original Contract */ function changeOwnershipto(address _nextOwner) onlyOwner public { require(ownedContract != address(0)); if (ownedContract.owner() != pendingOwnedOwner) { ownedContract.transferOwnership(_nextOwner); pendingOwnedOwner = _nextOwner; // ownedContract = Claimable(address(0)); // origOwner = address(0); } else { // the pending owner has already taken the ownership ownedContract = Claimable(address(0)); pendingOwnedOwner = address(0); } } /** * @dev to confirm the owner of the owned contract has already been transferred. * */ function ownedOwnershipTransferred() onlyOwner public returns (bool) { require(ownedContract != address(0)); if (ownedContract.owner() == pendingOwnedOwner) { // the pending owner has already taken the ownership ownedContract = Claimable(address(0)); pendingOwnedOwner = address(0); return true; } else { return false; } } } contract ReleaseAndLockToken is OwnerContract { using SafeMath for uint256; ILockedStorage lockedStorage; IFlyDropTokenMgr flyDropMgr; // ERC20 public erc20tk; mapping (address => uint256) preReleaseAmounts; event ReleaseFunds(address indexed _target, uint256 _amount); /** * @dev bind a contract as its owner * * @param _contract the LockedStorage contract address that will be binded by this Owner Contract * @param _flyDropContract the flydrop contract for transfer tokens from the fixed main accounts */ function initialize(address _contract, address _flyDropContract) onlyOwner public returns (bool) { require(_contract != address(0)); require(_flyDropContract != address(0)); require(super.bindContract(_contract)); lockedStorage = ILockedStorage(_contract); flyDropMgr = IFlyDropTokenMgr(_flyDropContract); // erc20tk = ERC20(_tk); return true; } /** * judge whether we need to release some of the locked token * */ function needRelease() public view returns (bool) { uint256 len = lockedStorage.size(); uint256 i = 0; while (i < len) { address frozenAddr = lockedStorage.addressByIndex(i); uint256 timeRecLen = lockedStorage.lockedStagesNum(frozenAddr); uint256 j = 0; while (j < timeRecLen) { if (now >= lockedStorage.endTimeOfStage(frozenAddr, j)) { return true; } j = j.add(1); } i = i.add(1); } return false; } /** * @dev judge whether we need to release the locked token of the target address * @param _target the owner of the amount of tokens * */ function needReleaseFor(address _target) public view returns (bool) { require(_target != address(0)); uint256 timeRecLen = lockedStorage.lockedStagesNum(_target); uint256 j = 0; while (j < timeRecLen) { if (now >= lockedStorage.endTimeOfStage(_target, j)) { return true; } j = j.add(1); } return false; } /** * @dev freeze the amount of tokens of an account * * @param _target the owner of some amount of tokens * @param _name the user name of the _target * @param _value the amount of the tokens * @param _frozenEndTime the end time of the lock period, unit is second * @param _releasePeriod the locking period, unit is second */ function freeze(address _target, string _name, uint256 _value, uint256 _frozenEndTime, uint256 _releasePeriod) onlyOwner public returns (bool) { //require(_tokenAddr != address(0)); require(_target != address(0)); require(_value > 0); require(_frozenEndTime > 0); if (!lockedStorage.isExisted(_target)) { lockedStorage.addAccount(_target, _name, _value); // add new account } // each time the new locked time will be added to the backend require(lockedStorage.addLockedTime(_target, _value, _frozenEndTime, _releasePeriod)); require(lockedStorage.freezeTokens(_target, true, _value)); return true; } /** * @dev transfer an amount of tokens to an account, and then freeze the tokens * * @param _target the account address that will hold an amount of the tokens * @param _name the user name of the _target * @param _from the tokens holder who will transfer the tokens to target address * @param _tk the erc20 token need to be transferred * @param _value the amount of the tokens which has been transferred * @param _frozenEndTime the end time of the lock period, unit is second * @param _releasePeriod the locking period, unit is second */ function transferAndFreeze(address _target, string _name, address _from, address _tk, uint256 _value, uint256 _frozenEndTime, uint256 _releasePeriod) onlyOwner public returns (bool) { require(_from != address(0)); require(_target != address(0)); require(_value > 0); require(_frozenEndTime > 0); // check firstly that the allowance of this contract has been set // require(owned.allowance(msg.sender, this) > 0); uint rand = now % 6 + 7; // random number between 7 to 12 require(flyDropMgr.prepare(rand, _from, _tk, _value)); // now we need transfer the funds before freeze them // require(owned.transferFrom(msg.sender, lockedStorage, _value)); address[] memory dests = new address[](1); dests[0] = address(lockedStorage); uint256[] memory amounts = new uint256[](1); amounts[0] = _value; require(flyDropMgr.flyDrop(dests, amounts) >= 1); if (!lockedStorage.isExisted(_target)) { require(lockedStorage.addAccount(_target, _name, _value)); } else { require(lockedStorage.increaseBalance(_target, _value)); } // freeze the account after transfering funds require(freeze(_target, _name, _value, _frozenEndTime, _releasePeriod)); return true; } /** * @dev transfer an amount of tokens to an account, and then freeze the tokens * * @param _target the account address that will hold an amount of the tokens * @param _tk the erc20 token need to be transferred * @param _value the amount of the tokens which has been transferred */ function releaseTokens(address _target, address _tk, uint256 _value) internal { require(lockedStorage.withdrawToken(_tk, _target, _value)); require(lockedStorage.freezeTokens(_target, false, _value)); require(lockedStorage.decreaseBalance(_target, _value)); } /** * @dev release the token which are locked for once and will be total released at once * after the end point of the lock period * @param _tk the erc20 token need to be transferred */ function releaseAllOnceLock(address _tk) onlyOwner public returns (bool) { require(_tk != address(0)); uint256 len = lockedStorage.size(); uint256 i = 0; while (i < len) { address target = lockedStorage.addressByIndex(i); if (lockedStorage.lockedStagesNum(target) == 1 && lockedStorage.endTimeOfStage(target, 0) == lockedStorage.releaseEndTimeOfStage(target, 0) && lockedStorage.endTimeOfStage(target, 0) > 0 && now >= lockedStorage.endTimeOfStage(target, 0)) { uint256 releasedAmount = lockedStorage.amountOfStage(target, 0); // remove current release period time record if (!lockedStorage.removeLockedTime(target, 0)) { return false; } // remove the froze account if (!lockedStorage.removeAccount(target)) { return false; } releaseTokens(target, _tk, releasedAmount); emit ReleaseFunds(target, releasedAmount); len = len.sub(1); } else { // no account has been removed i = i.add(1); } } return true; } /** * @dev release the locked tokens owned by an account, which only have only one locked time * and don't have release stage. * * @param _target the account address that hold an amount of locked tokens * @param _tk the erc20 token need to be transferred */ function releaseAccount(address _target, address _tk) onlyOwner public returns (bool) { require(_tk != address(0)); if (!lockedStorage.isExisted(_target)) { return false; } if (lockedStorage.lockedStagesNum(_target) == 1 && lockedStorage.endTimeOfStage(_target, 0) == lockedStorage.releaseEndTimeOfStage(_target, 0) && lockedStorage.endTimeOfStage(_target, 0) > 0 && now >= lockedStorage.endTimeOfStage(_target, 0)) { uint256 releasedAmount = lockedStorage.amountOfStage(_target, 0); // remove current release period time record if (!lockedStorage.removeLockedTime(_target, 0)) { return false; } // remove the froze account if (!lockedStorage.removeAccount(_target)) { return false; } releaseTokens(_target, _tk, releasedAmount); emit ReleaseFunds(_target, releasedAmount); } // if the account are not locked for once, we will do nothing here return true; } /** * @dev release the locked tokens owned by an account with several stages * this need the contract get approval from the account by call approve() in the token contract * * @param _target the account address that hold an amount of locked tokens * @param _tk the erc20 token need to be transferred */ function releaseWithStage(address _target, address _tk) onlyOwner public returns (bool) { require(_tk != address(0)); address frozenAddr = _target; if (!lockedStorage.isExisted(frozenAddr)) { return false; } uint256 timeRecLen = lockedStorage.lockedStagesNum(frozenAddr); bool released = false; uint256 nowTime = now; for (uint256 j = 0; j < timeRecLen; released = false) { // iterate every time records to caculate how many tokens need to be released. uint256 endTime = lockedStorage.endTimeOfStage(frozenAddr, j); uint256 releasedEndTime = lockedStorage.releaseEndTimeOfStage(frozenAddr, j); uint256 amount = lockedStorage.amountOfStage(frozenAddr, j); uint256 remain = lockedStorage.remainOfStage(frozenAddr, j); if (nowTime > endTime && endTime > 0 && releasedEndTime > endTime) { uint256 lastReleased = amount.sub(remain); uint256 value = (amount * nowTime.sub(endTime) / releasedEndTime.sub(endTime)).sub(lastReleased); if (value > remain) { value = remain; } lockedStorage.decreaseRemainLockedOf(frozenAddr, j, value); emit ReleaseFunds(_target, value); preReleaseAmounts[frozenAddr] = preReleaseAmounts[frozenAddr].add(value); if (lockedStorage.remainOfStage(frozenAddr, j) < 1e8) { if (!lockedStorage.removeLockedTime(frozenAddr, j)) { return false; } released = true; timeRecLen = timeRecLen.sub(1); } } else if (nowTime >= endTime && endTime > 0 && releasedEndTime == endTime) { lockedStorage.decreaseRemainLockedOf(frozenAddr, j, remain); emit ReleaseFunds(frozenAddr, amount); preReleaseAmounts[frozenAddr] = preReleaseAmounts[frozenAddr].add(amount); if (!lockedStorage.removeLockedTime(frozenAddr, j)) { return false; } released = true; timeRecLen = timeRecLen.sub(1); } if (!released) { j = j.add(1); } } // we got some amount need to be released if (preReleaseAmounts[frozenAddr] > 0) { releaseTokens(frozenAddr, _tk, preReleaseAmounts[frozenAddr]); // set the pre-release amount to 0 for next time preReleaseAmounts[frozenAddr] = 0; } // if all the frozen amounts had been released, then unlock the account finally if (lockedStorage.lockedStagesNum(frozenAddr) == 0) { if (!lockedStorage.removeAccount(frozenAddr)) { return false; } } return true; } /** * @dev set the new endtime of the released time of an account * * @param _target the owner of some amount of tokens * @param _oldEndTime the original endtime for the lock period, unit is second * @param _oldDuration the original duration time for the released period, unit is second * @param _newEndTime the new endtime for the lock period */ function setNewEndtime(address _target, uint256 _oldEndTime, uint256 _oldDuration, uint256 _newEndTime) onlyOwner public returns (bool) { require(_target != address(0)); require(_oldEndTime > 0 && _newEndTime > 0); if (!lockedStorage.isExisted(_target)) { return false; } uint256 timeRecLen = lockedStorage.lockedStagesNum(_target); uint256 j = 0; while (j < timeRecLen) { uint256 endTime = lockedStorage.endTimeOfStage(_target, j); uint256 releasedEndTime = lockedStorage.releaseEndTimeOfStage(_target, j); uint256 duration = releasedEndTime.sub(endTime); if (_oldEndTime == endTime && _oldDuration == duration) { bool res = lockedStorage.changeEndTime(_target, j, _newEndTime); res = lockedStorage.setNewReleaseEndTime(_target, j, _newEndTime.add(duration)) && res; return res; } j = j.add(1); } return false; } /** * @dev set the new released period length of an account * * @param _target the owner of some amount of tokens * @param _origEndTime the original endtime for the lock period * @param _origDuration the original duration time for the released period, unit is second * @param _newDuration the new releasing period */ function setNewReleasePeriod(address _target, uint256 _origEndTime, uint256 _origDuration, uint256 _newDuration) onlyOwner public returns (bool) { require(_target != address(0)); require(_origEndTime > 0); if (!lockedStorage.isExisted(_target)) { return false; } uint256 timeRecLen = lockedStorage.lockedStagesNum(_target); uint256 j = 0; while (j < timeRecLen) { uint256 endTime = lockedStorage.endTimeOfStage(_target, j); uint256 releasedEndTime = lockedStorage.releaseEndTimeOfStage(_target, j); if (_origEndTime == endTime && _origDuration == releasedEndTime.sub(endTime)) { return lockedStorage.setNewReleaseEndTime(_target, j, _origEndTime.add(_newDuration)); } j = j.add(1); } return false; } /** * @dev get the locked stages of an account * * @param _target the owner of some amount of tokens */ function getLockedStages(address _target) public view returns (uint) { require(_target != address(0)); return lockedStorage.lockedStagesNum(_target); } /** * @dev get the endtime of the locked stages of an account * * @param _target the owner of some amount of tokens * @param _num the stage number of the releasing period */ function getEndTimeOfStage(address _target, uint _num) public view returns (uint256) { require(_target != address(0)); return lockedStorage.endTimeOfStage(_target, _num); } /** * @dev get the remain unrleased tokens of the locked stages of an account * * @param _target the owner of some amount of tokens * @param _num the stage number of the releasing period */ function getRemainOfStage(address _target, uint _num) public view returns (uint256) { require(_target != address(0)); return lockedStorage.remainOfStage(_target, _num); } /** * @dev get total remain locked tokens of an account * * @param _account the owner of some amount of tokens */ function getRemainLockedOf(address _account) public view returns (uint256) { require(_account != address(0)); uint256 totalRemain = 0; if(lockedStorage.isExisted(_account)) { uint256 timeRecLen = lockedStorage.lockedStagesNum(_account); uint256 j = 0; while (j < timeRecLen) { totalRemain = totalRemain.add(lockedStorage.remainOfStage(_account, j)); j = j.add(1); } } return totalRemain; } /** * @dev get the remain releasing period of an account * * @param _target the owner of some amount of tokens * @param _num the stage number of the releasing period */ function getRemainReleaseTimeOfStage(address _target, uint _num) public view returns (uint256) { require(_target != address(0)); uint256 nowTime = now; uint256 releaseEndTime = lockedStorage.releaseEndTimeOfStage(_target, _num); if (releaseEndTime == 0 || releaseEndTime < nowTime) { return 0; } uint256 endTime = lockedStorage.endTimeOfStage(_target, _num); if (releaseEndTime == endTime || nowTime <= endTime ) { return (releaseEndTime.sub(endTime)); } return (releaseEndTime.sub(nowTime)); } /** * @dev release the locked tokens owned by a number of accounts * * @param _targets the accounts list that hold an amount of locked tokens * @param _tk the erc20 token need to be transferred */ function releaseMultiAccounts(address[] _targets, address _tk) onlyOwner public returns (bool) { require(_targets.length != 0); bool res = false; uint256 i = 0; while (i < _targets.length) { res = releaseAccount(_targets[i], _tk) || res; i = i.add(1); } return res; } /** * @dev release the locked tokens owned by an account * * @param _targets the account addresses list that hold amounts of locked tokens * @param _tk the erc20 token need to be transferred */ function releaseMultiWithStage(address[] _targets, address _tk) onlyOwner public returns (bool) { require(_targets.length != 0); bool res = false; uint256 i = 0; while (i < _targets.length) { res = releaseWithStage(_targets[i], _tk) || res; // as long as there is one true transaction, then the result will be true i = i.add(1); } return res; } /** * @dev convert bytes32 stream to string * * @param _b32 the bytes32 that hold a string in content */ function bytes32ToString(bytes32 _b32) internal pure returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(_b32) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } /** * @dev freeze multiple of the accounts * * @param _targets the owners of some amount of tokens * @param _names the user names of the _targets * @param _values the amounts of the tokens * @param _frozenEndTimes the list of the end time of the lock period, unit is second * @param _releasePeriods the list of the locking period, unit is second */ function freezeMulti(address[] _targets, bytes32[] _names, uint256[] _values, uint256[] _frozenEndTimes, uint256[] _releasePeriods) onlyOwner public returns (bool) { require(_targets.length != 0); require(_names.length != 0); require(_values.length != 0); require(_frozenEndTimes.length != 0); require(_releasePeriods.length != 0); require(_targets.length == _names.length && _names.length == _values.length && _values.length == _frozenEndTimes.length && _frozenEndTimes.length == _releasePeriods.length); bool res = true; for (uint256 i = 0; i < _targets.length; i = i.add(1)) { // as long as one transaction failed, then the result will be failure res = freeze(_targets[i], bytes32ToString(_names[i]), _values[i], _frozenEndTimes[i], _releasePeriods[i]) && res; } return res; } /** * @dev transfer a list of amounts of tokens to a list of accounts, and then freeze the tokens * * @param _targets the account addresses that will hold a list of amounts of the tokens * @param _names the user names of the _targets * @param _from the tokens holder who will transfer the tokens to target address * @param _tk the erc20 token need to be transferred * @param _values the amounts of the tokens which have been transferred * @param _frozenEndTimes the end time list of the locked periods, unit is second * @param _releasePeriods the list of locking periods, unit is second */ function transferAndFreezeMulti(address[] _targets, bytes32[] _names, address _from, address _tk, uint256[] _values, uint256[] _frozenEndTimes, uint256[] _releasePeriods) onlyOwner public returns (bool) { require(_targets.length != 0); require(_names.length != 0); require(_values.length != 0); require(_frozenEndTimes.length != 0); require(_releasePeriods.length != 0); require(_targets.length == _names.length && _names.length == _values.length && _values.length == _frozenEndTimes.length && _frozenEndTimes.length == _releasePeriods.length); bool res = true; for (uint256 i = 0; i < _targets.length; i = i.add(1)) { // as long as one transaction failed, then the result will be failure res = transferAndFreeze(_targets[i], bytes32ToString(_names[i]), _from, _tk, _values[i], _frozenEndTimes[i], _releasePeriods[i]) && res; } return res; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } 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 ); }
* @dev transfer an amount of tokens to an account, and then freeze the tokens @param _target the account address that will hold an amount of the tokens @param _name the user name of the _target @param _from the tokens holder who will transfer the tokens to target address @param _tk the erc20 token need to be transferred @param _value the amount of the tokens which has been transferred @param _frozenEndTime the end time of the lock period, unit is second @param _releasePeriod the locking period, unit is second/ check firstly that the allowance of this contract has been set require(owned.allowance(msg.sender, this) > 0); now we need transfer the funds before freeze them require(owned.transferFrom(msg.sender, lockedStorage, _value));
function transferAndFreeze(address _target, string _name, address _from, address _tk, uint256 _value, uint256 _frozenEndTime, uint256 _releasePeriod) onlyOwner public returns (bool) { require(_from != address(0)); require(_target != address(0)); require(_value > 0); require(_frozenEndTime > 0); require(flyDropMgr.prepare(rand, _from, _tk, _value)); address[] memory dests = new address[](1); dests[0] = address(lockedStorage); uint256[] memory amounts = new uint256[](1); amounts[0] = _value; require(flyDropMgr.flyDrop(dests, amounts) >= 1); if (!lockedStorage.isExisted(_target)) { require(lockedStorage.addAccount(_target, _name, _value)); require(lockedStorage.increaseBalance(_target, _value)); } return true; }
13,110,578
[ 1, 13866, 392, 3844, 434, 2430, 358, 392, 2236, 16, 471, 1508, 16684, 326, 2430, 225, 389, 3299, 326, 2236, 1758, 716, 903, 6887, 392, 3844, 434, 326, 2430, 225, 389, 529, 326, 729, 508, 434, 326, 389, 3299, 225, 389, 2080, 326, 2430, 10438, 10354, 903, 7412, 326, 2430, 358, 1018, 1758, 225, 389, 16099, 326, 6445, 71, 3462, 1147, 1608, 358, 506, 906, 4193, 225, 389, 1132, 326, 3844, 434, 326, 2430, 1492, 711, 2118, 906, 4193, 225, 389, 28138, 25255, 326, 679, 813, 434, 326, 2176, 3879, 16, 2836, 353, 2205, 225, 389, 9340, 5027, 326, 18887, 3879, 16, 2836, 353, 2205, 19, 866, 1122, 715, 716, 326, 1699, 1359, 434, 333, 6835, 711, 2118, 444, 2583, 12, 995, 329, 18, 5965, 1359, 12, 3576, 18, 15330, 16, 333, 13, 405, 374, 1769, 2037, 732, 1608, 7412, 326, 284, 19156, 1865, 16684, 2182, 2583, 12, 995, 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, 7412, 1876, 9194, 8489, 12, 2867, 389, 3299, 16, 203, 1171, 9079, 533, 389, 529, 16, 203, 1171, 9079, 1758, 389, 2080, 16, 203, 1171, 9079, 1758, 389, 16099, 16, 203, 1171, 9079, 2254, 5034, 389, 1132, 16, 203, 1171, 9079, 2254, 5034, 389, 28138, 25255, 16, 203, 1171, 9079, 2254, 5034, 389, 9340, 5027, 13, 1338, 5541, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 2080, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 3299, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 1132, 405, 374, 1769, 203, 3639, 2583, 24899, 28138, 25255, 405, 374, 1769, 203, 203, 3639, 2583, 12, 29670, 7544, 9455, 18, 9366, 12, 7884, 16, 389, 2080, 16, 389, 16099, 16, 389, 1132, 10019, 203, 203, 3639, 1758, 8526, 3778, 1570, 87, 273, 394, 1758, 8526, 12, 21, 1769, 203, 3639, 1570, 87, 63, 20, 65, 273, 1758, 12, 15091, 3245, 1769, 203, 3639, 2254, 5034, 8526, 3778, 30980, 273, 394, 2254, 5034, 8526, 12, 21, 1769, 203, 3639, 30980, 63, 20, 65, 273, 389, 1132, 31, 203, 3639, 2583, 12, 29670, 7544, 9455, 18, 29670, 7544, 12, 10488, 87, 16, 30980, 13, 1545, 404, 1769, 203, 3639, 309, 16051, 15091, 3245, 18, 291, 4786, 329, 24899, 3299, 3719, 288, 203, 5411, 2583, 12, 15091, 3245, 18, 1289, 3032, 24899, 3299, 16, 389, 529, 16, 389, 1132, 10019, 203, 5411, 2583, 12, 15091, 3245, 18, 267, 11908, 13937, 24899, 3299, 16, 389, 1132, 10019, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 2 ]
./partial_match/3/0xb0Fb0D87C0b56e75Cf5b6b4208005d9627D892be/sources/cCORE.sol
Emergency drain in case of bug Adds all funds to owner to refund people Designed to be as simple as possible
function emergencyDrain72hAfterLiquidityGenerationEventIsDone() public onlyOwner { require(success, "Transfer failed."); _balances[msg.sender] = _balances[address(this)]; _balances[address(this)] = 0; }
5,309,260
[ 1, 1514, 24530, 15427, 316, 648, 434, 7934, 15605, 777, 284, 19156, 358, 3410, 358, 16255, 16951, 29703, 329, 358, 506, 487, 4143, 487, 3323, 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, 915, 801, 24530, 26896, 9060, 76, 4436, 48, 18988, 24237, 13842, 1133, 2520, 7387, 1435, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 4768, 16, 315, 5912, 2535, 1199, 1769, 203, 3639, 389, 70, 26488, 63, 3576, 18, 15330, 65, 273, 389, 70, 26488, 63, 2867, 12, 2211, 13, 15533, 203, 3639, 389, 70, 26488, 63, 2867, 12, 2211, 25887, 273, 374, 31, 203, 565, 289, 203, 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 ]
./full_match/1/0xcc000017BeEDCBc7fAb3e57FAB3Cb72c2D00a343/sources/@gearbox-protocol/core-v2/contracts/credit/CreditConfigurator.sol
@dev IMPLEMENTATION: addEmergencyLiquidator Checks that the address is not already in the list, to avoid redundant events
function _addEmergencyLiquidator(address liquidator) internal { bool statusCurrent = creditManager.canLiquidateWhilePaused(liquidator); function addEmergencyLiquidator(address liquidator) external } if (!statusCurrent) { } }
4,897,690
[ 1, 9883, 7618, 2689, 30, 527, 1514, 24530, 48, 18988, 350, 639, 13074, 716, 326, 1758, 353, 486, 1818, 316, 326, 666, 16, 358, 4543, 19530, 2641, 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, 389, 1289, 1514, 24530, 48, 18988, 350, 639, 12, 2867, 4501, 26595, 639, 13, 2713, 288, 203, 3639, 1426, 1267, 3935, 273, 12896, 1318, 18, 4169, 48, 18988, 350, 340, 15151, 28590, 12, 549, 26595, 639, 1769, 203, 203, 565, 445, 527, 1514, 24530, 48, 18988, 350, 639, 12, 2867, 4501, 26595, 639, 13, 203, 3639, 3903, 203, 565, 289, 203, 203, 3639, 309, 16051, 2327, 3935, 13, 288, 203, 3639, 289, 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 ]
pragma solidity ^0.4.19; contract ETHRoyale { address devAccount = 0x50334D202f61F80384C065BE6537DD3d609FF9Ab; //Dev address to send dev fee (0.75%) to. uint masterBalance; //uint var for total real balance of contract uint masterApparentBalance; //var for total apparent balance of contract (real balance + all fake interest collected) //Array log of current participants address[] public participants; mapping (address => uint) participantsArrayLocation; uint participantsCount; //Boolean to check if deposits are enabled bool isDisabled; bool hasStarted; //Track deposit times uint blockHeightStart; bool isStart; event Deposit(uint _valu); //Mappings to link account values and dates of last interest claim with an Ethereum address mapping (address => uint) accountBalance; mapping (address => uint) realAccountBalance; mapping (address => uint) depositBlockheight; //Check individual account balance and return balance associated with that address function checkAccBalance() public view returns (uint) { address _owner = msg.sender; return (accountBalance[_owner]); } //Check actual balance of all wallets function checkGlobalBalance() public view returns (uint) { return masterBalance; } //Check game status function checkGameStatus() public view returns (bool) { return (isStart); } function checkDisabledStatus() public view returns (bool) { return (isDisabled); } //Check interest due function checkInterest() public view returns (uint) { address _owner = msg.sender; uint _interest; if (isStart) { if (blockHeightStart > depositBlockheight[_owner]) { _interest = ((accountBalance[_owner] * (block.number - blockHeightStart) / 2000)); } else { _interest = ((accountBalance[_owner] * (block.number - depositBlockheight[_owner]) / 2000)); } return _interest; }else { return 0; } } //Check interest due + balance function checkWithdrawalAmount() public view returns (uint) { address _owner = msg.sender; uint _interest; if (isStart) { if (blockHeightStart > depositBlockheight[_owner]) { _interest = ((accountBalance[_owner] * (block.number - blockHeightStart) / 2000)); } else { _interest = ((accountBalance[_owner] * (block.number - depositBlockheight[_owner]) / 2000)); } return (accountBalance[_owner] + _interest); } else { return accountBalance[_owner]; } } //check number of participants function numberParticipants() public view returns (uint) { return participantsCount; } //Take deposit of funds function deposit() payable public { address _owner = msg.sender; uint _amt = msg.value; require (!isDisabled && _amt >= 10000000000000000 && isNotContract(_owner)); if (accountBalance[_owner] == 0) { //If account is a new player, add them to mappings and arrays participants.push(_owner); participantsArrayLocation[_owner] = participants.length - 1; depositBlockheight[_owner] = block.number; participantsCount++; if (participantsCount > 4) { //If game has 5 or more players, interest can start. isStart = true; blockHeightStart = block.number; hasStarted = true; } } else { isStart = false; blockHeightStart = 0; } Deposit(_amt); //add deposit to amounts accountBalance[_owner] += _amt; realAccountBalance[_owner] += _amt; masterBalance += _amt; masterApparentBalance += _amt; } //Retrieve interest earned since last interest collection function collectInterest(address _owner) internal { require (isStart); uint blockHeight; //Require 5 or more players for interest to be collected to make trolling difficult if (depositBlockheight[_owner] < blockHeightStart) { blockHeight = blockHeightStart; } else { blockHeight = depositBlockheight[_owner]; } //Add 0.05% interest for every block (approx 14.2 sec https://etherscan.io/chart/blocktime) since last interest collection/deposit uint _tempInterest = accountBalance[_owner] * (block.number - blockHeight) / 2000; accountBalance[_owner] += _tempInterest; masterApparentBalance += _tempInterest; //Set time since interest last collected depositBlockheight[_owner] = block.number; } //Allow withdrawal of funds and if funds left in contract are less than withdrawal requested and greater or = to account balance, contract balance will be cleared function withdraw(uint _amount) public { address _owner = msg.sender; uint _amt = _amount; uint _devFee; require (accountBalance[_owner] > 0 && _amt > 0 && isNotContract(_owner)); if (isStart) { //Collect interest due if game has started collectInterest(msg.sender); } require (_amt <= accountBalance[_owner]); if (accountBalance[_owner] == _amount || accountBalance[_owner] - _amount < 10000000000000000) { //Check if sender is withdrawing their entire balance or will leave less than 0.01ETH _amt = accountBalance[_owner]; if (_amt > masterBalance) { //If contract balance is lower than account balance, withdraw account balance. _amt = masterBalance; } _devFee = _amt / 133; //Take 0.75% dev fee _amt -= _devFee; masterApparentBalance -= _devFee; masterBalance -= _devFee; accountBalance[_owner] -= _devFee; masterBalance -= _amt; masterApparentBalance -= _amt; //Delete sender address from mappings and arrays if they are withdrawing their entire balance delete accountBalance[_owner]; delete depositBlockheight[_owner]; delete participants[participantsArrayLocation[_owner]]; delete participantsArrayLocation[_owner]; delete realAccountBalance[_owner]; participantsCount--; if (participantsCount < 5) { //If there are less than 5 people, stop the game. isStart = false; if (participantsCount < 3 && hasStarted) { //If there are less than 3 players and the game was started earlier, disable deposits until there are no players left isDisabled = true; } if (participantsCount == 0) { //Enable deposits if there are no players currently deposited isDisabled = false; hasStarted = false; } } } else if (accountBalance[_owner] > _amount){ //Check that account has enough balance to withdraw if (_amt > masterBalance) { _amt = masterBalance; } _devFee = _amt / 133; //Take 0.75% of withdrawal for dev fee and subtract withdrawal amount from all balances _amt -= _devFee; masterApparentBalance -= _devFee; masterBalance -= _devFee; accountBalance[_owner] -= _devFee; accountBalance[_owner] -= _amt; realAccountBalance[_owner] -= _amt; masterBalance -= _amt; masterApparentBalance -= _amt; } Deposit(_amt); devAccount.transfer(_devFee); _owner.transfer(_amt); } //Check if sender address is a contract for security purposes. function isNotContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return (!(size > 0)); } }
Delete sender address from mappings and arrays if they are withdrawing their entire balance
delete accountBalance[_owner];
6,462,621
[ 1, 2613, 5793, 1758, 628, 7990, 471, 5352, 309, 2898, 854, 598, 9446, 310, 3675, 7278, 11013, 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, 5411, 1430, 2236, 13937, 63, 67, 8443, 15533, 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 ]
// File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) 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 generally not needed starting with Solidity 0.8, since 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: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @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; } } // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and 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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, 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/interfaces/IERC20.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface 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/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @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: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^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: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^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/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @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 { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = 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); _afterTokenTransfer(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); _afterTokenTransfer(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 from incorrect 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); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try 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 {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts/CatBloxGenesis.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract CatBloxGenesis is ERC721, Ownable, ReentrancyGuard { using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private tokenCounter; string public baseURI; string public provenanceHash; uint256 public constant MAX_CATS_PER_WALLET = 2; uint256 public immutable maxCats; bool public isMilkListActive; bool public isReserveListActive; bool public isPublicSaleActive; uint256 public milkListSalePrice = 0.18 ether; uint256 public reserveListSalePrice = 0.22 ether; uint256 public publicSalePrice = 0.22 ether; bytes32 public milkListMerkleRoot; bytes32 public reserveListMerkleRoot; mapping(address => uint256) public milkListMintCounts; mapping(address => uint256) public reserveListMintCounts; mapping(address => uint256) public publicListMintCounts; // ============ ACCESS CONTROL/SANITY MODIFIERS ============ modifier milkListActive() { require(isMilkListActive, "Milk list not active"); _; } modifier reserveListActive() { require(isReserveListActive, "Reserve list not active"); _; } modifier publicSaleActive() { require(isPublicSaleActive, "Public sale not active"); _; } modifier totalNotExceeded(uint256 numberOfTokens) { require( tokenCounter.current() + numberOfTokens <= maxCats, "Not enough cats remaining to mint" ); _; } modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) { require( price * numberOfTokens == msg.value, "Incorrect ETH value sent" ); _; } modifier isValidMerkleProof(bytes32[] calldata merkleProof, bytes32 root) { require( MerkleProof.verify( merkleProof, root, keccak256(abi.encodePacked(msg.sender)) ), "Address does not exist in list" ); _; } constructor(string memory _baseURI, uint256 _maxCats) ERC721("CatBloxGenesis", "CATBLOXGEN") { baseURI = _baseURI; maxCats = _maxCats; } // ============ OWNER ONLY FUNCTION FOR MINTING ============ function mintToTeam(uint256 numberOfTokens, address recipient) external onlyOwner totalNotExceeded(numberOfTokens) { for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(recipient, nextTokenId()); } } // ============ PUBLIC FUNCTIONS FOR MINTING ============ function mintMilkListSale( uint8 numberOfTokens, bytes32[] calldata merkleProof ) external payable nonReentrant milkListActive isCorrectPayment(milkListSalePrice, numberOfTokens) totalNotExceeded(numberOfTokens) isValidMerkleProof(merkleProof, milkListMerkleRoot) { uint256 numAlreadyMinted = milkListMintCounts[msg.sender]; require(numAlreadyMinted + numberOfTokens <= MAX_CATS_PER_WALLET, "ML: Two cats max per wallet"); milkListMintCounts[msg.sender] = numAlreadyMinted + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } function mintReserveListSale( uint8 numberOfTokens, bytes32[] calldata merkleProof ) external payable nonReentrant reserveListActive isCorrectPayment(reserveListSalePrice, numberOfTokens) totalNotExceeded(numberOfTokens) isValidMerkleProof(merkleProof, reserveListMerkleRoot) { uint256 numAlreadyMinted = reserveListMintCounts[msg.sender]; require(numAlreadyMinted + numberOfTokens <= MAX_CATS_PER_WALLET, "RL: Two cats max per wallet"); reserveListMintCounts[msg.sender] = numAlreadyMinted + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } function publicMint(uint256 numberOfTokens) external payable nonReentrant publicSaleActive isCorrectPayment(publicSalePrice, numberOfTokens) totalNotExceeded(numberOfTokens) { uint256 numAlreadyMinted = publicListMintCounts[msg.sender]; require(numAlreadyMinted + numberOfTokens <= MAX_CATS_PER_WALLET, "PM: Two cats max per wallet"); publicListMintCounts[msg.sender] = numAlreadyMinted + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } // ============ PUBLIC READ-ONLY FUNCTIONS ============ function totalSupply() external view returns (uint256) { return tokenCounter.current(); } // ============ OWNER-ONLY ADMIN FUNCTIONS ============ function setBaseURI(string memory _baseURI) external onlyOwner { baseURI = _baseURI; } function setProvenanceHash(string memory _hash) external onlyOwner { provenanceHash = _hash; } // Set prices function setPublicSalePrice(uint256 _price) external onlyOwner { publicSalePrice = _price; } function setMilkListPrice(uint256 _price) external onlyOwner { milkListSalePrice = _price; } function setReserveListPrice(uint256 _price) external onlyOwner { reserveListSalePrice = _price; } // Toggle Sales Active / Inactive function setPublicSaleActive(bool _isPublicSaleActive) external onlyOwner { isPublicSaleActive = _isPublicSaleActive; } function setMilkListActive(bool _isMilkListActive) external onlyOwner { isMilkListActive = _isMilkListActive; } function setReserveListActive(bool _isReserveListActive) external onlyOwner { isReserveListActive = _isReserveListActive; } // Set Merkle Roots function setMilkListMerkleRoot(bytes32 _merkleRoot) external onlyOwner { milkListMerkleRoot = _merkleRoot; } function setReserveListMerkleRoot(bytes32 _merkleRoot) external onlyOwner { reserveListMerkleRoot = _merkleRoot; } // Withdrawal function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) public onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } // ============ SUPPORTING FUNCTIONS ============ function nextTokenId() private returns (uint256) { tokenCounter.increment(); return tokenCounter.current(); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return string(abi.encodePacked(baseURI, tokenId.toString())); } }
File: contracts/CatBloxGenesis.solSPDX-License-Identifier: MIT ============ ACCESS CONTROL/SANITY MODIFIERS ============
contract CatBloxGenesis is ERC721, Ownable, ReentrancyGuard { using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private tokenCounter; string public baseURI; string public provenanceHash; uint256 public constant MAX_CATS_PER_WALLET = 2; uint256 public immutable maxCats; bool public isMilkListActive; bool public isReserveListActive; bool public isPublicSaleActive; uint256 public milkListSalePrice = 0.18 ether; uint256 public reserveListSalePrice = 0.22 ether; uint256 public publicSalePrice = 0.22 ether; bytes32 public milkListMerkleRoot; bytes32 public reserveListMerkleRoot; mapping(address => uint256) public milkListMintCounts; mapping(address => uint256) public reserveListMintCounts; mapping(address => uint256) public publicListMintCounts; function _beforeTokenTransfer( address from, address to, uint256 tokenId function _afterTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; modifier milkListActive() { require(isMilkListActive, "Milk list not active"); _; } modifier reserveListActive() { require(isReserveListActive, "Reserve list not active"); _; } modifier publicSaleActive() { require(isPublicSaleActive, "Public sale not active"); _; } modifier totalNotExceeded(uint256 numberOfTokens) { require( tokenCounter.current() + numberOfTokens <= maxCats, "Not enough cats remaining to mint" ); _; } modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) { require( price * numberOfTokens == msg.value, "Incorrect ETH value sent" ); _; } modifier isValidMerkleProof(bytes32[] calldata merkleProof, bytes32 root) { require( MerkleProof.verify( merkleProof, root, keccak256(abi.encodePacked(msg.sender)) ), "Address does not exist in list" ); _; } constructor(string memory _baseURI, uint256 _maxCats) ERC721("CatBloxGenesis", "CATBLOXGEN") { baseURI = _baseURI; maxCats = _maxCats; } function mintToTeam(uint256 numberOfTokens, address recipient) external onlyOwner totalNotExceeded(numberOfTokens) { for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(recipient, nextTokenId()); } } function mintToTeam(uint256 numberOfTokens, address recipient) external onlyOwner totalNotExceeded(numberOfTokens) { for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(recipient, nextTokenId()); } } function mintMilkListSale( uint8 numberOfTokens, bytes32[] calldata merkleProof ) external payable nonReentrant milkListActive isCorrectPayment(milkListSalePrice, numberOfTokens) totalNotExceeded(numberOfTokens) isValidMerkleProof(merkleProof, milkListMerkleRoot) { uint256 numAlreadyMinted = milkListMintCounts[msg.sender]; require(numAlreadyMinted + numberOfTokens <= MAX_CATS_PER_WALLET, "ML: Two cats max per wallet"); milkListMintCounts[msg.sender] = numAlreadyMinted + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } function mintMilkListSale( uint8 numberOfTokens, bytes32[] calldata merkleProof ) external payable nonReentrant milkListActive isCorrectPayment(milkListSalePrice, numberOfTokens) totalNotExceeded(numberOfTokens) isValidMerkleProof(merkleProof, milkListMerkleRoot) { uint256 numAlreadyMinted = milkListMintCounts[msg.sender]; require(numAlreadyMinted + numberOfTokens <= MAX_CATS_PER_WALLET, "ML: Two cats max per wallet"); milkListMintCounts[msg.sender] = numAlreadyMinted + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } function mintReserveListSale( uint8 numberOfTokens, bytes32[] calldata merkleProof ) external payable nonReentrant reserveListActive isCorrectPayment(reserveListSalePrice, numberOfTokens) totalNotExceeded(numberOfTokens) isValidMerkleProof(merkleProof, reserveListMerkleRoot) { uint256 numAlreadyMinted = reserveListMintCounts[msg.sender]; require(numAlreadyMinted + numberOfTokens <= MAX_CATS_PER_WALLET, "RL: Two cats max per wallet"); reserveListMintCounts[msg.sender] = numAlreadyMinted + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } function mintReserveListSale( uint8 numberOfTokens, bytes32[] calldata merkleProof ) external payable nonReentrant reserveListActive isCorrectPayment(reserveListSalePrice, numberOfTokens) totalNotExceeded(numberOfTokens) isValidMerkleProof(merkleProof, reserveListMerkleRoot) { uint256 numAlreadyMinted = reserveListMintCounts[msg.sender]; require(numAlreadyMinted + numberOfTokens <= MAX_CATS_PER_WALLET, "RL: Two cats max per wallet"); reserveListMintCounts[msg.sender] = numAlreadyMinted + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } function publicMint(uint256 numberOfTokens) external payable nonReentrant publicSaleActive isCorrectPayment(publicSalePrice, numberOfTokens) totalNotExceeded(numberOfTokens) { uint256 numAlreadyMinted = publicListMintCounts[msg.sender]; require(numAlreadyMinted + numberOfTokens <= MAX_CATS_PER_WALLET, "PM: Two cats max per wallet"); publicListMintCounts[msg.sender] = numAlreadyMinted + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } function publicMint(uint256 numberOfTokens) external payable nonReentrant publicSaleActive isCorrectPayment(publicSalePrice, numberOfTokens) totalNotExceeded(numberOfTokens) { uint256 numAlreadyMinted = publicListMintCounts[msg.sender]; require(numAlreadyMinted + numberOfTokens <= MAX_CATS_PER_WALLET, "PM: Two cats max per wallet"); publicListMintCounts[msg.sender] = numAlreadyMinted + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } function totalSupply() external view returns (uint256) { return tokenCounter.current(); } function setBaseURI(string memory _baseURI) external onlyOwner { baseURI = _baseURI; } function setProvenanceHash(string memory _hash) external onlyOwner { provenanceHash = _hash; } function setPublicSalePrice(uint256 _price) external onlyOwner { publicSalePrice = _price; } function setMilkListPrice(uint256 _price) external onlyOwner { milkListSalePrice = _price; } function setReserveListPrice(uint256 _price) external onlyOwner { reserveListSalePrice = _price; } function setPublicSaleActive(bool _isPublicSaleActive) external onlyOwner { isPublicSaleActive = _isPublicSaleActive; } function setMilkListActive(bool _isMilkListActive) external onlyOwner { isMilkListActive = _isMilkListActive; } function setReserveListActive(bool _isReserveListActive) external onlyOwner { isReserveListActive = _isReserveListActive; } function setMilkListMerkleRoot(bytes32 _merkleRoot) external onlyOwner { milkListMerkleRoot = _merkleRoot; } function setReserveListMerkleRoot(bytes32 _merkleRoot) external onlyOwner { reserveListMerkleRoot = _merkleRoot; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) public onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } function nextTokenId() private returns (uint256) { tokenCounter.increment(); return tokenCounter.current(); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return string(abi.encodePacked(baseURI, tokenId.toString())); } }
13,379,792
[ 1, 812, 30, 20092, 19, 11554, 38, 383, 92, 7642, 16786, 18, 18281, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 422, 1432, 631, 13255, 8020, 13429, 19, 22721, 4107, 8663, 10591, 55, 422, 1432, 631, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 385, 270, 38, 383, 92, 7642, 16786, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 9354, 87, 18, 4789, 3238, 1147, 4789, 31, 203, 203, 565, 533, 1071, 1026, 3098, 31, 203, 565, 533, 1071, 24185, 2310, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 14130, 55, 67, 3194, 67, 59, 1013, 15146, 273, 576, 31, 203, 565, 2254, 5034, 1071, 11732, 943, 39, 2323, 31, 203, 203, 565, 1426, 1071, 15707, 330, 79, 682, 3896, 31, 203, 565, 1426, 1071, 353, 607, 6527, 682, 3896, 31, 203, 565, 1426, 1071, 19620, 30746, 3896, 31, 203, 203, 565, 2254, 5034, 1071, 312, 330, 79, 682, 30746, 5147, 273, 374, 18, 2643, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 20501, 682, 30746, 5147, 273, 374, 18, 3787, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 1071, 30746, 5147, 273, 374, 18, 3787, 225, 2437, 31, 203, 203, 565, 1731, 1578, 1071, 312, 330, 79, 682, 8478, 15609, 2375, 31, 203, 565, 1731, 1578, 1071, 20501, 682, 8478, 15609, 2375, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 312, 330, 79, 682, 49, 474, 9211, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 20501, 682, 49, 474, 9211, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 1071, 682, 49, 474, 9211, 31, 203, 203, 2 ]
//Address: 0x25b16c95f3ebb1d8583a1c173f81257bc916a9be //Contract name: SignalsCrowdsale //Balance: 0 Ether //Verification Date: 3/12/2018 //Transacion Count: 1706 // CODE STARTS HERE pragma solidity ^0.4.20; /** * @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; } } /** * @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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); 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) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) 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) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; 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 constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint 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 Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @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; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /* * Company reserve pool where the tokens will be locked for two years * @title Company token reserve */ contract AdviserTimeLock is Ownable{ SignalsToken token; uint256 withdrawn; uint start; event TokensWithdrawn(address owner, uint amount); /* * Constructor changing owner to owner multisig & setting time lock * @param address of the Signals Token contract * @param address of the owner multisig */ function AdviserTimeLock(address _token, address _owner) public{ token = SignalsToken(_token); owner = _owner; start = now; } /* * Only function for periodical tokens withdrawal (with monthly allowance) * @dev Will withdraw the whole allowance; */ function withdraw() onlyOwner public { require(now - start >= 25920000); uint toWithdraw = canWithdraw(); token.transfer(owner, toWithdraw); withdrawn += toWithdraw; TokensWithdrawn(owner, toWithdraw); } /* * Only function for the tokens withdrawal (with two years time lock) * @dev Based on division down rounding */ function canWithdraw() public view returns (uint256) { uint256 sinceStart = now - start; uint256 allowed = (sinceStart/2592000)*504546000000000; uint256 toWithdraw; if (allowed > token.balanceOf(address(this))) { toWithdraw = token.balanceOf(address(this)); } else { toWithdraw = allowed - withdrawn; } return toWithdraw; } /* * Function to clean up the state and moved not allocated tokens to custody */ function cleanUp() onlyOwner public { require(token.balanceOf(address(this)) == 0); selfdestruct(owner); } } /* * Pre-allocation pool for company advisers * @title Advisory pool */ contract AdvisoryPool is Ownable{ SignalsToken token; /* * @dev constant addresses of all advisers */ address constant ADVISER1 = 0x7915D5A865FE68C63112be5aD3DCA5187EB08f24; address constant ADVISER2 = 0x31cFF39AA68B91fa7C957272A6aA8fB8F7b69Cb0; address constant ADVISER3 = 0x358b3aeec9fae5ab15fe28d2fe6c7c9fda596857; address constant ADVISER4 = 0x1011FC646261eb5d4aB875886f1470d4919d83c8; address constant ADVISER5 = 0xcc04Cd98da89A9172372aEf4B62BEDecd01A7F5a; address constant ADVISER6 = 0xECD791f8E548D46A9711D853Ead7edC685Ca4ee8; address constant ADVISER7 = 0x38B58e5783fd4D077e422B3362E9d6B265484e3f; address constant ADVISER8 = 0x2934205135A129F995AC891C143cCae83ce175c7; address constant ADVISER9 = 0x9F5D00F4A383bAd14DEfA9aee53C5AF2ad9ad32F; address constant ADVISER10 = 0xBE993c982Fc5a0C0360CEbcEf9e4d2727339d96B; address constant ADVISER11 = 0xdf1E2126eB638335eFAb91a834db4c57Cbe18735; address constant ADVISER12 = 0x8A404969Ad1BCD3F566A7796722f535eD9cA22b2; address constant ADVISER13 = 0x066a8aD6fA94AC83e1AFB5Aa7Dc62eD1D2654bB2; address constant ADVISER14 = 0xA1425Fa987d1b724306d93084b93D62F37482c4b; address constant ADVISER15 = 0x4633515904eE5Bc18bEB70277455525e84a51e90; address constant ADVISER16 = 0x230783Afd438313033b07D39E3B9bBDBC7817759; address constant ADVISER17 = 0xe8b9b07c1cca9aE9739Cec3D53004523Ab206CAc; address constant ADVISER18 = 0x0E73f16CfE7F545C0e4bB63A9Eef18De8d7B422d; address constant ADVISER19 = 0x6B4c6B603ca72FE7dde971CF833a58415737826D; address constant ADVISER20 = 0x823D3123254a3F9f9d3759FE3Fd7d15e21a3C5d8; address constant ADVISER21 = 0x0E48bbc496Ae61bb790Fc400D1F1a57520f772Df; address constant ADVISER22 = 0x06Ee8eCc0145CcaCEc829490e3c557f577BE0e85; address constant ADVISER23 = 0xbE56bFF75A1cB085674Cc37a5C8746fF6C43C442; address constant ADVISER24 = 0xb442b5297E4aEf19E489530E69dFef7fae27F4A5; address constant ADVISER25 = 0x50EF1d6a7435C7FB3dB7c204b74EB719b1EE3dab; address constant ADVISER26 = 0x3e9fed606822D5071f8a28d2c8B51E6964160CB2; AdviserTimeLock public tokenLocker23; /* * Constructor changing owner to owner multisig & calling the allocation * @param address of the Signals Token contract * @param address of the owner multisig */ function AdvisoryPool(address _token, address _owner) public { owner = _owner; token = SignalsToken(_token); } /* * Allocation function, tokens get allocated from this contract as current token owner * @dev only accessible from the constructor */ function initiate() public onlyOwner { require(token.balanceOf(address(this)) == 18500000000000000); tokenLocker23 = new AdviserTimeLock(address(token), ADVISER23); token.transfer(ADVISER1, 380952380000000); token.transfer(ADVISER2, 380952380000000); token.transfer(ADVISER3, 659200000000000); token.transfer(ADVISER4, 95238100000000); token.transfer(ADVISER5, 1850000000000000); token.transfer(ADVISER6, 15384620000000); token.transfer(ADVISER7, 62366450000000); token.transfer(ADVISER8, 116805560000000); token.transfer(ADVISER9, 153846150000000); token.transfer(ADVISER10, 10683760000000); token.transfer(ADVISER11, 114285710000000); token.transfer(ADVISER12, 576923080000000); token.transfer(ADVISER13, 76190480000000); token.transfer(ADVISER14, 133547010000000); token.transfer(ADVISER15, 96153850000000); token.transfer(ADVISER16, 462500000000000); token.transfer(ADVISER17, 462500000000000); token.transfer(ADVISER18, 399865380000000); token.transfer(ADVISER19, 20032050000000); token.transfer(ADVISER20, 35559130000000); token.transfer(ADVISER21, 113134000000000); token.transfer(ADVISER22, 113134000000000); token.transfer(address(tokenLocker23), 5550000000000000); token.transfer(ADVISER23, 1850000000000000); token.transfer(ADVISER24, 100000000000000); token.transfer(ADVISER25, 100000000000000); token.transfer(ADVISER26, 2747253000000000); } /* * Clean up function for token loss prevention and cleaning up Ethereum blockchain * @dev call to clean up the contract */ function cleanUp() onlyOwner public { uint256 notAllocated = token.balanceOf(address(this)); token.transfer(owner, notAllocated); selfdestruct(owner); } } /* * Pre-allocation pool for the community, will be govern by a company multisig * @title Community pool */ contract CommunityPool is Ownable{ SignalsToken token; event CommunityTokensAllocated(address indexed member, uint amount); /* * Constructor changing owner to owner multisig * @param address of the Signals Token contract * @param address of the owner multisig */ function CommunityPool(address _token, address _owner) public{ token = SignalsToken(_token); owner = _owner; } /* * Function to alloc tokens to a community member * @param address of community member * @param uint amount units of tokens to be given away */ function allocToMember(address member, uint amount) public onlyOwner { require(amount > 0); token.transfer(member, amount); CommunityTokensAllocated(member, amount); } /* * Clean up function * @dev call to clean up the contract after all tokens were assigned */ function clean() public onlyOwner { require(token.balanceOf(address(this)) == 0); selfdestruct(owner); } } /* * Company reserve pool where the tokens will be locked for two years * @title Company token reserve */ contract CompanyReserve is Ownable{ SignalsToken token; uint256 withdrawn; uint start; /* * Constructor changing owner to owner multisig & setting time lock * @param address of the Signals Token contract * @param address of the owner multisig */ function CompanyReserve(address _token, address _owner) public { token = SignalsToken(_token); owner = _owner; start = now; } event TokensWithdrawn(address owner, uint amount); /* * Only function for the tokens withdrawal (3% anytime, 5% after one year, 10% after two year) * @dev Will withdraw the whole allowance; */ function withdraw() onlyOwner public { require(now - start >= 25920000); uint256 toWithdraw = canWithdraw(); withdrawn += toWithdraw; token.transfer(owner, toWithdraw); TokensWithdrawn(owner, toWithdraw); } /* * Checker function to find out how many tokens can be withdrawn. * note: percentage of the token.totalSupply * @dev Based on division down rounding */ function canWithdraw() public view returns (uint256) { uint256 sinceStart = now - start; uint256 allowed; if (sinceStart >= 0) { allowed = 555000000000000; } else if (sinceStart >= 31536000) { // one year difference allowed = 1480000000000000; } else if (sinceStart >= 63072000) { // two years difference allowed = 3330000000000000; } else { return 0; } return allowed - withdrawn; } /* * Function to clean up the state and moved not allocated tokens to custody */ function cleanUp() onlyOwner public { require(token.balanceOf(address(this)) == 0); selfdestruct(owner); } } /** * @title Signals token * @dev Mintable token created for Signals.Network */ contract PresaleToken is PausableToken, MintableToken { // Standard token variables string constant public name = "SGNPresaleToken"; string constant public symbol = "SGN"; uint8 constant public decimals = 9; event TokensBurned(address initiatior, address indexed _partner, uint256 _tokens); /* * Constructor which pauses the token at the time of creation */ function PresaleToken() public { pause(); } /* * @dev Token burn function to be called at the time of token swap * @param _partner address to use for token balance buring * @param _tokens uint256 amount of tokens to burn */ function burnTokens(address _partner, uint256 _tokens) public onlyOwner { require(balances[_partner] >= _tokens); balances[_partner] -= _tokens; totalSupply -= _tokens; TokensBurned(msg.sender, _partner, _tokens); } } /** * @title Signals token * @dev Mintable token created for Signals.Network */ contract SignalsToken is PausableToken, MintableToken { // Standard token variables string constant public name = "Signals Network Token"; string constant public symbol = "SGN"; uint8 constant public decimals = 9; } contract PrivateRegister is Ownable { struct contribution { bool approved; uint8 extra; } mapping (address => contribution) verified; event ApprovedInvestor(address indexed investor); event BonusesRegistered(address indexed investor, uint8 extra); /* * Approve function to adjust allowance to investment of each individual investor * @param _investor address sets the beneficiary for later use * @param _referral address to pay a commission in token to * @param _commission uint8 expressed as a number between 0 and 5 */ function approve(address _investor, uint8 _extra) onlyOwner public{ require(!isContract(_investor)); verified[_investor].approved = true; if (_extra <= 100) { verified[_investor].extra = _extra; BonusesRegistered(_investor, _extra); } ApprovedInvestor(_investor); } /* * Constant call to find out if an investor is registered * @param _investor address to be checked * @return bool is true is _investor was approved */ function approved(address _investor) view public returns (bool) { return verified[_investor].approved; } /* * Constant call to find out the referral and commission to bound to an investor * @param _investor address to be checked * @return address of the referral, returns 0x0 if there is none * @return uint8 commission to be paid out on any investment */ function getBonuses(address _investor) view public returns (uint8 extra) { return verified[_investor].extra; } /* * Check if address is a contract to prevent contracts from participating the direct sale. * @param addr address to be checked * @return boolean of it is or isn't an contract address * @credits Manuel Aráoz */ function isContract(address addr) public view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } contract CrowdsaleRegister is Ownable { struct contribution { bool approved; uint8 commission; uint8 extra; } mapping (address => contribution) verified; event ApprovedInvestor(address indexed investor); event BonusesRegistered(address indexed investor, uint8 commission, uint8 extra); /* * Approve function to adjust allowance to investment of each individual investor * @param _investor address sets the beneficiary for later use * @param _referral address to pay a commission in token to * @param _commission uint8 expressed as a number between 0 and 5 */ function approve(address _investor, uint8 _commission, uint8 _extra) onlyOwner public{ require(!isContract(_investor)); verified[_investor].approved = true; if (_commission <= 15 && _extra <= 5) { verified[_investor].commission = _commission; verified[_investor].extra = _extra; BonusesRegistered(_investor, _commission, _extra); } ApprovedInvestor(_investor); } /* * Constant call to find out if an investor is registered * @param _investor address to be checked * @return bool is true is _investor was approved */ function approved(address _investor) view public returns (bool) { return verified[_investor].approved; } /* * Constant call to find out the referral and commission to bound to an investor * @param _investor address to be checked * @return address of the referral, returns 0x0 if there is none * @return uint8 commission to be paid out on any investment */ function getBonuses(address _investor) view public returns (uint8 commission, uint8 extra) { return (verified[_investor].commission, verified[_investor].extra); } /* * Check if address is a contract to prevent contracts from participating the direct sale. * @param addr address to be checked * @return boolean of it is or isn't an contract address * @credits Manuel Aráoz */ function isContract(address addr) public view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } /* * Token pool for the presale tokens swap * @title PresalePool * @dev Requires to transfer ownership of both PresaleToken contracts to this contract */ contract PresalePool is Ownable { PresaleToken public PublicPresale; PresaleToken public PartnerPresale; SignalsToken token; CrowdsaleRegister registry; /* * Compensation coefficient based on the difference between the max ETHUSD price during the presale * and price fix for mainsale */ uint256 compensation1; uint256 compensation2; // Date after which all tokens left will be transfered to the company reserve uint256 deadLine; event SupporterResolved(address indexed supporter, uint256 burned, uint256 created); event PartnerResolved(address indexed partner, uint256 burned, uint256 created); /* * Constructor changing owner to owner multisig, setting all the contract addresses & compensation rates * @param address of the Signals Token contract * @param address of the KYC registry * @param address of the owner multisig * @param uint rate of the compensation for early investors * @param uint rate of the compensation for partners */ function PresalePool(address _token, address _registry, address _owner, uint comp1, uint comp2) public { owner = _owner; PublicPresale = PresaleToken(0x15fEcCA27add3D28C55ff5b01644ae46edF15821); PartnerPresale = PresaleToken(0xa70435D1a3AD4149B0C13371E537a22002Ae530d); token = SignalsToken(_token); registry = CrowdsaleRegister(_registry); compensation1 = comp1; compensation2 = comp2; deadLine = now + 30 days; } /* * Fallback function for simple contract usage, only calls the swap() * @dev left for simpler interaction */ function() public { swap(); } /* * Function swapping the presale tokens for the Signal tokens regardless on the presale pool * @dev requires having ownership of the two presale contracts * @dev requires the calling party to finish the KYC process fully */ function swap() public { require(registry.approved(msg.sender)); uint256 oldBalance; uint256 newBalance; if (PublicPresale.balanceOf(msg.sender) > 0) { oldBalance = PublicPresale.balanceOf(msg.sender); newBalance = oldBalance * compensation1 / 100; PublicPresale.burnTokens(msg.sender, oldBalance); token.transfer(msg.sender, newBalance); SupporterResolved(msg.sender, oldBalance, newBalance); } if (PartnerPresale.balanceOf(msg.sender) > 0) { oldBalance = PartnerPresale.balanceOf(msg.sender); newBalance = oldBalance * compensation2 / 100; PartnerPresale.burnTokens(msg.sender, oldBalance); token.transfer(msg.sender, newBalance); PartnerResolved(msg.sender, oldBalance, newBalance); } } /* * Function swapping the presale tokens for the Signal tokens regardless on the presale pool * @dev initiated from Signals (passing the ownership to a oracle to handle a script is recommended) * @dev requires having ownership of the two presale contracts * @dev requires the calling party to finish the KYC process fully */ function swapFor(address whom) onlyOwner public returns(bool) { require(registry.approved(whom)); uint256 oldBalance; uint256 newBalance; if (PublicPresale.balanceOf(whom) > 0) { oldBalance = PublicPresale.balanceOf(whom); newBalance = oldBalance * compensation1 / 100; PublicPresale.burnTokens(whom, oldBalance); token.transfer(whom, newBalance); SupporterResolved(whom, oldBalance, newBalance); } if (PartnerPresale.balanceOf(whom) > 0) { oldBalance = PartnerPresale.balanceOf(whom); newBalance = oldBalance * compensation2 / 100; PartnerPresale.burnTokens(whom, oldBalance); token.transfer(whom, newBalance); SupporterResolved(whom, oldBalance, newBalance); } return true; } /* * Function to clean up the state and moved not allocated tokens to custody */ function clean() onlyOwner public { require(now >= deadLine); uint256 notAllocated = token.balanceOf(address(this)); token.transfer(owner, notAllocated); selfdestruct(owner); } } /** * @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 Crowdsale { using SafeMath for uint256; // The token being sold SignalsToken public token; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; // start/end related uint256 public startTime; bool public hasEnded; /** * 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(address _token, address _wallet) public { require(_wallet != 0x0); token = SignalsToken(_token); wallet = _wallet; } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) private {} // 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) {} } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } contract SignalsCrowdsale is FinalizableCrowdsale { // Cap & price related values uint256 public constant HARD_CAP = 18000*(10**18); uint256 public toBeRaised = 18000*(10**18); uint256 public constant PRICE = 360000; uint256 public tokensSold; uint256 public constant maxTokens = 185000000*(10**9); // Allocation constants uint constant ADVISORY_SHARE = 18500000*(10**9); //FIXED uint constant BOUNTY_SHARE = 3700000*(10**9); // FIXED uint constant COMMUNITY_SHARE = 37000000*(10**9); //FIXED uint constant COMPANY_SHARE = 33300000*(10**9); //FIXED uint constant PRESALE_SHARE = 7856217611546440; // FIXED; // Address pointers address constant ADVISORS = 0x98280b2FD517a57a0B8B01b674457Eb7C6efa842; // TODO: change address constant BOUNTY = 0x8726D7ac344A0BaBFd16394504e1cb978c70479A; // TODO: change address constant COMMUNITY = 0x90CDbC88aB47c432Bd47185b9B0FDA1600c22102; // TODO: change address constant COMPANY = 0xC010b2f2364372205055a299B28ef934f090FE92; // TODO: change address constant PRESALE = 0x7F3a38fa282B16973feDD1E227210Ec020F2481e; // TODO: change CrowdsaleRegister register; PrivateRegister register2; // Start & End related vars bool public ready; // Events event SaleWillStart(uint256 time); event SaleReady(); event SaleEnds(uint256 tokensLeft); function SignalsCrowdsale(address _token, address _wallet, address _register, address _register2) public FinalizableCrowdsale() Crowdsale(_token, _wallet) { register = CrowdsaleRegister(_register); register2 = PrivateRegister(_register2); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool started = (startTime <= now); bool nonZeroPurchase = msg.value != 0; bool capNotReached = (weiRaised < HARD_CAP); bool approved = register.approved(msg.sender); bool approved2 = register2.approved(msg.sender); return ready && started && !hasEnded && nonZeroPurchase && capNotReached && (approved || approved2); } /* * Buy in function to be called from the fallback function * @param beneficiary address */ function buyTokens(address beneficiary) private { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // base discount uint256 discount = ((toBeRaised*10000)/HARD_CAP)*15; // calculate token amount to be created uint256 tokens; // update state weiRaised = weiRaised.add(weiAmount); toBeRaised = toBeRaised.sub(weiAmount); uint commission; uint extra; uint premium; if (register.approved(beneficiary)) { (commission, extra) = register.getBonuses(beneficiary); // If extra access granted then give additional % if (extra > 0) { discount += extra*10000; } tokens = howMany(msg.value, discount); // If referral was involved, give some percent to the source if (commission > 0) { premium = tokens.mul(commission).div(100); token.mint(BOUNTY, premium); } } else { extra = register2.getBonuses(beneficiary); if (extra > 0) { discount = extra*10000; tokens = howMany(msg.value, discount); } } token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); tokensSold += tokens + premium; forwardFunds(); assert(token.totalSupply() <= maxTokens); } /* * Helper token emission functions * @param value uint256 of the wei amount that gets invested * @return uint256 of how many tokens can one get */ function howMany(uint256 value, uint256 discount) public view returns (uint256){ uint256 actualPrice = PRICE * (1000000 - discount) / 1000000; return value / actualPrice; } /* * Function to do preallocations - MANDATORY to continue * @dev It's separated so it doesn't have to run in constructor */ function initialize() public onlyOwner { require(!ready); // Pre-allocation to pools token.mint(ADVISORS,ADVISORY_SHARE); token.mint(BOUNTY,BOUNTY_SHARE); token.mint(COMMUNITY,COMMUNITY_SHARE); token.mint(COMPANY,COMPANY_SHARE); token.mint(PRESALE,PRESALE_SHARE); tokensSold = PRESALE_SHARE; ready = true; SaleReady(); } /* * Function to do set or adjust the startTime - NOT MANDATORY but good for future start */ function changeStart(uint256 _time) public onlyOwner { startTime = _time; SaleWillStart(_time); } /* * Function end or pause the sale * @dev It's MANDATORY to finalize() */ function endSale(bool end) public onlyOwner { require(startTime <= now); uint256 tokensLeft = maxTokens - token.totalSupply(); if (tokensLeft > 0) { token.mint(wallet, tokensLeft); } hasEnded = end; SaleEnds(tokensLeft); } /* * Adjust finalization to transfer token ownership to the fund holding address for further use */ function finalization() internal { token.finishMinting(); token.transferOwnership(wallet); } /* * Clean up function to get the contract selfdestructed - OPTIONAL */ function cleanUp() public onlyOwner { require(isFinalized); selfdestruct(owner); } }
Only function for the tokens withdrawal (3% anytime, 5% after one year, 10% after two year) @dev Will withdraw the whole allowance;/
function withdraw() onlyOwner public { require(now - start >= 25920000); uint256 toWithdraw = canWithdraw(); withdrawn += toWithdraw; token.transfer(owner, toWithdraw); TokensWithdrawn(owner, toWithdraw); }
14,091,126
[ 1, 3386, 445, 364, 326, 2430, 598, 9446, 287, 261, 23, 9, 1281, 957, 16, 1381, 9, 1839, 1245, 3286, 16, 1728, 9, 1839, 2795, 3286, 13, 225, 9980, 598, 9446, 326, 7339, 1699, 1359, 31, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 598, 9446, 1435, 1338, 5541, 1071, 288, 203, 3639, 2583, 12, 3338, 300, 787, 1545, 576, 6162, 22, 2787, 1769, 203, 3639, 2254, 5034, 358, 1190, 9446, 273, 848, 1190, 9446, 5621, 203, 3639, 598, 9446, 82, 1011, 358, 1190, 9446, 31, 203, 3639, 1147, 18, 13866, 12, 8443, 16, 358, 1190, 9446, 1769, 203, 3639, 13899, 1190, 9446, 82, 12, 8443, 16, 358, 1190, 9446, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-01-31 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.11; /// @title ClonesWithImmutableArgs /// @author wighawag, zefram.eth /// @notice Enables creating clone contracts with immutable args library ClonesWithImmutableArgs { error CreateFail(); /// @notice Creates a clone proxy of the implementation contract, with immutable args /// @dev data cannot exceed 65535 bytes, since 2 bytes are used to store the data length /// @param implementation The implementation contract to clone /// @param data Encoded immutable args /// @return instance The address of the created clone function clone(address implementation, bytes memory data) internal returns (address instance) { // unrealistic for memory ptr or data length to exceed 256 bits unchecked { uint256 extraLength = data.length + 2; // +2 bytes for telling how much data there is appended to the call uint256 creationSize = 0x43 + extraLength; uint256 runSize = creationSize - 11; uint256 dataPtr; uint256 ptr; // solhint-disable-next-line no-inline-assembly assembly { ptr := mload(0x40) // ------------------------------------------------------------------------------------------------------------- // CREATION (11 bytes) // ------------------------------------------------------------------------------------------------------------- // 3d | RETURNDATASIZE | 0 | – // 61 runtime | PUSH2 runtime (r) | r 0 | – mstore( ptr, 0x3d61000000000000000000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x02), shl(240, runSize)) // size of the contract running bytecode (16 bits) // creation size = 0b // 80 | DUP1 | r r 0 | – // 60 creation | PUSH1 creation (c) | c r r 0 | – // 3d | RETURNDATASIZE | 0 c r r 0 | – // 39 | CODECOPY | r 0 | [0-2d]: runtime code // 81 | DUP2 | 0 c 0 | [0-2d]: runtime code // f3 | RETURN | 0 | [0-2d]: runtime code mstore( add(ptr, 0x04), 0x80600b3d3981f300000000000000000000000000000000000000000000000000 ) // ------------------------------------------------------------------------------------------------------------- // RUNTIME // ------------------------------------------------------------------------------------------------------------- // 36 | CALLDATASIZE | cds | – // 3d | RETURNDATASIZE | 0 cds | – // 3d | RETURNDATASIZE | 0 0 cds | – // 37 | CALLDATACOPY | – | [0, cds] = calldata // 61 | PUSH2 extra | extra | [0, cds] = calldata mstore( add(ptr, 0x0b), 0x363d3d3761000000000000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x10), shl(240, extraLength)) // 60 0x38 | PUSH1 0x38 | 0x38 extra | [0, cds] = calldata // 0x38 (56) is runtime size - data // 36 | CALLDATASIZE | cds 0x38 extra | [0, cds] = calldata // 39 | CODECOPY | _ | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 0 0 | [0, cds] = calldata // 36 | CALLDATASIZE | cds 0 0 0 | [0, cds] = calldata // 61 extra | PUSH2 extra | extra cds 0 0 0 | [0, cds] = calldata mstore( add(ptr, 0x12), 0x603836393d3d3d36610000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x1b), shl(240, extraLength)) // 01 | ADD | cds+extra 0 0 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 cds 0 0 0 | [0, cds] = calldata // 73 addr | PUSH20 0x123… | addr 0 cds 0 0 0 | [0, cds] = calldata mstore( add(ptr, 0x1d), 0x013d730000000000000000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x20), shl(0x60, implementation)) // 5a | GAS | gas addr 0 cds 0 0 0 | [0, cds] = calldata // f4 | DELEGATECALL | success 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | rds success 0 | [0, cds] = calldata // 82 | DUP3 | 0 rds success 0 | [0, cds] = calldata // 80 | DUP1 | 0 0 rds success 0 | [0, cds] = calldata // 3e | RETURNDATACOPY | success 0 | [0, rds] = return data (there might be some irrelevant leftovers in memory [rds, cds] when rds < cds) // 90 | SWAP1 | 0 success | [0, rds] = return data // 3d | RETURNDATASIZE | rds 0 success | [0, rds] = return data // 91 | SWAP2 | success 0 rds | [0, rds] = return data // 60 0x36 | PUSH1 0x36 | 0x36 sucess 0 rds | [0, rds] = return data // 57 | JUMPI | 0 rds | [0, rds] = return data // fd | REVERT | – | [0, rds] = return data // 5b | JUMPDEST | 0 rds | [0, rds] = return data // f3 | RETURN | – | [0, rds] = return data mstore( add(ptr, 0x34), 0x5af43d82803e903d91603657fd5bf30000000000000000000000000000000000 ) } // ------------------------------------------------------------------------------------------------------------- // APPENDED DATA (Accessible from extcodecopy) // (but also send as appended data to the delegatecall) // ------------------------------------------------------------------------------------------------------------- extraLength -= 2; uint256 counter = extraLength; uint256 copyPtr = ptr + 0x43; // solhint-disable-next-line no-inline-assembly assembly { dataPtr := add(data, 32) } for (; counter >= 32; counter -= 32) { // solhint-disable-next-line no-inline-assembly assembly { mstore(copyPtr, mload(dataPtr)) } copyPtr += 32; dataPtr += 32; } uint256 mask = ~(256**(32 - counter) - 1); // solhint-disable-next-line no-inline-assembly assembly { mstore(copyPtr, and(mload(dataPtr), mask)) } copyPtr += counter; // solhint-disable-next-line no-inline-assembly assembly { mstore(copyPtr, shl(240, extraLength)) } // solhint-disable-next-line no-inline-assembly assembly { instance := create(0, ptr, creationSize) } if (instance == address(0)) { revert CreateFail(); } } } } /// @title Clone /// @author zefram.eth /// @notice Provides helper functions for reading immutable args from calldata contract Clone { /// @notice Reads an immutable arg with type address /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgAddress(uint256 argOffset) internal pure returns (address arg) { uint256 offset = _getImmutableArgsOffset(); assembly { arg := shr(0x60, calldataload(add(offset, argOffset))) } } /// @notice Reads an immutable arg with type uint256 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint256(uint256 argOffset) internal pure returns (uint256 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := calldataload(add(offset, argOffset)) } } /// @notice Reads an immutable arg with type uint64 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint64(uint256 argOffset) internal pure returns (uint64 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := shr(0xc0, calldataload(add(offset, argOffset))) } } /// @notice Reads an immutable arg with type uint8 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint8(uint256 argOffset) internal pure returns (uint8 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := shr(0xf8, calldataload(add(offset, argOffset))) } } /// @return offset The offset of the packed immutable args in calldata function _getImmutableArgsOffset() internal pure returns (uint256 offset) { // solhint-disable-next-line no-inline-assembly assembly { offset := sub( calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2) ) } } } /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20Clone is Clone { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// METADATA //////////////////////////////////////////////////////////////*/ function name() external pure returns (string memory) { return string(abi.encodePacked(_getArgUint256(0))); } function symbol() external pure returns (string memory) { return string(abi.encodePacked(_getArgUint256(0x20))); } function decimals() external pure returns (uint8) { return _getArgUint8(0x40); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// INTERNAL LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } function _getImmutableVariablesOffset() internal pure returns (uint256 offset) { assembly { offset := sub( calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2) ) } } } /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { 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, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } } /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (type(uint256).max - denominator + 1) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); unchecked { if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } } /// @title VestedERC20 /// @author zefram.eth /// @notice An ERC20 wrapper token that linearly vests an underlying token to /// its holders contract VestedERC20 is ERC20Clone { /// ----------------------------------------------------------------------- /// Library usage /// ----------------------------------------------------------------------- using SafeTransferLib for ERC20; /// ----------------------------------------------------------------------- /// Errors /// ----------------------------------------------------------------------- error Error_Wrap_VestOver(); error Error_Wrap_AmountTooLarge(); /// ----------------------------------------------------------------------- /// Storage variables /// ----------------------------------------------------------------------- /// @notice The amount of underlying tokens claimed by a token holder mapping(address => uint256) public claimedUnderlyingAmount; /// ----------------------------------------------------------------------- /// Immutable parameters /// ----------------------------------------------------------------------- /// @notice The token that is vested /// @return _underlying The address of the underlying token function underlying() public pure returns (address _underlying) { return _getArgAddress(0x41); } /// @notice The Unix timestamp (in seconds) of the start of the vest /// @return _startTimestamp The vest start timestamp function startTimestamp() public pure returns (uint64 _startTimestamp) { return _getArgUint64(0x55); } /// @notice The Unix timestamp (in seconds) of the end of the vest /// @return _endTimestamp The vest end timestamp function endTimestamp() public pure returns (uint64 _endTimestamp) { return _getArgUint64(0x5d); } /// ----------------------------------------------------------------------- /// User actions /// ----------------------------------------------------------------------- /// @notice Mints wrapped tokens using underlying tokens. Can only be called before the vest is over. /// @param underlyingAmount The amount of underlying tokens to wrap /// @param recipient The address that will receive the minted wrapped tokens /// @return wrappedTokenAmount The amount of wrapped tokens minted function wrap(uint256 underlyingAmount, address recipient) external returns (uint256 wrappedTokenAmount) { /// ------------------------------------------------------------------- /// Validation /// ------------------------------------------------------------------- uint256 _startTimestamp = startTimestamp(); uint256 _endTimestamp = endTimestamp(); if (block.timestamp >= _endTimestamp) { revert Error_Wrap_VestOver(); } if ( underlyingAmount >= type(uint256).max / (_endTimestamp - _startTimestamp) ) { revert Error_Wrap_AmountTooLarge(); } /// ------------------------------------------------------------------- /// State updates /// ------------------------------------------------------------------- if (block.timestamp >= _startTimestamp) { // vest already started // wrappedTokenAmount * (endTimestamp() - block.timestamp) / (endTimestamp() - startTimestamp()) == underlyingAmount // thus, wrappedTokenAmount = underlyingAmount * (endTimestamp() - startTimestamp()) / (endTimestamp() - block.timestamp) wrappedTokenAmount = (underlyingAmount * (_endTimestamp - _startTimestamp)) / (_endTimestamp - block.timestamp); // pretend we have claimed the vested underlying amount claimedUnderlyingAmount[recipient] += wrappedTokenAmount - underlyingAmount; } else { // vest hasn't started yet wrappedTokenAmount = underlyingAmount; } // mint wrapped tokens _mint(recipient, wrappedTokenAmount); /// ------------------------------------------------------------------- /// Effects /// ------------------------------------------------------------------- ERC20 underlyingToken = ERC20(underlying()); underlyingToken.safeTransferFrom( msg.sender, address(this), underlyingAmount ); } /// @notice Allows a holder of the wrapped token to redeem the vested tokens /// @param recipient The address that will receive the vested tokens /// @return redeemedAmount The amount of vested tokens redeemed function redeem(address recipient) external returns (uint256 redeemedAmount) { /// ------------------------------------------------------------------- /// State updates /// ------------------------------------------------------------------- uint256 _claimedUnderlyingAmount = claimedUnderlyingAmount[msg.sender]; redeemedAmount = _getRedeemableAmount( msg.sender, _claimedUnderlyingAmount ); claimedUnderlyingAmount[msg.sender] = _claimedUnderlyingAmount + redeemedAmount; /// ------------------------------------------------------------------- /// Effects /// ------------------------------------------------------------------- if (redeemedAmount > 0) { ERC20 underlyingToken = ERC20(underlying()); underlyingToken.safeTransfer(recipient, redeemedAmount); } } /// @notice The ERC20 transfer function function transfer(address to, uint256 amount) public override returns (bool) { uint256 senderBalance = balanceOf[msg.sender]; uint256 senderClaimedUnderlyingAmount = claimedUnderlyingAmount[ msg.sender ]; balanceOf[msg.sender] = senderBalance - amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv( senderClaimedUnderlyingAmount, amount, senderBalance ); if (claimedUnderlyingAmountToTransfer > 0) { claimedUnderlyingAmount[msg.sender] = senderClaimedUnderlyingAmount - claimedUnderlyingAmountToTransfer; unchecked { claimedUnderlyingAmount[ to ] += claimedUnderlyingAmountToTransfer; } } emit Transfer(msg.sender, to, amount); return true; } /// @notice The ERC20 transferFrom function function transferFrom( address from, address to, uint256 amount ) public override returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; uint256 fromBalance = balanceOf[from]; uint256 fromClaimedUnderlyingAmount = claimedUnderlyingAmount[from]; balanceOf[from] = fromBalance - amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv( fromClaimedUnderlyingAmount, amount, fromBalance ); if (claimedUnderlyingAmountToTransfer > 0) { claimedUnderlyingAmount[from] = fromClaimedUnderlyingAmount - claimedUnderlyingAmountToTransfer; unchecked { claimedUnderlyingAmount[ to ] += claimedUnderlyingAmountToTransfer; } } emit Transfer(from, to, amount); return true; } /// ----------------------------------------------------------------------- /// Getters /// ----------------------------------------------------------------------- /// @notice Computes the amount of vested tokens redeemable by an account /// @param holder The wrapped token holder to query /// @return The amount of vested tokens redeemable function getRedeemableAmount(address holder) external view returns (uint256) { return _getRedeemableAmount(holder, claimedUnderlyingAmount[holder]); } /// ----------------------------------------------------------------------- /// Internal functions /// ----------------------------------------------------------------------- function _getRedeemableAmount( address holder, uint256 holderClaimedUnderlyingAmount ) internal view returns (uint256) { uint256 _startTimestamp = startTimestamp(); uint256 _endTimestamp = endTimestamp(); if (block.timestamp <= _startTimestamp) { // vest hasn't started yet, nothing is vested return 0; } else if (block.timestamp >= _endTimestamp) { // vest is over, everything is vested return balanceOf[holder] - holderClaimedUnderlyingAmount; } else { // middle of vest, compute linear vesting return (balanceOf[holder] * (block.timestamp - _startTimestamp)) / (_endTimestamp - _startTimestamp) - holderClaimedUnderlyingAmount; } } } /// @title VestedERC20Factory /// @author zefram.eth /// @notice Factory for deploying VestedERC20 contracts cheaply contract VestedERC20Factory { /// ----------------------------------------------------------------------- /// Library usage /// ----------------------------------------------------------------------- using ClonesWithImmutableArgs for address; /// ----------------------------------------------------------------------- /// Errors /// ----------------------------------------------------------------------- error Error_InvalidTimeRange(); /// ----------------------------------------------------------------------- /// Events /// ----------------------------------------------------------------------- event CreateVestedERC20(VestedERC20 vestedERC20); /// ----------------------------------------------------------------------- /// Immutable parameters /// ----------------------------------------------------------------------- /// @notice The VestedERC20 used as the template for all clones created VestedERC20 public immutable implementation; constructor(VestedERC20 implementation_) { implementation = implementation_; } /// @notice Creates a VestedERC20 contract /// @dev Uses a modified minimal proxy contract that stores immutable parameters in code and /// passes them in through calldata. See ClonesWithCallData. /// @param name The name of the VestedERC20 token /// @param symbol The symbol of the VestedERC20 token /// @param decimals The number of decimals used by the VestedERC20 token /// @param underlying The ERC20 token that is vested /// @param startTimestamp The start time of the vest, Unix timestamp in seconds /// @param endTimestamp The end time of the vest, must be greater than startTimestamp, Unix timestamp in seconds /// @return vestedERC20 The created VestedERC20 contract function createVestedERC20( bytes32 name, bytes32 symbol, uint8 decimals, address underlying, uint64 startTimestamp, uint64 endTimestamp ) external returns (VestedERC20 vestedERC20) { if (endTimestamp <= startTimestamp) { revert Error_InvalidTimeRange(); } bytes memory data = abi.encodePacked( name, symbol, decimals, underlying, startTimestamp, endTimestamp ); vestedERC20 = VestedERC20(address(implementation).clone(data)); emit CreateVestedERC20(vestedERC20); } }
//*///*///*///*///*/
) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } ERC20 LOGIC
2,133,593
[ 1, 2105, 18235, 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, 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, 3639, 262, 288, 203, 5411, 508, 273, 389, 529, 31, 203, 5411, 3273, 273, 389, 7175, 31, 203, 5411, 15105, 273, 389, 31734, 31, 203, 203, 5411, 28226, 67, 1792, 6964, 67, 734, 273, 1203, 18, 5639, 350, 31, 203, 5411, 28226, 67, 18192, 67, 4550, 273, 3671, 3748, 6581, 5621, 203, 3639, 289, 203, 203, 27573, 4232, 39, 3462, 2018, 2871, 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 ]
pragma solidity ^0.4.20; /** * Standard SafeMath Library: zeppelin-solidity/contracts/math/SafeMath.sol */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } } /** * Buy GPX automatically when Ethers are received */ contract Buyable { function buy() payable public returns (uint256); } /** * Exchange all my ParcelX token to mainchain GPX */ contract Convertible { function convertMainchainGPX(string destinationAccount, string extra) external returns (bool); // ParcelX deamon program is monitoring this event. // Once it triggered, ParcelX will transfer corresponding GPX to destination account event Converted(address indexed who, string destinationAccount, uint256 amount, string extra); } /** * Starndard ERC20 interface: https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); 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); } /** * FEATURE 2): MultiOwnable implementation */ contract MultiOwnable { address[8] m_owners; uint m_numOwners; uint m_multiRequires; mapping (bytes32 => uint) internal m_pendings; // constructor is given number of sigs required to do protected "multiOwner" transactions // as well as the selection of addresses capable of confirming them. function MultiOwnable (address[] _otherOwners, uint _multiRequires) internal { require(0 < _multiRequires && _multiRequires <= _otherOwners.length + 1); m_numOwners = _otherOwners.length + 1; require(m_numOwners <= 8); // 不支持大于8人 m_owners[0] = msg.sender; for (uint i = 0; i < _otherOwners.length; ++i) { m_owners[1 + i] = _otherOwners[i]; } m_multiRequires = _multiRequires; } // Any one of the owners, will approve the action modifier anyOwner { if (isOwner(msg.sender)) { _; } } // Requiring num > m_multiRequires owners, to approve the action modifier mostOwner(bytes32 operation) { if (checkAndConfirm(msg.sender, operation)) { _; } } function isOwner(address currentOwner) internal view returns (bool) { for (uint i = 0; i < m_numOwners; ++i) { if (m_owners[i] == currentOwner) { return true; } } return false; } function checkAndConfirm(address currentOwner, bytes32 operation) internal returns (bool) { uint ownerIndex = m_numOwners; uint i; for (i = 0; i < m_numOwners; ++i) { if (m_owners[i] == currentOwner) { ownerIndex = i; } } if (ownerIndex == m_numOwners) { return false; // Not Owner } uint newBitFinger = (m_pendings[operation] | (2 ** ownerIndex)); uint confirmTotal = 0; for (i = 0; i < m_numOwners; ++i) { if ((newBitFinger & (2 ** i)) > 0) { confirmTotal ++; } } if (confirmTotal >= m_multiRequires) { delete m_pendings[operation]; return true; } else { m_pendings[operation] = newBitFinger; return false; } } } /** * FEATURE 3): Pausable implementation */ contract Pausable is MultiOwnable { event Pause(); event Unpause(); bool paused = false; // Modifier to make a function callable only when the contract is not paused. modifier whenNotPaused() { require(!paused); _; } // Modifier to make a function callable only when the contract is paused. modifier whenPaused() { require(paused); _; } // called by the owner to pause, triggers stopped state function pause() mostOwner(keccak256(msg.data)) whenNotPaused public { paused = true; Pause(); } // called by the owner to unpause, returns to normal state function unpause() mostOwner(keccak256(msg.data)) whenPaused public { paused = false; Unpause(); } function isPause() view public returns(bool) { return paused; } } /** * The main body of final smart contract */ contract ParcelXToken is ERC20, MultiOwnable, Pausable, Buyable, Convertible { using SafeMath for uint256; string public constant name = "TestGPX-name"; string public constant symbol = "TestGPX-symbol"; uint8 public constant decimals = 18; uint256 public constant TOTAL_SUPPLY = uint256(1000000000) * (uint256(10) ** decimals); // 10,0000,0000 address internal tokenPool; // Use a token pool holding all GPX. Avoid using sender address. mapping(address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; function ParcelXToken(address[] _otherOwners, uint _multiRequires) MultiOwnable(_otherOwners, _multiRequires) public { tokenPool = this; balances[tokenPool] = TOTAL_SUPPLY; } /** * FEATURE 1): ERC20 implementation */ function totalSupply() public view returns (uint256) { return TOTAL_SUPPLY; } 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); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } 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); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint 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; } /** * FEATURE 4): Buyable implements * 0.000268 eth per GPX, so the rate is 1.0 / 0.000268 = 3731.3432835820895 */ uint256 internal buyRate = uint256(3731); event Deposit(address indexed who, uint256 value); event Withdraw(address indexed who, uint256 value, address indexed lastApprover); function getBuyRate() external view returns (uint256) { return buyRate; } function setBuyRate(uint256 newBuyRate) mostOwner(keccak256(msg.data)) external { buyRate = newBuyRate; } // minimum of 0.001 ether for purchase in the public, pre-ico, and private sale function buy() payable whenNotPaused public returns (uint256) { require(msg.value >= 0.001 ether); uint256 tokens = msg.value.mul(buyRate); // calculates the amount require(balances[tokenPool] >= tokens); // checks if it has enough to sell balances[tokenPool] = balances[tokenPool].sub(tokens); // subtracts amount from seller's balance balances[msg.sender] = balances[msg.sender].add(tokens); // adds the amount to buyer's balance Transfer(tokenPool, msg.sender, tokens); // execute an event reflecting the change return tokens; // ends function and returns } // gets called when no other function matches function () public payable { if (msg.value > 0) { buy(); Deposit(msg.sender, msg.value); } } function execute(address _to, uint256 _value, bytes _data) mostOwner(keccak256(msg.data)) external returns (bool){ require(_to != address(0)); Withdraw(_to, _value, msg.sender); return _to.call.value(_value)(_data); } /** * FEATURE 5): Convertible implements */ function convertMainchainGPX(string destinationAccount, string extra) external returns (bool) { require(bytes(destinationAccount).length > 10 && bytes(destinationAccount).length < 128); require(balances[msg.sender] > 0); uint256 amount = balances[msg.sender]; balances[msg.sender] = 0; balances[tokenPool] = balances[tokenPool].add(amount); // recycle ParcelX to tokenPool's init account Converted(msg.sender, destinationAccount, amount, extra); return true; } }
minimum of 0.001 ether for purchase in the public, pre-ico, and private sale
function buy() payable whenNotPaused public returns (uint256) { require(msg.value >= 0.001 ether); }
1,399,401
[ 1, 15903, 434, 374, 18, 11664, 225, 2437, 364, 23701, 316, 326, 1071, 16, 675, 17, 10764, 16, 471, 3238, 272, 5349, 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, 30143, 1435, 8843, 429, 1347, 1248, 28590, 1071, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 374, 18, 11664, 225, 2437, 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 ]
./full_match/80001/0x3fd146029F4Ea198E97B7E90727B056F3E09d6C8/sources/src/MintpadERC1155Drop.sol
//*/ @dev Runs before every `claim` function call.
Internal (overrideable) functions function _beforeClaim( uint256 _tokenId, address, uint256 _quantity, address, uint256, AllowlistProof calldata, bytes memory ) internal view override { require( maxTotalSupply[_tokenId] == 0 || totalSupply[_tokenId] + _quantity <= maxTotalSupply[_tokenId], "exceed max total supply" ); }
5,610,685
[ 1, 28111, 225, 1939, 87, 1865, 3614, 1375, 14784, 68, 445, 745, 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 ]
[ 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, 13491, 3186, 261, 10601, 429, 13, 4186, 203, 203, 565, 445, 389, 5771, 9762, 12, 203, 3639, 2254, 5034, 389, 2316, 548, 16, 203, 3639, 1758, 16, 203, 3639, 2254, 5034, 389, 16172, 16, 203, 3639, 1758, 16, 203, 3639, 2254, 5034, 16, 203, 3639, 7852, 1098, 20439, 745, 892, 16, 203, 3639, 1731, 3778, 203, 565, 262, 2713, 1476, 3849, 288, 203, 3639, 2583, 12, 203, 5411, 943, 5269, 3088, 1283, 63, 67, 2316, 548, 65, 422, 374, 747, 2078, 3088, 1283, 63, 67, 2316, 548, 65, 397, 389, 16172, 1648, 943, 5269, 3088, 1283, 63, 67, 2316, 548, 6487, 203, 5411, 315, 338, 5288, 943, 2078, 14467, 6, 203, 3639, 11272, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; interface ManagementList { function isManager(address accountAddress) external returns (bool); } contract Manageable { ManagementList public managementList; constructor(address _managementListAddress) { managementList = ManagementList(_managementListAddress); } modifier onlyManagers() { bool isManager = managementList.isManager(msg.sender); require(isManager, "ManagementList: caller is not a manager"); _; } } /******************************************************* * Interfaces * *******************************************************/ interface IEarnRegistry { function assets() external view returns (address[] memory); function numAssets() external view returns (uint256); } /******************************************************* * Generator Logic * *******************************************************/ contract AddressesGeneratorEarn is Manageable { mapping(address => bool) public assetDeprecated; // Support for deprecating assets. If an asset is deprecated it will not appear is results uint256 public numberOfDeprecatedAssets; // Used to keep track of the number of deprecated assets for an adapter address[] public positionSpenderAddresses; // A settable list of spender addresses with which to fetch asset allowances IEarnRegistry public registry; // The registry is used to fetch the list of assets /** * Information about the generator */ struct GeneratorInfo { address id; // Generator address string typeId; // Generator typeId (for example "VAULT_V2" or "IRON_BANK_MARKET") string categoryId; // Generator categoryId (for example "VAULT") } /** * Configure generator */ constructor(address _registryAddress, address _managementListAddress) Manageable(_managementListAddress) { require( _managementListAddress != address(0), "Missing management list address" ); require(_registryAddress != address(0), "Missing registry address"); registry = IEarnRegistry(_registryAddress); } /** * Deprecate or undeprecate an asset. Deprecated assets will not appear in any adapter or generator method call responses */ function setAssetDeprecated(address assetAddress, bool newDeprecationStatus) public onlyManagers { bool currentDeprecationStatus = assetDeprecated[assetAddress]; if (currentDeprecationStatus == newDeprecationStatus) { revert("Generator: Unable to change asset deprecation status"); } if (newDeprecationStatus == true) { numberOfDeprecatedAssets++; } else { numberOfDeprecatedAssets--; } assetDeprecated[assetAddress] = newDeprecationStatus; } /** * Set position spender addresses. Used by `adapter.assetAllowances(address,address)`. */ function setPositionSpenderAddresses(address[] memory addresses) public onlyManagers { positionSpenderAddresses = addresses; } /** * Set registry address */ function setRegistryAddress(address _registryAddress) public onlyManagers { require(_registryAddress != address(0), "Missing registry address"); registry = IEarnRegistry(_registryAddress); } /** * Fetch a list of position spender addresses */ function getPositionSpenderAddresses() external view returns (address[] memory) { return positionSpenderAddresses; } /** * Fetch generator info */ function generatorInfo() public view returns (GeneratorInfo memory) { return GeneratorInfo({ id: address(this), typeId: "EARN", categoryId: "SAFE" }); } /** * Fetch the total number of assets */ function assetsLength() public view returns (uint256) { return registry.numAssets() - numberOfDeprecatedAssets; } /** * Fetch all asset addresses */ function assetsAddresses() public view returns (address[] memory) { uint256 _numberOfAssets = registry.numAssets(); uint256 _filteredAssetsLength = assetsLength(); address[] memory originalAddresses = registry.assets(); if (_numberOfAssets == _filteredAssetsLength) { return originalAddresses; } uint256 currentAssetIdx; for (uint256 assetIdx = 0; assetIdx < _numberOfAssets; assetIdx++) { address currentAssetAddress = originalAddresses[assetIdx]; bool assetIsNotDeprecated = assetDeprecated[currentAssetAddress] == false; if (assetIsNotDeprecated) { originalAddresses[currentAssetIdx] = currentAssetAddress; currentAssetIdx++; } } bytes memory encodedAddresses = abi.encode(originalAddresses); assembly { // Manually truncate the filtered list mstore(add(encodedAddresses, 0x40), _filteredAssetsLength) } address[] memory filteredAddresses = abi.decode(encodedAddresses, (address[])); return filteredAddresses; } }
The registry is used to fetch the list of assets
IEarnRegistry public registry;
1,343,736
[ 1, 1986, 4023, 353, 1399, 358, 2158, 326, 666, 434, 7176, 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, 10897, 1303, 4243, 1071, 4023, 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 ]
// Sources flattened with hardhat v2.6.0 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol // SPDX-License-Identifier: MIT pragma solidity >=0.4.24 <0.7.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; } } // File deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.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 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 deps/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.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 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 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 interfaces/badger/IMiniMe.sol pragma solidity >=0.5.0 <0.8.0; interface IMiniMe { event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint256 _snapshotBlock); event Approval(address indexed _owner, address indexed _spender, uint256 _amount); function claimTokens(address _token) external; function controller() external view returns (address); function enableTransfers(bool _transfersEnabled) external; function generateTokens(address _owner, uint256 _amount) external returns (bool); function destroyTokens(address _owner, uint256 _amount) external returns (bool); function changeController(address _newController) external returns (address); } // File interfaces/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 name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() 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/badger-core/GatedMiniMeController.sol pragma solidity 0.6.12; /* === Gated MiniMe Controller === Limits the functinality of the MiniMe controller address by serving as an intermediate contract. The owner maintains the ability to mint and burn tokens from it's own balance, losing the ability to mint and burn to/from arbitrary accounts. The MiniMe controller can no longer be changed. The owner maintains the ability to claim other tokens sent to the MiniMe contract. This contract is designed to be upgradeable, this ability can be removed by transferring the proxyAdmin to 0x0. Minting and burning can be permanently removed by the disableMinting() function. claimTokens() is designed to be retained. It ability can be removed (along with minting and burning), by burning the owner() address. */ contract GatedMiniMeController is OwnableUpgradeable { IMiniMe public minime; bool public mintingEnabled; function initialize(address token_) external { __Ownable_init(); minime = IMiniMe(token_); mintingEnabled = true; } modifier onlyWhenMintingEnabled() { require(mintingEnabled == true, "minting disabled"); _; } /// @dev Minting and burning can be permanently disabled by the owner function disableMinting() external onlyOwner { mintingEnabled = false; } /// @dev Mint tokens to governance function mint(uint256 amount) external onlyOwner onlyWhenMintingEnabled { require(minime.generateTokens(owner(), amount), "mint failed"); } /// @dev Burn tokens from governance function burn(uint256 amount) external onlyOwner onlyWhenMintingEnabled { require(minime.destroyTokens(owner(), amount), "burn failed"); } /// @dev Claim other tokens function claimTokens(address token) external onlyOwner { minime.claimTokens(token); require(IERC20(token).transfer(owner(), IERC20(token).balanceOf(address(this))), "claim tokens transfer to owner failed"); } }
@dev Claim other tokens
function claimTokens(address token) external onlyOwner { minime.claimTokens(token); require(IERC20(token).transfer(owner(), IERC20(token).balanceOf(address(this))), "claim tokens transfer to owner failed"); }
7,537
[ 1, 9762, 1308, 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, 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, 7516, 5157, 12, 2867, 1147, 13, 3903, 1338, 5541, 288, 203, 3639, 1131, 494, 18, 14784, 5157, 12, 2316, 1769, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 2316, 2934, 13866, 12, 8443, 9334, 467, 654, 39, 3462, 12, 2316, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 3631, 315, 14784, 2430, 7412, 358, 3410, 2535, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-09-04 */ // 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 Stattitude { 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, 'Stattitude: hex length insufficient'); 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(), '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); } } /** * @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; } } /** * @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); } 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 Stattitude 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(to).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, food 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, food 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 emLoot is ERC721Enumerable, ReentrancyGuard, Ownable { string[] private face = [ unicode'😀', unicode'😂', unicode'😍', unicode'😎', unicode'😡', unicode'🥺', unicode'😩', unicode'😴', unicode'😷', unicode'😈', unicode'👻', unicode'🤖', unicode'🤮', unicode'😱', unicode'😭', unicode'🤪', unicode'🤡', unicode'👽' ]; string[] private pet = [ unicode'🐶', unicode'🐱', unicode'🐭', unicode'🐰', unicode'🦊', unicode'🐻', unicode'🐯', unicode'🦁', unicode'🐮', unicode'🐷', unicode'🐸', unicode'🐵', unicode'🐔', unicode'🦉', unicode'🦄', unicode'🐟', unicode'🐳', unicode'🐏' ]; string[] private food = [ unicode'🍳', unicode'🍔', unicode'🍕', unicode'🍣', unicode'🍵', unicode'🍺', unicode'🍎', unicode'🍉', unicode'🍒', unicode'🍋', unicode'🍌', unicode'🍜', unicode'🍭', unicode'🍼', unicode'🦴', unicode'🧋', unicode'🎂', unicode'🧀' ]; string[] private sport = [ unicode'⚽️', unicode'🏀', unicode'🏈', unicode'🎾', unicode'🏐', unicode'🎱', unicode'🏓', unicode'🏸', unicode'🏒', unicode'⛳️', unicode'🏹', unicode'🎣', unicode'🥊', unicode'🤿', unicode'🥋', unicode'⛷', unicode'🏊️', unicode'🚴️' ]; string[] private traffic = [ unicode'🚗', unicode'🚕', unicode'🚌', unicode'🚜', unicode'🛴', unicode'🦽', unicode'🚲', unicode'🛵', unicode'🚄', unicode'✈️', unicode'🚀', unicode'⛵️', unicode'🚁', unicode'🦵' ]; string[] private job = [ unicode'👮', unicode'👷', unicode'🧑‍💻', unicode'🧑‍🎓', unicode'🧑‍🌾', unicode'🧑‍🎨', unicode'🧑‍🔬', unicode'🧑‍🏫', unicode'🧑‍🍳', unicode'🧑‍⚕️', unicode'🕵️', unicode'🧑‍🚒', unicode'🧑‍🚀', unicode'🥷', unicode'🧞️', unicode'🧛' ]; string[] private tool = [ unicode'💊', unicode'📱', unicode'💻', unicode'🎙', unicode'🎥', unicode'🛠', unicode'🔪', unicode'⛓', unicode'💣', unicode'🔫', unicode'🚽', unicode'🎁', unicode'🎉', unicode'💎', unicode'💰' ]; string[] private attitude = [ unicode'👍', unicode'👎', unicode'✊', unicode'🤘', unicode'🤏', unicode'🤙', unicode'🙏', unicode'🖕', unicode'👌', unicode'👏', unicode'💩', unicode'👄', unicode'👋', unicode'✌️', unicode'💪' ]; string[] private suffixes = [ unicode'at 🌅', unicode'at 🌄', unicode'at 🎆', unicode'at 🏞', unicode'at 🌃', unicode'at 🏦', unicode'at 🏥', unicode'at 🏠', unicode'at 🎡', unicode'at 🏖', unicode'at 🏛' ]; string[] private namePrefixes = [ unicode'🔥', unicode'🌈', unicode'⭐️', unicode'🌎', unicode'❤️', unicode'💡', unicode'💯' ]; string[] private nameSuffixes = [ unicode'❗️', unicode'❓', unicode'🎉', unicode'💎', unicode'💰', unicode'🎖' ]; function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getFace(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, 'FACE', face); } function getPet(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, 'PET', pet); } function getFood(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, 'FOOD', food); } function getSport(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, 'SPORT', sport); } function getTraffic(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, 'TRAFFIC', traffic); } function getJob(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, 'JOB', job); } function getTool(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, 'TOOL', tool); } function getAttitude(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, 'ATTITUDE', attitude); } function pluck( uint256 tokenId, string memory keyPrefix, string[] memory sourceArray ) internal view returns (string memory) { uint256 rand = random( string(abi.encodePacked(keyPrefix, toString(tokenId))) ); string memory output = sourceArray[rand % sourceArray.length]; uint256 greatness = rand % 21; if (greatness > 14) { output = string( abi.encodePacked(output, ' ', suffixes[rand % suffixes.length]) ); } if (greatness >= 19) { string[2] memory name; name[0] = namePrefixes[rand % namePrefixes.length]; name[1] = nameSuffixes[rand % nameSuffixes.length]; if (greatness == 19) { output = string( abi.encodePacked( '#', name[0], ' ', name[1], '# ', output, unicode' 🏆' ) ); } else { output = string( abi.encodePacked('#', name[0], ' ', name[1], '# ', output) ); } } return output; } function tokenURI(uint256 tokenId) public view override returns (string memory) { string[17] memory parts; parts[ 0 ] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getFace(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getPet(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getFood(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getSport(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getTraffic(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getJob(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getTool(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; parts[15] = getAttitude(tokenId); parts[16] = '</text></svg>'; string memory output = string( abi.encodePacked( parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8] ) ); output = string( abi.encodePacked( output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14], parts[15], parts[16] ) ); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "Person #', toString(tokenId), '", "description": "Emoji Loot uses emoji to describe an abstract person", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '","attributes": [', abi.encodePacked( '{"trait_type": "Face", "value": "', parts[1], '"},', '{"trait_type": "Pet", "value": "', parts[3], '"},', '{"trait_type": "Food", "value": "', parts[5], '"},' ), abi.encodePacked( '{"trait_type": "Sport", "value": "', parts[7], '"},', '{"trait_type": "Traffic", "value": "', parts[9], '"},', '{"trait_type": "Job", "value": "', parts[11], '"},' ), abi.encodePacked( '{"trait_type": "Tool", "value": "', parts[13], '"},', '{"trait_type": "Attitude", "value": "', parts[15], '"}' ), ']}' ) ) ) ); 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); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } constructor() ERC721('emLoot', 'emLoot') Ownable() {} } 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); } }
* the Metadata extension, but not including the Enumerable extension, which is available separately as {ERC721Enumerable}./ Token name Token symbol Mapping from token ID to owner address Mapping owner address to token count Mapping from token ID to approved address Mapping from owner to operator approvals
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Stattitude for uint256; string private _name; string private _symbol; mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), 'ERC721: balance query for the zero address' ); return _balances[owner]; } 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; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } 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())) : ''; } function _baseURI() internal view virtual returns (string memory) { return ''; } 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); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), 'ERC721: approved query for nonexistent token' ); return _tokenApprovals[tokenId]; } 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); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), 'ERC721: transfer caller is not owner nor approved' ); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } 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); } 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' ); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } 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)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ''); } 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' ); } 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); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } 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); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } 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; if (reason.length == 0) { revert( 'ERC721: transfer to non ERC721Receiver implementer' ); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } 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; if (reason.length == 0) { revert( 'ERC721: transfer to non ERC721Receiver implementer' ); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } 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; if (reason.length == 0) { revert( 'ERC721: transfer to non ERC721Receiver implementer' ); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } catch (bytes memory reason) { 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; if (reason.length == 0) { revert( 'ERC721: transfer to non ERC721Receiver implementer' ); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } else { 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; if (reason.length == 0) { revert( 'ERC721: transfer to non ERC721Receiver implementer' ); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } else { ) internal virtual {} }
10,726,731
[ 1, 5787, 6912, 2710, 16, 1496, 486, 6508, 326, 6057, 25121, 2710, 16, 1492, 353, 2319, 18190, 487, 288, 654, 39, 27, 5340, 3572, 25121, 5496, 19, 3155, 508, 3155, 3273, 9408, 628, 1147, 1599, 358, 3410, 1758, 9408, 3410, 1758, 358, 1147, 1056, 9408, 628, 1147, 1599, 358, 20412, 1758, 9408, 628, 3410, 358, 3726, 6617, 4524, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 4232, 39, 27, 5340, 353, 1772, 16, 4232, 39, 28275, 16, 467, 654, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 2277, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 934, 4558, 3540, 364, 2254, 5034, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 995, 414, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 203, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 565, 289, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 12, 654, 39, 28275, 16, 467, 654, 39, 28275, 13, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 203, 5411, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 2934, 5831, 548, 747, 203, 5411, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 2277, 2934, 5831, 548, 747, 203, 5411, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 2 ]
./full_match/122/0xc01cF5d80994FC2C38318a01b12EcE94F93f03D8/sources/contracts/masset/Masset.sol
* @dev Set the ecosystem fee for sewapping bAssets or redeeming specific bAssets @param _swapFee Fee calculated in (%/100 1e18)/
function setFees(uint256 _swapFee, uint256 _redemptionFee) external override onlyGovernor { require(_swapFee <= MAX_FEE, "Swap rate oob"); require(_redemptionFee <= MAX_FEE, "Redemption rate oob"); data.swapFee = _swapFee; data.redemptionFee = _redemptionFee; emit FeesChanged(_swapFee, _redemptionFee); }
16,367,626
[ 1, 694, 326, 6557, 538, 1108, 14036, 364, 272, 359, 438, 1382, 324, 10726, 578, 283, 24903, 310, 2923, 324, 10726, 225, 389, 22270, 14667, 30174, 8894, 316, 6142, 19, 6625, 225, 404, 73, 2643, 13176, 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, 565, 445, 444, 2954, 281, 12, 11890, 5034, 389, 22270, 14667, 16, 2254, 5034, 389, 266, 19117, 375, 14667, 13, 3903, 3849, 1338, 43, 1643, 29561, 288, 203, 3639, 2583, 24899, 22270, 14667, 1648, 4552, 67, 8090, 41, 16, 315, 12521, 4993, 320, 947, 8863, 203, 3639, 2583, 24899, 266, 19117, 375, 14667, 1648, 4552, 67, 8090, 41, 16, 315, 426, 19117, 375, 4993, 320, 947, 8863, 203, 203, 3639, 501, 18, 22270, 14667, 273, 389, 22270, 14667, 31, 203, 3639, 501, 18, 266, 19117, 375, 14667, 273, 389, 266, 19117, 375, 14667, 31, 203, 203, 3639, 3626, 5782, 281, 5033, 24899, 22270, 14667, 16, 389, 266, 19117, 375, 14667, 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 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "../../interfaces/IPendleCompoundForge.sol"; import "./../abstract/PendleMarketBase.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract PendleCompoundMarket is PendleMarketBase { using Math for uint256; using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private globalLastExchangeRate; constructor( address _governanceManager, address _xyt, address _token ) PendleMarketBase(_governanceManager, _xyt, _token) {} function _getExchangeRate() internal returns (uint256) { return IPendleCompoundForge(forge).getExchangeRate(underlyingAsset); } function _afterBootstrap() internal override { paramL = 1; globalLastExchangeRate = _getExchangeRate(); } /// @inheritdoc PendleMarketBase /* * Please refer to AaveMarket's _updateDueInterests to better understand this function * The key difference between Aave & Compound is in Compound there is no compound effect for locked in asset I.e: Only when the user use the cToken to redeem the underlyingAsset that he will enjoy the compound effect */ function _updateDueInterests(address user) internal override { // before calc the interest for users, updateParamL _updateParamL(); uint256 _paramL = paramL; uint256 userLastParamL = lastParamL[user]; if (userLastParamL == 0) { lastParamL[user] = _paramL; return; } uint256 principal = balanceOf(user); uint256 interestValuePerLP = _paramL.sub(userLastParamL); uint256 interestFromLp = principal.mul(interestValuePerLP).div(MULTIPLIER); dueInterests[user] = dueInterests[user].add(interestFromLp); lastParamL[user] = _paramL; } /// @inheritdoc PendleMarketBase // Please refer to AaveMarket's _getFirstTermAndParamR to better understand this function function _getFirstTermAndParamR(uint256 currentNYield) internal override returns (uint256 firstTerm, uint256 paramR) { firstTerm = paramL; paramR = currentNYield.sub(lastNYield); globalLastExchangeRate = _getExchangeRate(); } /// @inheritdoc PendleMarketBase function _getIncomeIndexIncreaseRate() internal override returns (uint256 increaseRate) { return _getExchangeRate().rdiv(globalLastExchangeRate).sub(Math.RONE); } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleForge.sol"; interface IPendleCompoundForge is IPendleForge { /** @dev directly get the exchangeRate from Compound */ function getExchangeRate(address _underlyingAsset) external returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "../../interfaces/IPendleData.sol"; import "../../interfaces/IPendleMarket.sol"; import "../../interfaces/IPendleForge.sol"; import "../../interfaces/IPendleMarketFactory.sol"; import "../../interfaces/IPendleYieldToken.sol"; import "../../interfaces/IPendlePausingManager.sol"; import "../../periphery/WithdrawableV2.sol"; import "../../tokens/PendleBaseToken.sol"; import "../../libraries/MarketMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** @dev HIGH LEVEL PRINCIPAL: * So most of the functions in market is only callable by Router, except view/pure functions. If a function is non view/pure and is callable by anyone, it must be explicitly stated so * Market will not do any yieldToken/baseToken transfer but instead will fill in the transfer array and router will do them instead. (This is to reduce the number of approval users need to do) * mint, burn will be done directly with users */ abstract contract PendleMarketBase is IPendleMarket, PendleBaseToken, WithdrawableV2 { using Math for uint256; using SafeMath for uint256; using SafeERC20 for IERC20; bytes32 public immutable override factoryId; address internal immutable forge; address public immutable override token; address public immutable override xyt; bool public bootstrapped; string private constant NAME = "Pendle Market"; string private constant SYMBOL = "PENDLE-LPT"; uint256 private constant MINIMUM_LIQUIDITY = 10**3; uint8 private constant DECIMALS = 18; uint256 private constant LN_PI_PLUSONE = 1562071538258; // this is equal to Math.ln(Math.PI_PLUSONE,Math.RONE) uint256 internal constant MULTIPLIER = 10**20; // variables for LP interests calc uint256 public paramL; uint256 public lastNYield; mapping(address => uint256) internal lastParamL; mapping(address => uint256) internal dueInterests; // paramK used for mintProtocolFee. ParamK = xytBal ^ xytWeight * tokenBal ^ tokenW uint256 public lastParamK; // the last block that we do curveShift uint256 public lastCurveShiftBlock; /* * The reserveData will consist of 3 variables: xytBalance, tokenBalance & xytWeight To save gas, we will pack these 3 variables into a single uint256 variable as follows: Bit 148 -> 255: xytBalance Bit 40 -> 147: tokenBalance Bit 0 -> 39: xytWeight tokenWeight = Math.RONE - xytWeight Refer to writeReserveData and readReserveData for more details */ uint256 private reserveData; uint256 private lastRelativePrice = Math.RONE; uint256 private constant MASK_148_TO_255 = type(uint256).max ^ ((1 << 148) - 1); uint256 private constant MASK_40_TO_147 = ((1 << 148) - 1) ^ ((1 << 40) - 1); uint256 private constant MASK_0_TO_39 = ((1 << 40) - 1); uint256 private constant MAX_TOKEN_RESERVE_BALANCE = (1 << 108) - 1; /* * the lockStartTime is set at the bootstrap time of the market, and will not be changed for the entire market duration Once the market has been locked, only removeMarketLiquidityDual is allowed * Why lock the market? Because when the time is very close to the end of the market, the ratio of weights are either extremely big or small, which leads to high precision error */ uint256 public lockStartTime; /* these variables are used often, so we get them once in the constructor and save gas for retrieving them afterwards */ bytes32 private immutable forgeId; address internal immutable underlyingAsset; IERC20 private immutable underlyingYieldToken; IPendleData private immutable data; IPendlePausingManager private immutable pausingManager; uint256 private immutable xytStartTime; constructor( address _governanceManager, address _xyt, address _token ) PendleBaseToken( address(IPendleYieldToken(_xyt).forge().router()), NAME, SYMBOL, DECIMALS, block.timestamp, IPendleYieldToken(_xyt).expiry() ) PermissionsV2(_governanceManager) { require(_xyt != address(0), "ZERO_ADDRESS"); require(_token != address(0), "ZERO_ADDRESS"); require(_token != IPendleYieldToken(_xyt).underlyingYieldToken(), "INVALID_TOKEN_PAIR"); IPendleForge _forge = IPendleYieldToken(_xyt).forge(); forge = address(_forge); xyt = _xyt; token = _token; forgeId = _forge.forgeId(); underlyingAsset = IPendleYieldToken(_xyt).underlyingAsset(); underlyingYieldToken = IERC20(IPendleYieldToken(_xyt).underlyingYieldToken()); data = _forge.data(); pausingManager = _forge.data().pausingManager(); xytStartTime = IPendleYieldToken(_xyt).start(); factoryId = IPendleMarketFactory(msg.sender).marketFactoryId(); address _router = address(_forge.router()); IERC20(_xyt).safeApprove(_router, type(uint256).max); IERC20(_token).safeApprove(_router, type(uint256).max); } // INVARIANT: All write functions, except for ERC20's approve(), increaseAllowance(), decreaseAllowance() // must go through this check. This means that minting/burning/transferring of LP tokens is paused too. function checkNotPaused() internal { (bool paused, ) = pausingManager.checkMarketStatus(factoryId, address(this)); require(!paused, "MARKET_PAUSED"); } /// Refer to the docs for reserveData function readReserveData() internal view returns ( uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight ) { xytBalance = (reserveData & MASK_148_TO_255) >> 148; tokenBalance = (reserveData & MASK_40_TO_147) >> 40; xytWeight = reserveData & MASK_0_TO_39; tokenWeight = Math.RONE - xytWeight; } /// parse an asset address to tokenReserve /// _asset will only be either xyt or baseToken function parseTokenReserveData(address _asset) internal view returns (TokenReserve memory tokenReserve) { (uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) = readReserveData(); if (_asset == xyt) { tokenReserve = TokenReserve(xytWeight, xytBalance); } else { tokenReserve = TokenReserve(tokenWeight, tokenBalance); } } /// pass in a tokenReserve & the type of token (through _asset), update the reserveData function updateReserveData(TokenReserve memory tokenReserve, address _asset) internal { (uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) = readReserveData(); // Basically just update the weight & bal of the corresponding token & write the reserveData again if (_asset == xyt) { (xytWeight, xytBalance) = (tokenReserve.weight, tokenReserve.balance); } else { (tokenWeight, tokenBalance) = (tokenReserve.weight, tokenReserve.balance); xytWeight = Math.RONE.sub(tokenWeight); } writeReserveData(xytBalance, tokenBalance, xytWeight); } /// Refer to the docs for reserveData function writeReserveData( uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight ) internal { require(0 < xytBalance && xytBalance <= MAX_TOKEN_RESERVE_BALANCE, "YT_BALANCE_ERROR"); require( 0 < tokenBalance && tokenBalance <= MAX_TOKEN_RESERVE_BALANCE, "TOKEN_BALANCE_ERROR" ); reserveData = (xytBalance << 148) | (tokenBalance << 40) | xytWeight; } // Only the marketEmergencyHandler can call this function, when its in emergencyMode // this will allow a spender to spend the whole balance of the specified tokens // the spender should ideally be a contract with logic for users to withdraw out their funds. function setUpEmergencyMode(address spender) external override { (, bool emergencyMode) = pausingManager.checkMarketStatus(factoryId, address(this)); require(emergencyMode, "NOT_EMERGENCY"); (address marketEmergencyHandler, , ) = pausingManager.marketEmergencyHandler(); require(msg.sender == marketEmergencyHandler, "NOT_EMERGENCY_HANDLER"); IERC20(xyt).safeApprove(spender, type(uint256).max); IERC20(token).safeApprove(spender, type(uint256).max); IERC20(underlyingYieldToken).safeApprove(spender, type(uint256).max); } function bootstrap( address user, uint256 initialXytLiquidity, uint256 initialTokenLiquidity ) external override returns (PendingTransfer[2] memory transfers, uint256 exactOutLp) { require(msg.sender == address(router), "ONLY_ROUTER"); checkNotPaused(); require(!bootstrapped, "ALREADY_BOOTSTRAPPED"); // market's lock params should be initialized at bootstrap time _initializeLock(); // at the start of the market, xytWeight = tokenWeight = Math.RONE / 2 // As such, we will write it into the reserveData writeReserveData(initialXytLiquidity, initialTokenLiquidity, Math.RONE / 2); _updateLastParamK(); // update paramK since this is the first time it's set emit Sync(initialXytLiquidity, Math.RONE / 2, initialTokenLiquidity); _afterBootstrap(); // Taking inspiration from Uniswap, we will keep MINIMUM_LIQUIDITY in the market to make sure the market is always non-empty exactOutLp = Math.sqrt(initialXytLiquidity.mul(initialTokenLiquidity)).sub( MINIMUM_LIQUIDITY ); // No one should possibly own a specific address like this 0x1 // We mint to 0x1 instead of 0x0 because sending to 0x0 is not permitted _mint(address(0x1), MINIMUM_LIQUIDITY); _mint(user, exactOutLp); transfers[0].amount = initialXytLiquidity; transfers[0].isOut = false; transfers[1].amount = initialTokenLiquidity; transfers[1].isOut = false; lastCurveShiftBlock = block.number; bootstrapped = true; } /** * @notice Join the market by specifying the desired (and max) amount of xyts * and tokens to put in. * @param _desiredXytAmount amount of XYTs user wants to contribute * @param _desiredTokenAmount amount of tokens user wants to contribute * @param _xytMinAmount min amount of XYTs user wants to be able to contribute * @param _tokenMinAmount min amount of tokens user wants to be able to contribute * @dev no curveShift to save gas because this function doesn't depend on weights of tokens * Note: the logic of this function is similar to that of Uniswap * Conditions: * checkAddRemoveSwapClaimAllowed(false) is true */ function addMarketLiquidityDual( address user, uint256 _desiredXytAmount, uint256 _desiredTokenAmount, uint256 _xytMinAmount, uint256 _tokenMinAmount ) external override returns (PendingTransfer[2] memory transfers, uint256 lpOut) { checkAddRemoveSwapClaimAllowed(false); // mint protocol fees before k is changed by a non-swap event (add liquidity) _mintProtocolFees(); (uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData(); uint256 amountXytUsed; uint256 amountTokenUsed = _desiredXytAmount.mul(tokenBalance).div(xytBalance); if (amountTokenUsed <= _desiredTokenAmount) { // using _desiredXytAmount to determine the LP and add liquidity require(amountTokenUsed >= _tokenMinAmount, "INSUFFICIENT_TOKEN_AMOUNT"); amountXytUsed = _desiredXytAmount; lpOut = _desiredXytAmount.mul(totalSupply()).div(xytBalance); } else { // using _desiredTokenAmount to determine the LP and add liquidity amountXytUsed = _desiredTokenAmount.mul(xytBalance).div(tokenBalance); require(amountXytUsed >= _xytMinAmount, "INSUFFICIENT_YT_AMOUNT"); amountTokenUsed = _desiredTokenAmount; lpOut = _desiredTokenAmount.mul(totalSupply()).div(tokenBalance); } xytBalance = xytBalance.add(amountXytUsed); transfers[0].amount = amountXytUsed; transfers[0].isOut = false; tokenBalance = tokenBalance.add(amountTokenUsed); transfers[1].amount = amountTokenUsed; transfers[1].isOut = false; writeReserveData(xytBalance, tokenBalance, xytWeight); _updateLastParamK(); // update paramK since it has changed due to a non-swap event // Mint LP directly to the user _mint(user, lpOut); emit Sync(xytBalance, xytWeight, tokenBalance); } /** * @notice Join the market by deposit token (single) and get liquidity token * need to specify the desired amount of contributed token (xyt or token) * and minimum output liquidity token * @param _inToken address of token (xyt or token) user wants to contribute * @param _exactIn amount of tokens (xyt or token) user wants to contribute * @param _minOutLp min amount of liquidity token user expect to receive * @dev curveShift needed since function operation relies on weights */ function addMarketLiquiditySingle( address user, address _inToken, uint256 _exactIn, uint256 _minOutLp ) external override returns (PendingTransfer[2] memory transfers, uint256 exactOutLp) { checkAddRemoveSwapClaimAllowed(false); // mint protocol fees before k is changed by a non-swap event (add liquidity) _mintProtocolFees(); _curveShift(); /* * Note that in theory we could do another _mintProtocolFee in this function to take a portion of the swap fees for the implicit swap of this operation * However, we have decided to not charge the protocol fees on the swap fees for this operation. * The user will still pay the swap fees, just that all the swap fees in the implicit swap will all go back to the market (and shared among the LP holders) */ TokenReserve memory inTokenReserve = parseTokenReserveData(_inToken); uint256 totalLp = totalSupply(); // Calc out amount of LP token. exactOutLp = MarketMath._calcOutAmountLp( _exactIn, inTokenReserve, data.swapFee(), totalLp ); require(exactOutLp >= _minOutLp, "HIGH_LP_OUT_LIMIT"); // Update reserves and operate underlying LP and inToken. inTokenReserve.balance = inTokenReserve.balance.add(_exactIn); transfers[0].amount = _exactIn; transfers[0].isOut = false; // repack data updateReserveData(inTokenReserve, _inToken); _updateLastParamK(); // update paramK since it has changed not due to swap // Mint and push LP token. _mint(user, exactOutLp); (uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData(); // unpack data emit Sync(xytBalance, xytWeight, tokenBalance); } /** * @notice Exit the market by putting in the desired amount of LP tokens * and getting back XYT and pair tokens. * @dev no curveShift to save gas because this function doesn't depend on weights of tokens * @dev this function will never be locked since we always let users withdraw their funds. That's why we skip time check in checkAddRemoveSwapClaimAllowed */ function removeMarketLiquidityDual( address user, uint256 _inLp, uint256 _minOutXyt, uint256 _minOutToken ) external override returns (PendingTransfer[2] memory transfers) { checkAddRemoveSwapClaimAllowed(true); // mint protocol fees before k is changed by a non-swap event (remove liquidity) _mintProtocolFees(); uint256 totalLp = totalSupply(); (uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData(); // unpack data // Calc and withdraw xyt token. uint256 xytOut = _inLp.mul(xytBalance).div(totalLp); uint256 tokenOut = _inLp.mul(tokenBalance).div(totalLp); require(tokenOut >= _minOutToken, "INSUFFICIENT_TOKEN_OUT"); require(xytOut >= _minOutXyt, "INSUFFICIENT_YT_OUT"); xytBalance = xytBalance.sub(xytOut); tokenBalance = tokenBalance.sub(tokenOut); transfers[0].amount = xytOut; transfers[0].isOut = true; transfers[1].amount = tokenOut; transfers[1].isOut = true; writeReserveData(xytBalance, tokenBalance, xytWeight); // repack data _updateLastParamK(); // update paramK since it has changed due to a non-swap event _burn(user, _inLp); emit Sync(xytBalance, xytWeight, tokenBalance); } /** * @notice Exit the market by putting in the desired amount of LP tokens * and getting back XYT or pair tokens. * @param _outToken address of the token that user wants to get back * @param _inLp the exact amount of liquidity token that user wants to put back * @param _minOutAmountToken the minimum of token that user wants to get back * @dev curveShift needed since function operation relies on weights */ function removeMarketLiquiditySingle( address user, address _outToken, uint256 _inLp, uint256 _minOutAmountToken ) external override returns (PendingTransfer[2] memory transfers) { checkAddRemoveSwapClaimAllowed(false); // mint protocol fees before k is changed by a non-swap event (remove liquidity) _mintProtocolFees(); _curveShift(); /* * Note that in theory we should do another _mintProtocolFee in this function since this add single involves an implicit swap operation * The reason we don't do that is same as in addMarketLiquiditySingle */ TokenReserve memory outTokenReserve = parseTokenReserveData(_outToken); uint256 swapFee = data.swapFee(); uint256 totalLp = totalSupply(); uint256 outAmountToken = MarketMath._calcOutAmountToken(outTokenReserve, totalLp, _inLp, swapFee); require(outAmountToken >= _minOutAmountToken, "INSUFFICIENT_TOKEN_OUT"); outTokenReserve.balance = outTokenReserve.balance.sub(outAmountToken); transfers[0].amount = outAmountToken; transfers[0].isOut = true; updateReserveData(outTokenReserve, _outToken); _updateLastParamK(); // update paramK since it has changed by a non-swap event _burn(user, _inLp); (uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData(); // unpack data emit Sync(xytBalance, xytWeight, tokenBalance); } function swapExactIn( address inToken, uint256 inAmount, address outToken, uint256 minOutAmount ) external override returns (uint256 outAmount, PendingTransfer[2] memory transfers) { checkAddRemoveSwapClaimAllowed(false); // We only need to do _mintProtocolFees if there is a curveShift that follows if (checkNeedCurveShift()) { _mintProtocolFees(); _curveShift(); _updateLastParamK(); // update paramK since it has changed due to a non-swap event } TokenReserve memory inTokenReserve = parseTokenReserveData(inToken); TokenReserve memory outTokenReserve = parseTokenReserveData(outToken); // calc out amount of token to be swapped out outAmount = MarketMath._calcExactOut( inTokenReserve, outTokenReserve, inAmount, data.swapFee() ); require(outAmount >= minOutAmount, "HIGH_OUT_LIMIT"); inTokenReserve.balance = inTokenReserve.balance.add(inAmount); outTokenReserve.balance = outTokenReserve.balance.sub(outAmount); // repack data updateReserveData(inTokenReserve, inToken); updateReserveData(outTokenReserve, outToken); // no update paramK since it has changed but due to swap transfers[0].amount = inAmount; transfers[0].isOut = false; transfers[1].amount = outAmount; transfers[1].isOut = true; (uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData(); // unpack data emit Sync(xytBalance, xytWeight, tokenBalance); } function swapExactOut( address inToken, uint256 maxInAmount, address outToken, uint256 outAmount ) external override returns (uint256 inAmount, PendingTransfer[2] memory transfers) { checkAddRemoveSwapClaimAllowed(false); // We only need to do _mintProtocolFees if there is a curveShift that follows if (checkNeedCurveShift()) { _mintProtocolFees(); _curveShift(); _updateLastParamK(); // update paramK since it has changed due to a non-swap event } TokenReserve memory inTokenReserve = parseTokenReserveData(inToken); TokenReserve memory outTokenReserve = parseTokenReserveData(outToken); // Calc in amount. inAmount = MarketMath._calcExactIn( inTokenReserve, outTokenReserve, outAmount, data.swapFee() ); require(inAmount <= maxInAmount, "LOW_IN_LIMIT"); inTokenReserve.balance = inTokenReserve.balance.add(inAmount); outTokenReserve.balance = outTokenReserve.balance.sub(outAmount); // repack data updateReserveData(inTokenReserve, inToken); updateReserveData(outTokenReserve, outToken); // no update paramK since it has changed but due to swap transfers[0].amount = inAmount; transfers[0].isOut = false; transfers[1].amount = outAmount; transfers[1].isOut = true; (uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) = readReserveData(); // unpack data emit Sync(xytBalance, xytWeight, tokenBalance); } /** * @notice for user to claim their interest as holder of underlyingYield token * @param user user's address * @dev only can claim through router (included in checkAddRemoveSwapClaimAllowed) * We skip time check in checkAddRemoveSwapClaimAllowed because users can always claim interests * Since the Router has already had Reentrancy protection, we don't need one here */ function redeemLpInterests(address user) external override returns (uint256 interests) { checkAddRemoveSwapClaimAllowed(true); interests = _beforeTransferDueInterests(user); _safeTransferYieldToken(user, interests); } /** * @notice get the most up-to-date reserveData of the market by doing a dry curveShift */ function getReserves() external view override returns ( uint256 xytBalance, uint256 xytWeight, uint256 tokenBalance, uint256 tokenWeight, uint256 currentBlock ) { (xytBalance, tokenBalance, xytWeight, tokenWeight) = readReserveData(); if (checkNeedCurveShift()) { (xytWeight, tokenWeight, ) = _updateWeightDry(); } currentBlock = block.number; } /** * @notice update the weights of the market */ function _updateWeight() internal { (uint256 xytBalance, uint256 tokenBalance, , ) = readReserveData(); // unpack data (uint256 xytWeightUpdated, , uint256 currentRelativePrice) = _updateWeightDry(); writeReserveData(xytBalance, tokenBalance, xytWeightUpdated); // repack data lastRelativePrice = currentRelativePrice; } // do the weight update calculation but don't update the token reserve memory function _updateWeightDry() internal view returns ( uint256 xytWeightUpdated, uint256 tokenWeightUpdated, uint256 currentRelativePrice ) { // get current timestamp currentTime uint256 currentTime = block.timestamp; uint256 endTime = expiry; uint256 startTime = xytStartTime; uint256 duration = endTime - startTime; (, , uint256 xytWeight, uint256 tokenWeight) = readReserveData(); // unpack data uint256 timeLeft; if (endTime >= currentTime) { timeLeft = endTime - currentTime; } else { timeLeft = 0; } // get time_to_mature = (endTime - currentTime) / (endTime - startTime) uint256 timeToMature = Math.rdiv(timeLeft * Math.RONE, duration * Math.RONE); // get price for now = ln(3.14 * t + 1) / ln(4.14) currentRelativePrice = Math.rdiv( Math.ln(Math.rmul(Math.PI, timeToMature).add(Math.RONE), Math.RONE), LN_PI_PLUSONE ); uint256 r = Math.rdiv(currentRelativePrice, lastRelativePrice); require(Math.RONE >= r, "MATH_ERROR"); uint256 thetaNumerator = Math.rmul(Math.rmul(xytWeight, tokenWeight), Math.RONE.sub(r)); uint256 thetaDenominator = Math.rmul(r, xytWeight).add(tokenWeight); // calc weight changes theta uint256 theta = Math.rdiv(thetaNumerator, thetaDenominator); xytWeightUpdated = xytWeight.sub(theta); tokenWeightUpdated = tokenWeight.add(theta); } /* To add/remove/swap/claim, the market must have been * bootstrapped * only Router can call it * if the function is not removeMarketLiquidityDual, then must check the market hasn't been locked yet */ function checkAddRemoveSwapClaimAllowed(bool skipOpenCheck) internal { checkNotPaused(); require(bootstrapped, "NOT_BOOTSTRAPPED"); require(msg.sender == address(router), "ONLY_ROUTER"); if (!skipOpenCheck) { require(block.timestamp < lockStartTime, "MARKET_LOCKED"); } } //curve shift will be called before any calculation using weight //Note: there must be a _mintProtocolFees() before calling _curveShift() function _curveShift() internal { if (!checkNeedCurveShift()) return; _updateWeight(); lastCurveShiftBlock = block.number; } /** @notice To be called before the dueInterest of any users is redeemed */ function _beforeTransferDueInterests(address user) internal returns (uint256 amountOut) { _updateDueInterests(user); amountOut = dueInterests[user]; dueInterests[user] = 0; // Use subMax0 to handle the extreme case of the market lacking a few wei of tokens to send out lastNYield = lastNYield.subMax0(amountOut); } /** * We will only updateParamL if the normalisedIncome / exchangeRate has increased more than a delta * This delta is expected to be very small */ function checkNeedUpdateParamL() internal returns (bool) { return _getIncomeIndexIncreaseRate() > data.interestUpdateRateDeltaForMarket(); } /** * We will only do curveShift() once every curveShiftBlockDelta blocks */ function checkNeedCurveShift() internal view returns (bool) { return block.number > lastCurveShiftBlock.add(data.curveShiftBlockDelta()); } /** * @notice use to updateParamL. Must only be called by _updateDueInterests * ParamL can be thought of as an always-increase incomeIndex for 1 LP Consideration: * Theoretically we have to updateParamL whenever the _updateDueInterests is called, since the external incomeIndex (normalisedIncome/exchangeRate) is always increasing, and there are always interests to be claimed * Yet, if we do so, the amount of interests to be claimed maybe negligible while the amount of gas spent is tremendous (100k~200k last time we checked) => Caching is actually beneficial to user * The users may lose some negligible amount of interest when they do removeLiquidity or transfer LP to others (to be exact, they will lose NO MORE THAN interestUpdateRateDeltaForMarket%). In exchange, they will save a lot of gas. * If we assume the yearly interest rate is 10%, and we would like to only update the market's interest every one hour, interestUpdateRateDeltaForMarket% = 1.10 ^ (1/ (365*24)) - 1 = 0.00108802167011 % * The correctness of caching can be thought of like this: We just pretend that there are only income once in a while, and when that income come, they will come in large amount, and we will distribute them fairly to all users */ function _updateParamL() internal { if (!checkNeedUpdateParamL()) return; // redeem the interest from XYT router.redeemDueInterests(forgeId, underlyingAsset, expiry, address(this)); uint256 currentNYield = underlyingYieldToken.balanceOf(address(this)); (uint256 firstTerm, uint256 paramR) = _getFirstTermAndParamR(currentNYield); uint256 secondTerm; /* * paramR can be thought of as the amount of interest earned by the market (but excluding the compound effect). paramR is normally small & totalSupply is normally much larger so we need to multiply them with MULTIPLIER */ if (totalSupply() != 0) secondTerm = paramR.mul(MULTIPLIER).div(totalSupply()); // firstTerm & secondTerm are not the best names, but please refer to AMM specs // to understand the meaning of these 2 params paramL = firstTerm.add(secondTerm); lastNYield = currentNYield; } // before we send LPs, we need to update LP interests for both the to and from addresses function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { super._beforeTokenTransfer(from, to, amount); checkNotPaused(); if (from != address(0)) _updateDueInterests(from); if (to != address(0)) _updateDueInterests(to); } /** @dev Must be the only way to transfer aToken/cToken out // Please refer to _safeTransfer of PendleForgeBase for the rationale of this function */ function _safeTransferYieldToken(address _user, uint256 _amount) internal { if (_amount == 0) return; _amount = Math.min(_amount, underlyingYieldToken.balanceOf(address(this))); underlyingYieldToken.safeTransfer(_user, _amount); } /** * @notice _initialize the lock of the market. Must only be called in bootstrap */ function _initializeLock() internal { uint256 duration = expiry.sub(xytStartTime); // market expiry = xyt expiry uint256 lockDuration = duration.mul(data.lockNumerator()).div(data.lockDenominator()); lockStartTime = expiry.sub(lockDuration); } /** @notice _mint new LP for protocol fee. Mint them directly to the treasury @dev this function should be very similar to Uniswap */ function _mintProtocolFees() internal { uint256 feeRatio = data.protocolSwapFee(); uint256 _lastParamK = lastParamK; if (feeRatio > 0) { if (_lastParamK != 0) { uint256 k = _calcParamK(); if (k > _lastParamK) { uint256 numer = totalSupply().mul(k.sub(_lastParamK)); uint256 denom = Math.RONE.sub(feeRatio).mul(k).div(feeRatio).add(_lastParamK); uint256 liquidity = numer / denom; address treasury = data.treasury(); if (liquidity > 0) { _mint(treasury, liquidity); } } } } else if (_lastParamK != 0) { // if fee is turned off, we need to reset lastParamK as well lastParamK = 0; } } /** Equation for paramK: paramK = xytBal ^ xytWeight * tokenBal ^ tokenW * @dev must be called whenever the above equation changes but not due to a swapping action I.e: after add/remove/bootstrap liquidity or curveShift */ function _updateLastParamK() internal { if (data.protocolSwapFee() == 0) return; lastParamK = _calcParamK(); } /** * @notice calc the value of paramK. The formula for this can be referred in the AMM specs */ function _calcParamK() internal view returns (uint256 paramK) { (uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) = readReserveData(); paramK = Math .rpow(xytBalance.toFP(), xytWeight) .rmul(Math.rpow(tokenBalance.toFP(), tokenWeight)) .toInt(); } function _allowedToWithdraw(address _token) internal view override returns (bool allowed) { allowed = _token != xyt && _token != token && _token != address(this) && _token != address(underlyingYieldToken); } function _afterBootstrap() internal virtual; /** @notice update the LP interest for users (before their balances of LP changes) @dev This must be called before any transfer / mint/ burn action of LP (and this has been implemented in the beforeTokenTransfer of this contract) */ function _updateDueInterests(address user) internal virtual; /// @notice Get params to update paramL. Must only be called by updateParamL function _getFirstTermAndParamR(uint256 currentNYield) internal virtual returns (uint256 firstTerm, uint256 paramR); /// @notice Get the increase rate of normalisedIncome / exchangeRate function _getIncomeIndexIncreaseRate() internal virtual returns (uint256 increaseRate); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; import "./IPendleRewardManager.sol"; import "./IPendleYieldContractDeployer.sol"; import "./IPendleData.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleForge { /** * @dev Emitted when the Forge has minted the OT and XYT tokens. * @param forgeId The forgeId * @param underlyingAsset The address of the underlying yield token. * @param expiry The expiry of the XYT token * @param amountToTokenize The amount of yield bearing assets to tokenize * @param amountTokenMinted The amount of OT/XYT minted **/ event MintYieldTokens( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amountToTokenize, uint256 amountTokenMinted, address indexed user ); /** * @dev Emitted when the Forge has created new yield token contracts. * @param forgeId The forgeId * @param underlyingAsset The address of the underlying asset. * @param expiry The date in epoch time when the contract will expire. * @param ot The address of the ownership token. * @param xyt The address of the new future yield token. **/ event NewYieldContracts( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, address ot, address xyt, address yieldBearingAsset ); /** * @dev Emitted when the Forge has redeemed the OT and XYT tokens. * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param amountToRedeem The amount of OT to be redeemed. * @param redeemedAmount The amount of yield token received **/ event RedeemYieldToken( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amountToRedeem, uint256 redeemedAmount, address indexed user ); /** * @dev Emitted when interest claim is settled * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param user Interest receiver Address * @param amount The amount of interest claimed **/ event DueInterestsSettled( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amount, uint256 forgeFeeAmount, address indexed user ); /** * @dev Emitted when forge fee is withdrawn * @param forgeId The forgeId * @param underlyingAsset the address of the underlying asset * @param expiry The expiry of the XYT token * @param amount The amount of interest claimed **/ event ForgeFeeWithdrawn( bytes32 forgeId, address indexed underlyingAsset, uint256 indexed expiry, uint256 amount ); function setUpEmergencyMode( address _underlyingAsset, uint256 _expiry, address spender ) external; function newYieldContracts(address underlyingAsset, uint256 expiry) external returns (address ot, address xyt); function redeemAfterExpiry( address user, address underlyingAsset, uint256 expiry ) external returns (uint256 redeemedAmount); function redeemDueInterests( address user, address underlyingAsset, uint256 expiry ) external returns (uint256 interests); function updateDueInterests( address underlyingAsset, uint256 expiry, address user ) external; function updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) external; function redeemUnderlying( address user, address underlyingAsset, uint256 expiry, uint256 amountToRedeem ) external returns (uint256 redeemedAmount); function mintOtAndXyt( address underlyingAsset, uint256 expiry, uint256 amountToTokenize, address to ) external returns ( address ot, address xyt, uint256 amountTokenMinted ); function withdrawForgeFee(address underlyingAsset, uint256 expiry) external; function getYieldBearingToken(address underlyingAsset) external returns (address); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); function data() external view returns (IPendleData); function rewardManager() external view returns (IPendleRewardManager); function yieldContractDeployer() external view returns (IPendleYieldContractDeployer); function rewardToken() external view returns (IERC20); /** * @notice Gets the bytes32 ID of the forge. * @return Returns the forge and protocol identifier. **/ function forgeId() external view returns (bytes32); function dueInterests( address _underlyingAsset, uint256 expiry, address _user ) external view returns (uint256); function yieldTokenHolders(address _underlyingAsset, uint256 _expiry) external view returns (address yieldTokenHolder); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma abicoder v2; import "../interfaces/IWETH.sol"; import "./IPendleData.sol"; import "../libraries/PendleStructs.sol"; import "./IPendleMarketFactory.sol"; interface IPendleRouter { /** * @notice Emitted when a market for a future yield token and an ERC20 token is created. * @param marketFactoryId Forge identifier. * @param xyt The address of the tokenized future yield token as the base asset. * @param token The address of an ERC20 token as the quote asset. * @param market The address of the newly created market. **/ event MarketCreated( bytes32 marketFactoryId, address indexed xyt, address indexed token, address indexed market ); /** * @notice Emitted when a swap happens on the market. * @param trader The address of msg.sender. * @param inToken The input token. * @param outToken The output token. * @param exactIn The exact amount being traded. * @param exactOut The exact amount received. * @param market The market address. **/ event SwapEvent( address indexed trader, address inToken, address outToken, uint256 exactIn, uint256 exactOut, address market ); /** * @dev Emitted when user adds liquidity * @param sender The user who added liquidity. * @param token0Amount the amount of token0 (xyt) provided by user * @param token1Amount the amount of token1 provided by user * @param market The market address. * @param exactOutLp The exact LP minted */ event Join( address indexed sender, uint256 token0Amount, uint256 token1Amount, address market, uint256 exactOutLp ); /** * @dev Emitted when user removes liquidity * @param sender The user who removed liquidity. * @param token0Amount the amount of token0 (xyt) given to user * @param token1Amount the amount of token1 given to user * @param market The market address. * @param exactInLp The exact Lp to remove */ event Exit( address indexed sender, uint256 token0Amount, uint256 token1Amount, address market, uint256 exactInLp ); /** * @notice Gets a reference to the PendleData contract. * @return Returns the data contract reference. **/ function data() external view returns (IPendleData); /** * @notice Gets a reference of the WETH9 token contract address. * @return WETH token reference. **/ function weth() external view returns (IWETH); /*********** * FORGE * ***********/ function newYieldContracts( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (address ot, address xyt); function redeemAfterExpiry( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (uint256 redeemedAmount); function redeemDueInterests( bytes32 forgeId, address underlyingAsset, uint256 expiry, address user ) external returns (uint256 interests); function redeemUnderlying( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountToRedeem ) external returns (uint256 redeemedAmount); function renewYield( bytes32 forgeId, uint256 oldExpiry, address underlyingAsset, uint256 newExpiry, uint256 renewalRate ) external returns ( uint256 redeemedAmount, uint256 amountRenewed, address ot, address xyt, uint256 amountTokenMinted ); function tokenizeYield( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountToTokenize, address to ) external returns ( address ot, address xyt, uint256 amountTokenMinted ); /*********** * MARKET * ***********/ function addMarketLiquidityDual( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _desiredXytAmount, uint256 _desiredTokenAmount, uint256 _xytMinAmount, uint256 _tokenMinAmount ) external payable returns ( uint256 amountXytUsed, uint256 amountTokenUsed, uint256 lpOut ); function addMarketLiquiditySingle( bytes32 marketFactoryId, address xyt, address token, bool forXyt, uint256 exactInAsset, uint256 minOutLp ) external payable returns (uint256 exactOutLp); function removeMarketLiquidityDual( bytes32 marketFactoryId, address xyt, address token, uint256 exactInLp, uint256 minOutXyt, uint256 minOutToken ) external returns (uint256 exactOutXyt, uint256 exactOutToken); function removeMarketLiquiditySingle( bytes32 marketFactoryId, address xyt, address token, bool forXyt, uint256 exactInLp, uint256 minOutAsset ) external returns (uint256 exactOutXyt, uint256 exactOutToken); /** * @notice Creates a market given a protocol ID, future yield token, and an ERC20 token. * @param marketFactoryId Market Factory identifier. * @param xyt Token address of the future yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the address of the newly created market. **/ function createMarket( bytes32 marketFactoryId, address xyt, address token ) external returns (address market); function bootstrapMarket( bytes32 marketFactoryId, address xyt, address token, uint256 initialXytLiquidity, uint256 initialTokenLiquidity ) external payable; function swapExactIn( address tokenIn, address tokenOut, uint256 inTotalAmount, uint256 minOutTotalAmount, bytes32 marketFactoryId ) external payable returns (uint256 outTotalAmount); function swapExactOut( address tokenIn, address tokenOut, uint256 outTotalAmount, uint256 maxInTotalAmount, bytes32 marketFactoryId ) external payable returns (uint256 inTotalAmount); function redeemLpInterests(address market, address user) external returns (uint256 interests); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleRewardManager { event UpdateFrequencySet(address[], uint256[]); event SkippingRewardsSet(bool); event DueRewardsSettled( bytes32 forgeId, address underlyingAsset, uint256 expiry, uint256 amountOut, address user ); function redeemRewards( address _underlyingAsset, uint256 _expiry, address _user ) external returns (uint256 dueRewards); function updatePendingRewards( address _underlyingAsset, uint256 _expiry, address _user ) external; function updateParamLManual(address _underlyingAsset, uint256 _expiry) external; function setUpdateFrequency( address[] calldata underlyingAssets, uint256[] calldata frequencies ) external; function setSkippingRewards(bool skippingRewards) external; function forgeId() external returns (bytes32); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleYieldContractDeployer { function forgeId() external returns (bytes32); function forgeOwnershipToken( address _underlyingAsset, string memory _name, string memory _symbol, uint8 _decimals, uint256 _expiry ) external returns (address ot); function forgeFutureYieldToken( address _underlyingAsset, string memory _name, string memory _symbol, uint8 _decimals, uint256 _expiry ) external returns (address xyt); function deployYieldTokenHolder(address yieldToken, uint256 expiry) external returns (address yieldTokenHolder); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; import "./IPendleYieldToken.sol"; import "./IPendlePausingManager.sol"; import "./IPendleMarket.sol"; interface IPendleData { /** * @notice Emitted when validity of a forge-factory pair is updated * @param _forgeId the forge id * @param _marketFactoryId the market factory id * @param _valid valid or not **/ event ForgeFactoryValiditySet(bytes32 _forgeId, bytes32 _marketFactoryId, bool _valid); /** * @notice Emitted when Pendle and PendleFactory addresses have been updated. * @param treasury The address of the new treasury contract. **/ event TreasurySet(address treasury); /** * @notice Emitted when LockParams is changed **/ event LockParamsSet(uint256 lockNumerator, uint256 lockDenominator); /** * @notice Emitted when ExpiryDivisor is changed **/ event ExpiryDivisorSet(uint256 expiryDivisor); /** * @notice Emitted when forge fee is changed **/ event ForgeFeeSet(uint256 forgeFee); /** * @notice Emitted when interestUpdateRateDeltaForMarket is changed * @param interestUpdateRateDeltaForMarket new interestUpdateRateDeltaForMarket setting **/ event InterestUpdateRateDeltaForMarketSet(uint256 interestUpdateRateDeltaForMarket); /** * @notice Emitted when market fees are changed * @param _swapFee new swapFee setting * @param _protocolSwapFee new protocolSwapFee setting **/ event MarketFeesSet(uint256 _swapFee, uint256 _protocolSwapFee); /** * @notice Emitted when the curve shift block delta is changed * @param _blockDelta new block delta setting **/ event CurveShiftBlockDeltaSet(uint256 _blockDelta); /** * @dev Emitted when new forge is added * @param marketFactoryId Human Readable Market Factory ID in Bytes * @param marketFactoryAddress The Market Factory Address */ event NewMarketFactory(bytes32 indexed marketFactoryId, address indexed marketFactoryAddress); /** * @notice Set/update validity of a forge-factory pair * @param _forgeId the forge id * @param _marketFactoryId the market factory id * @param _valid valid or not **/ function setForgeFactoryValidity( bytes32 _forgeId, bytes32 _marketFactoryId, bool _valid ) external; /** * @notice Sets the PendleTreasury contract addresses. * @param newTreasury Address of new treasury contract. **/ function setTreasury(address newTreasury) external; /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function pausingManager() external view returns (IPendlePausingManager); /** * @notice Gets the treasury contract address where fees are being sent to. * @return Address of the treasury contract. **/ function treasury() external view returns (address); /*********** * FORGE * ***********/ /** * @notice Emitted when a forge for a protocol is added. * @param forgeId Forge and protocol identifier. * @param forgeAddress The address of the added forge. **/ event ForgeAdded(bytes32 indexed forgeId, address indexed forgeAddress); /** * @notice Adds a new forge for a protocol. * @param forgeId Forge and protocol identifier. * @param forgeAddress The address of the added forge. **/ function addForge(bytes32 forgeId, address forgeAddress) external; /** * @notice Store new OT and XYT details. * @param forgeId Forge and protocol identifier. * @param ot The address of the new XYT. * @param xyt The address of the new XYT. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. **/ function storeTokens( bytes32 forgeId, address ot, address xyt, address underlyingAsset, uint256 expiry ) external; /** * @notice Set a new forge fee * @param _forgeFee new forge fee **/ function setForgeFee(uint256 _forgeFee) external; /** * @notice Gets the OT and XYT tokens. * @param forgeId Forge and protocol identifier. * @param underlyingYieldToken Token address of the underlying yield token. * @param expiry Yield contract expiry in epoch time. * @return ot The OT token references. * @return xyt The XYT token references. **/ function getPendleYieldTokens( bytes32 forgeId, address underlyingYieldToken, uint256 expiry ) external view returns (IPendleYieldToken ot, IPendleYieldToken xyt); /** * @notice Gets a forge given the identifier. * @param forgeId Forge and protocol identifier. * @return forgeAddress Returns the forge address. **/ function getForgeAddress(bytes32 forgeId) external view returns (address forgeAddress); /** * @notice Checks if an XYT token is valid. * @param forgeId The forgeId of the forge. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. * @return True if valid, false otherwise. **/ function isValidXYT( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (bool); /** * @notice Checks if an OT token is valid. * @param forgeId The forgeId of the forge. * @param underlyingAsset Token address of the underlying asset. * @param expiry Yield contract expiry in epoch time. * @return True if valid, false otherwise. **/ function isValidOT( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (bool); function validForgeFactoryPair(bytes32 _forgeId, bytes32 _marketFactoryId) external view returns (bool); /** * @notice Gets a reference to a specific OT. * @param forgeId Forge and protocol identifier. * @param underlyingYieldToken Token address of the underlying yield token. * @param expiry Yield contract expiry in epoch time. * @return ot Returns the reference to an OT. **/ function otTokens( bytes32 forgeId, address underlyingYieldToken, uint256 expiry ) external view returns (IPendleYieldToken ot); /** * @notice Gets a reference to a specific XYT. * @param forgeId Forge and protocol identifier. * @param underlyingAsset Token address of the underlying asset * @param expiry Yield contract expiry in epoch time. * @return xyt Returns the reference to an XYT. **/ function xytTokens( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external view returns (IPendleYieldToken xyt); /*********** * MARKET * ***********/ event MarketPairAdded(address indexed market, address indexed xyt, address indexed token); function addMarketFactory(bytes32 marketFactoryId, address marketFactoryAddress) external; function isMarket(address _addr) external view returns (bool result); function isXyt(address _addr) external view returns (bool result); function addMarket( bytes32 marketFactoryId, address xyt, address token, address market ) external; function setMarketFees(uint256 _swapFee, uint256 _protocolSwapFee) external; function setInterestUpdateRateDeltaForMarket(uint256 _interestUpdateRateDeltaForMarket) external; function setLockParams(uint256 _lockNumerator, uint256 _lockDenominator) external; function setExpiryDivisor(uint256 _expiryDivisor) external; function setCurveShiftBlockDelta(uint256 _blockDelta) external; /** * @notice Displays the number of markets currently existing. * @return Returns markets length, **/ function allMarketsLength() external view returns (uint256); function forgeFee() external view returns (uint256); function interestUpdateRateDeltaForMarket() external view returns (uint256); function expiryDivisor() external view returns (uint256); function lockNumerator() external view returns (uint256); function lockDenominator() external view returns (uint256); function swapFee() external view returns (uint256); function protocolSwapFee() external view returns (uint256); function curveShiftBlockDelta() external view returns (uint256); function getMarketByIndex(uint256 index) external view returns (address market); /** * @notice Gets a market given a future yield token and an ERC20 token. * @param xyt Token address of the future yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the market address. **/ function getMarket( bytes32 marketFactoryId, address xyt, address token ) external view returns (address market); /** * @notice Gets a market factory given the identifier. * @param marketFactoryId MarketFactory identifier. * @return marketFactoryAddress Returns the factory address. **/ function getMarketFactoryAddress(bytes32 marketFactoryId) external view returns (address marketFactoryAddress); function getMarketFromKey( address xyt, address token, bytes32 marketFactoryId ) external view returns (address market); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; struct TokenReserve { uint256 weight; uint256 balance; } struct PendingTransfer { uint256 amount; bool isOut; } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "./IPendleRouter.sol"; interface IPendleMarketFactory { /** * @notice Creates a market given a protocol ID, future yield token, and an ERC20 token. * @param xyt Token address of the futuonlyCorere yield token as base asset. * @param token Token address of an ERC20 token as quote asset. * @return market Returns the address of the newly created market. **/ function createMarket(address xyt, address token) external returns (address market); /** * @notice Gets a reference to the PendleRouter contract. * @return Returns the router contract reference. **/ function router() external view returns (IPendleRouter); function marketFactoryId() external view returns (bytes32); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IPendleBaseToken.sol"; import "./IPendleForge.sol"; interface IPendleYieldToken is IERC20, IPendleBaseToken { /** * @notice Emitted when burning OT or XYT tokens. * @param user The address performing the burn. * @param amount The amount to be burned. **/ event Burn(address indexed user, uint256 amount); /** * @notice Emitted when minting OT or XYT tokens. * @param user The address performing the mint. * @param amount The amount to be minted. **/ event Mint(address indexed user, uint256 amount); /** * @notice Burns OT or XYT tokens from user, reducing the total supply. * @param user The address performing the burn. * @param amount The amount to be burned. **/ function burn(address user, uint256 amount) external; /** * @notice Mints new OT or XYT tokens for user, increasing the total supply. * @param user The address to send the minted tokens. * @param amount The amount to be minted. **/ function mint(address user, uint256 amount) external; /** * @notice Gets the forge address of the PendleForge contract for this yield token. * @return Retuns the forge address. **/ function forge() external view returns (IPendleForge); /** * @notice Returns the address of the underlying asset. * @return Returns the underlying asset address. **/ function underlyingAsset() external view returns (address); /** * @notice Returns the address of the underlying yield token. * @return Returns the underlying yield token address. **/ function underlyingYieldToken() external view returns (address); /** * @notice let the router approve itself to spend OT/XYT/LP from any wallet * @param user user to approve **/ function approveRouter(address user) external; } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendlePausingManager { event AddPausingAdmin(address admin); event RemovePausingAdmin(address admin); event PendingForgeEmergencyHandler(address _pendingForgeHandler); event PendingMarketEmergencyHandler(address _pendingMarketHandler); event PendingLiqMiningEmergencyHandler(address _pendingLiqMiningHandler); event ForgeEmergencyHandlerSet(address forgeEmergencyHandler); event MarketEmergencyHandlerSet(address marketEmergencyHandler); event LiqMiningEmergencyHandlerSet(address liqMiningEmergencyHandler); event PausingManagerLocked(); event ForgeHandlerLocked(); event MarketHandlerLocked(); event LiqMiningHandlerLocked(); event SetForgePaused(bytes32 forgeId, bool settingToPaused); event SetForgeAssetPaused(bytes32 forgeId, address underlyingAsset, bool settingToPaused); event SetForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool settingToPaused ); event SetForgeLocked(bytes32 forgeId); event SetForgeAssetLocked(bytes32 forgeId, address underlyingAsset); event SetForgeAssetExpiryLocked(bytes32 forgeId, address underlyingAsset, uint256 expiry); event SetMarketFactoryPaused(bytes32 marketFactoryId, bool settingToPaused); event SetMarketPaused(bytes32 marketFactoryId, address market, bool settingToPaused); event SetMarketFactoryLocked(bytes32 marketFactoryId); event SetMarketLocked(bytes32 marketFactoryId, address market); event SetLiqMiningPaused(address liqMiningContract, bool settingToPaused); event SetLiqMiningLocked(address liqMiningContract); function forgeEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function marketEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function liqMiningEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function permLocked() external view returns (bool); function permForgeHandlerLocked() external view returns (bool); function permMarketHandlerLocked() external view returns (bool); function permLiqMiningHandlerLocked() external view returns (bool); function isPausingAdmin(address) external view returns (bool); function setPausingAdmin(address admin, bool isAdmin) external; function requestForgeHandlerChange(address _pendingForgeHandler) external; function requestMarketHandlerChange(address _pendingMarketHandler) external; function requestLiqMiningHandlerChange(address _pendingLiqMiningHandler) external; function applyForgeHandlerChange() external; function applyMarketHandlerChange() external; function applyLiqMiningHandlerChange() external; function lockPausingManagerPermanently() external; function lockForgeHandlerPermanently() external; function lockMarketHandlerPermanently() external; function lockLiqMiningHandlerPermanently() external; function setForgePaused(bytes32 forgeId, bool paused) external; function setForgeAssetPaused( bytes32 forgeId, address underlyingAsset, bool paused ) external; function setForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool paused ) external; function setForgeLocked(bytes32 forgeId) external; function setForgeAssetLocked(bytes32 forgeId, address underlyingAsset) external; function setForgeAssetExpiryLocked( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external; function checkYieldContractStatus( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (bool _paused, bool _locked); function setMarketFactoryPaused(bytes32 marketFactoryId, bool paused) external; function setMarketPaused( bytes32 marketFactoryId, address market, bool paused ) external; function setMarketFactoryLocked(bytes32 marketFactoryId) external; function setMarketLocked(bytes32 marketFactoryId, address market) external; function checkMarketStatus(bytes32 marketFactoryId, address market) external returns (bool _paused, bool _locked); function setLiqMiningPaused(address liqMiningContract, bool settingToPaused) external; function setLiqMiningLocked(address liqMiningContract) external; function checkLiqMiningStatus(address liqMiningContract) external returns (bool _paused, bool _locked); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma abicoder v2; import "./IPendleRouter.sol"; import "./IPendleBaseToken.sol"; import "../libraries/PendleStructs.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleMarket is IERC20 { /** * @notice Emitted when reserves pool has been updated * @param reserve0 The XYT reserves. * @param weight0 The XYT weight * @param reserve1 The generic token reserves. * For the generic Token weight it can be inferred by (2^40) - weight0 **/ event Sync(uint256 reserve0, uint256 weight0, uint256 reserve1); function setUpEmergencyMode(address spender) external; function bootstrap( address user, uint256 initialXytLiquidity, uint256 initialTokenLiquidity ) external returns (PendingTransfer[2] memory transfers, uint256 exactOutLp); function addMarketLiquiditySingle( address user, address inToken, uint256 inAmount, uint256 minOutLp ) external returns (PendingTransfer[2] memory transfers, uint256 exactOutLp); function addMarketLiquidityDual( address user, uint256 _desiredXytAmount, uint256 _desiredTokenAmount, uint256 _xytMinAmount, uint256 _tokenMinAmount ) external returns (PendingTransfer[2] memory transfers, uint256 lpOut); function removeMarketLiquidityDual( address user, uint256 inLp, uint256 minOutXyt, uint256 minOutToken ) external returns (PendingTransfer[2] memory transfers); function removeMarketLiquiditySingle( address user, address outToken, uint256 exactInLp, uint256 minOutToken ) external returns (PendingTransfer[2] memory transfers); function swapExactIn( address inToken, uint256 inAmount, address outToken, uint256 minOutAmount ) external returns (uint256 outAmount, PendingTransfer[2] memory transfers); function swapExactOut( address inToken, uint256 maxInAmount, address outToken, uint256 outAmount ) external returns (uint256 inAmount, PendingTransfer[2] memory transfers); function redeemLpInterests(address user) external returns (uint256 interests); function getReserves() external view returns ( uint256 xytBalance, uint256 xytWeight, uint256 tokenBalance, uint256 tokenWeight, uint256 currentBlock ); function factoryId() external view returns (bytes32); function token() external view returns (address); function xyt() external view returns (address); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPendleBaseToken is IERC20 { /** * @notice Decreases the allowance granted to spender by the caller. * @param spender The address to reduce the allowance from. * @param subtractedValue The amount allowance to subtract. * @return Returns true if allowance has decreased, otherwise false. **/ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); /** * @notice The yield contract start in epoch time. * @return Returns the yield start date. **/ function start() external view returns (uint256); /** * @notice The yield contract expiry in epoch time. * @return Returns the yield expiry date. **/ function expiry() external view returns (uint256); /** * @notice Increases the allowance granted to spender by the caller. * @param spender The address to increase the allowance from. * @param addedValue The amount allowance to add. * @return Returns true if allowance has increased, otherwise false **/ function increaseAllowance(address spender, uint256 addedValue) external returns (bool); /** * @notice Returns the number of decimals the token uses. * @return Returns the token's decimals. **/ function decimals() external view returns (uint8); /** * @notice Returns the name of the token. * @return Returns the token's name. **/ function name() external view returns (string memory); /** * @notice Returns the symbol of the token. * @return Returns the token's symbol. **/ function symbol() external view returns (string memory); /** * @notice approve using the owner's signature **/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PermissionsV2.sol"; abstract contract WithdrawableV2 is PermissionsV2 { using SafeERC20 for IERC20; event EtherWithdraw(uint256 amount, address sendTo); event TokenWithdraw(IERC20 token, uint256 amount, address sendTo); /** * @dev Allows governance to withdraw Ether in a Pendle contract * in case of accidental ETH transfer into the contract. * @param amount The amount of Ether to withdraw. * @param sendTo The recipient address. */ function withdrawEther(uint256 amount, address payable sendTo) external onlyGovernance { (bool success, ) = sendTo.call{value: amount}(""); require(success, "WITHDRAW_FAILED"); emit EtherWithdraw(amount, sendTo); } /** * @dev Allows governance to withdraw all IERC20 compatible tokens in a Pendle * contract in case of accidental token transfer into the contract. * @param token IERC20 The address of the token contract. * @param amount The amount of IERC20 tokens to withdraw. * @param sendTo The recipient address. */ function withdrawToken( IERC20 token, uint256 amount, address sendTo ) external onlyGovernance { require(_allowedToWithdraw(address(token)), "TOKEN_NOT_ALLOWED"); token.safeTransfer(sendTo, amount); emit TokenWithdraw(token, amount, sendTo); } // must be overridden by the sub contracts, so we must consider explicitly // in each and every contract which tokens are allowed to be withdrawn function _allowedToWithdraw(address) internal view virtual returns (bool allowed); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "../interfaces/IPendleBaseToken.sol"; import "../interfaces/IPendleRouter.sol"; /** * @title PendleBaseToken * @dev The contract implements the standard ERC20 functions, plus some * Pendle specific fields and functions, namely: * - expiry * * This abstract contract is inherited by PendleFutureYieldToken * and PendleOwnershipToken contracts. **/ abstract contract PendleBaseToken is ERC20 { using SafeMath for uint256; uint256 public immutable start; uint256 public immutable expiry; IPendleRouter public immutable router; //// Start of EIP-2612 related part, exactly the same as UniswapV2ERC20.sol bytes32 public immutable DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; //// End of EIP-2612 related part constructor( address _router, string memory _name, string memory _symbol, uint8 _decimals, uint256 _start, uint256 _expiry ) ERC20(_name, _symbol) { _setupDecimals(_decimals); start = _start; expiry = _expiry; router = IPendleRouter(_router); //// Start of EIP-2612 related part, exactly the same as UniswapV2ERC20.sol, except for the noted parts below uint256 chainId; assembly { chainId := chainid() // chainid() is a function in assembly in this solidity version } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(_name)), // use our own _name here keccak256(bytes("1")), chainId, address(this) ) ); //// End of EIP-2612 related part } //// Start of EIP-2612 related part, exactly the same as UniswapV2ERC20.sol function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "PERMIT_EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ECDSA.recover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNATURE"); _approve(owner, spender, value); } //// End of EIP-2612 related part function _beforeTokenTransfer( address from, address to, uint256 ) internal virtual override { require(to != address(this), "SEND_TO_TOKEN_CONTRACT"); require(to != from, "SEND_TO_SELF"); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./MathLib.sol"; import "./PendleStructs.sol"; library MarketMath { using SafeMath for uint256; /** * @notice calculate the exact amount of tokens that user need to put in the market * in order to get back certain amount of the other token * @param inTokenReserve market reserve details of token that user wants to put in * @param outTokenReserve market reserve details of token that user wants to get back * @param exactOut exact amount of token that user wants to get back * @param swapFee swap fee ratio for swap * @dev The formula for this function can be referred in the AMM Specs */ function _calcExactIn( TokenReserve memory inTokenReserve, TokenReserve memory outTokenReserve, uint256 exactOut, uint256 swapFee ) internal pure returns (uint256 exactIn) { uint256 weightRatio = Math.rdiv(outTokenReserve.weight, inTokenReserve.weight); uint256 diff = outTokenReserve.balance.sub(exactOut); uint256 y = Math.rdiv(outTokenReserve.balance, diff); uint256 foo = Math.rpow(y, weightRatio); foo = foo.sub(Math.RONE); exactIn = Math.RONE.sub(swapFee); exactIn = Math.rdiv(Math.rmul(inTokenReserve.balance, foo), exactIn); } /** * @notice calculate the exact amount of tokens that user can get back from the market * if user put in certain amount of the other token * @param inTokenReserve market reserve details of token that user wants to put in * @param outTokenReserve market reserve details of token that user wants to get back * @param exactIn exact amount of token that user wants to put in * @param swapFee swap fee (percentage) for swap * @dev The formula for this function can be referred in the AMM Specs */ function _calcExactOut( TokenReserve memory inTokenReserve, TokenReserve memory outTokenReserve, uint256 exactIn, uint256 swapFee ) internal pure returns (uint256 exactOut) { uint256 weightRatio = Math.rdiv(inTokenReserve.weight, outTokenReserve.weight); uint256 adjustedIn = Math.RONE.sub(swapFee); adjustedIn = Math.rmul(exactIn, adjustedIn); uint256 y = Math.rdiv(inTokenReserve.balance, inTokenReserve.balance.add(adjustedIn)); uint256 foo = Math.rpow(y, weightRatio); uint256 bar = Math.RONE.sub(foo); exactOut = Math.rmul(outTokenReserve.balance, bar); } /** * @notice to calculate exact amount of lp token to be minted if single token liquidity is added to market * @param inAmount exact amount of the token that user wants to put in * @param inTokenReserve market reserve details of the token that user wants to put in * @param swapFee swap fee (percentage) for swap * @param totalSupplyLp current (before adding liquidity) lp supply * @dev swap fee applies here since add liquidity by single token is equivalent of a swap * @dev used when add liquidity by single token * @dev The formula for this function can be referred in the AMM Specs */ function _calcOutAmountLp( uint256 inAmount, TokenReserve memory inTokenReserve, uint256 swapFee, uint256 totalSupplyLp ) internal pure returns (uint256 exactOutLp) { uint256 nWeight = inTokenReserve.weight; uint256 feePortion = Math.rmul(Math.RONE.sub(nWeight), swapFee); uint256 inAmountAfterFee = Math.rmul(inAmount, Math.RONE.sub(feePortion)); uint256 inBalanceUpdated = inTokenReserve.balance.add(inAmountAfterFee); uint256 inTokenRatio = Math.rdiv(inBalanceUpdated, inTokenReserve.balance); uint256 lpTokenRatio = Math.rpow(inTokenRatio, nWeight); uint256 totalSupplyLpUpdated = Math.rmul(lpTokenRatio, totalSupplyLp); exactOutLp = totalSupplyLpUpdated.sub(totalSupplyLp); return exactOutLp; } /** * @notice to calculate exact amount of token that user can get back if * single token liquidity is removed from market * @param outTokenReserve market reserve details of the token that user wants to get back * @param totalSupplyLp current (before adding liquidity) lp supply * @param inLp exact amount of the lp token (single liquidity to remove) that user wants to put in * @param swapFee swap fee (percentage) for swap * @dev swap fee applies here since add liquidity by single token is equivalent of a swap * @dev used when remove liquidity by single token * @dev The formula for this function can be referred in the AMM Specs */ function _calcOutAmountToken( TokenReserve memory outTokenReserve, uint256 totalSupplyLp, uint256 inLp, uint256 swapFee ) internal pure returns (uint256 exactOutToken) { uint256 nWeight = outTokenReserve.weight; uint256 totalSupplyLpUpdated = totalSupplyLp.sub(inLp); uint256 lpRatio = Math.rdiv(totalSupplyLpUpdated, totalSupplyLp); uint256 outTokenRatio = Math.rpow(lpRatio, Math.rdiv(Math.RONE, nWeight)); uint256 outTokenBalanceUpdated = Math.rmul(outTokenRatio, outTokenReserve.balance); uint256 outAmountTokenBeforeSwapFee = outTokenReserve.balance.sub(outTokenBalanceUpdated); uint256 feePortion = Math.rmul(Math.RONE.sub(nWeight), swapFee); exactOutToken = Math.rmul(outAmountTokenBeforeSwapFee, Math.RONE.sub(feePortion)); return exactOutToken; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../core/PendleGovernanceManager.sol"; import "../interfaces/IPermissionsV2.sol"; abstract contract PermissionsV2 is IPermissionsV2 { PendleGovernanceManager public immutable override governanceManager; address internal initializer; constructor(address _governanceManager) { require(_governanceManager != address(0), "ZERO_ADDRESS"); initializer = msg.sender; governanceManager = PendleGovernanceManager(_governanceManager); } modifier initialized() { require(initializer == address(0), "NOT_INITIALIZED"); _; } modifier onlyGovernance() { require(msg.sender == _governance(), "ONLY_GOVERNANCE"); _; } function _governance() internal view returns (address) { return governanceManager.governance(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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); } } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; contract PendleGovernanceManager { address public governance; address public pendingGovernance; event GovernanceClaimed(address newGovernance, address previousGovernance); event TransferGovernancePending(address pendingGovernance); constructor(address _governance) { require(_governance != address(0), "ZERO_ADDRESS"); governance = _governance; } modifier onlyGovernance() { require(msg.sender == governance, "ONLY_GOVERNANCE"); _; } /** * @dev Allows the pendingGovernance address to finalize the change governance process. */ function claimGovernance() external { require(pendingGovernance == msg.sender, "WRONG_GOVERNANCE"); emit GovernanceClaimed(pendingGovernance, governance); governance = pendingGovernance; pendingGovernance = address(0); } /** * @dev Allows the current governance to set the pendingGovernance address. * @param _governance The address to transfer ownership to. */ function transferGovernance(address _governance) external onlyGovernance { require(_governance != address(0), "ZERO_ADDRESS"); pendingGovernance = _governance; emit TransferGovernancePending(pendingGovernance); } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma abicoder v2; import "../core/PendleGovernanceManager.sol"; interface IPermissionsV2 { function governanceManager() external returns (PendleGovernanceManager); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _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 virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.0; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; library Math { using SafeMath for uint256; uint256 internal constant BIG_NUMBER = (uint256(1) << uint256(200)); uint256 internal constant PRECISION_BITS = 40; uint256 internal constant RONE = uint256(1) << PRECISION_BITS; uint256 internal constant PI = (314 * RONE) / 10**2; uint256 internal constant PI_PLUSONE = (414 * RONE) / 10**2; uint256 internal constant PRECISION_POW = 1e2; function checkMultOverflow(uint256 _x, uint256 _y) internal pure returns (bool) { if (_y == 0) return false; return (((_x * _y) / _y) != _x); } /** @notice find the integer part of log2(p/q) => find largest x s.t p >= q * 2^x => find largest x s.t 2^x <= p / q */ function log2Int(uint256 _p, uint256 _q) internal pure returns (uint256) { uint256 res = 0; uint256 remain = _p / _q; while (remain > 0) { res++; remain /= 2; } return res - 1; } /** @notice log2 for a number that it in [1,2) @dev _x is FP, return a FP @dev function is from Kyber. Long modified the condition to be (_x >= one) && (_x < two) to avoid the case where x = 2 may lead to incorrect result */ function log2ForSmallNumber(uint256 _x) internal pure returns (uint256) { uint256 res = 0; uint256 one = (uint256(1) << PRECISION_BITS); uint256 two = 2 * one; uint256 addition = one; require((_x >= one) && (_x < two), "MATH_ERROR"); require(PRECISION_BITS < 125, "MATH_ERROR"); for (uint256 i = PRECISION_BITS; i > 0; i--) { _x = (_x * _x) / one; addition = addition / 2; if (_x >= two) { _x = _x / 2; res += addition; } } return res; } /** @notice log2 of (p/q). returns result in FP form @dev function is from Kyber. @dev _p & _q is FP, return a FP */ function logBase2(uint256 _p, uint256 _q) internal pure returns (uint256) { uint256 n = 0; if (_p > _q) { n = log2Int(_p, _q); } require(n * RONE <= BIG_NUMBER, "MATH_ERROR"); require(!checkMultOverflow(_p, RONE), "MATH_ERROR"); require(!checkMultOverflow(n, RONE), "MATH_ERROR"); require(!checkMultOverflow(uint256(1) << n, _q), "MATH_ERROR"); uint256 y = (_p * RONE) / (_q * (uint256(1) << n)); uint256 log2Small = log2ForSmallNumber(y); assert(log2Small <= BIG_NUMBER); return n * RONE + log2Small; } /** @notice calculate ln(p/q). returned result >= 0 @dev function is from Kyber. @dev _p & _q is FP, return a FP */ function ln(uint256 p, uint256 q) internal pure returns (uint256) { uint256 ln2Numerator = 6931471805599453094172; uint256 ln2Denomerator = 10000000000000000000000; uint256 log2x = logBase2(p, q); require(!checkMultOverflow(ln2Numerator, log2x), "MATH_ERROR"); return (ln2Numerator * log2x) / ln2Denomerator; } /** @notice extract the fractional part of a FP @dev value is a FP, return a FP */ function fpart(uint256 value) internal pure returns (uint256) { return value % RONE; } /** @notice convert a FP to an Int @dev value is a FP, return an Int */ function toInt(uint256 value) internal pure returns (uint256) { return value / RONE; } /** @notice convert an Int to a FP @dev value is an Int, return a FP */ function toFP(uint256 value) internal pure returns (uint256) { return value * RONE; } /** @notice return e^exp in FP form @dev estimation by formula at http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html the function is based on exp function of: https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol @dev the function is expected to converge quite fast, after about 20 iteration @dev exp is a FP, return a FP */ function rpowe(uint256 exp) internal pure returns (uint256) { uint256 res = 0; uint256 curTerm = RONE; for (uint256 n = 0; ; n++) { res += curTerm; curTerm = rmul(curTerm, rdiv(exp, toFP(n + 1))); if (curTerm == 0) { break; } if (n == 500) { /* testing shows that in the most extreme case, it will take 430 turns to converge. however, it's expected that the numbers will not exceed 2^120 in normal situation the most extreme case is rpow((1<<256)-1,(1<<40)-1) (equal to rpow((2^256-1)/2^40,0.99..9)) */ revert("RPOWE_SLOW_CONVERGE"); } } return res; } /** @notice calculate base^exp with base and exp being FP int @dev to improve accuracy, base^exp = base^(int(exp)+frac(exp)) = base^int(exp) * base^frac @dev base & exp are FP, return a FP */ function rpow(uint256 base, uint256 exp) internal pure returns (uint256) { if (exp == 0) { // Anything to the 0 is 1 return RONE; } if (base == 0) { // 0 to anything except 0 is 0 return 0; } uint256 frac = fpart(exp); // get the fractional part uint256 whole = exp - frac; uint256 wholePow = rpowi(base, toInt(whole)); // whole is a FP, convert to Int uint256 fracPow; // instead of calculating base ^ frac, we will calculate e ^ (frac*ln(base)) if (base < RONE) { /* since the base is smaller than 1.0, ln(base) < 0. Since 1 / (e^(frac*ln(1/base))) = e ^ (frac*ln(base)), we will calculate 1 / (e^(frac*ln(1/base))) instead. */ uint256 newExp = rmul(frac, ln(rdiv(RONE, base), RONE)); fracPow = rdiv(RONE, rpowe(newExp)); } else { /* base is greater than 1, calculate normally */ uint256 newExp = rmul(frac, ln(base, RONE)); fracPow = rpowe(newExp); } return rmul(wholePow, fracPow); } /** @notice return base^exp with base in FP form and exp in Int @dev this function use a technique called: exponentiating by squaring complexity O(log(q)) @dev function is from Kyber. @dev base is a FP, exp is an Int, return a FP */ function rpowi(uint256 base, uint256 exp) internal pure returns (uint256) { uint256 res = exp % 2 != 0 ? base : RONE; for (exp /= 2; exp != 0; exp /= 2) { base = rmul(base, base); if (exp % 2 != 0) { res = rmul(res, base); } } return res; } /** @dev y is an Int, returns an Int @dev babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) @dev from Uniswap */ 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; } } /** @notice divide 2 FP, return a FP @dev function is from Balancer. @dev x & y are FP, return a FP */ function rdiv(uint256 x, uint256 y) internal pure returns (uint256) { return (y / 2).add(x.mul(RONE)).div(y); } /** @notice multiply 2 FP, return a FP @dev function is from Balancer. @dev x & y are FP, return a FP */ function rmul(uint256 x, uint256 y) internal pure returns (uint256) { return (RONE / 2).add(x.mul(y)).div(RONE); } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function subMax0(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a - b : 0; } }
* @notice Exit the market by putting in the desired amount of LP tokens and getting back XYT or pair tokens. @param _outToken address of the token that user wants to get back @param _inLp the exact amount of liquidity token that user wants to put back @param _minOutAmountToken the minimum of token that user wants to get back @dev curveShift needed since function operation relies on weights/ mint protocol fees before k is changed by a non-swap event (remove liquidity)
function removeMarketLiquiditySingle( address user, address _outToken, uint256 _inLp, uint256 _minOutAmountToken ) external override returns (PendingTransfer[2] memory transfers) { checkAddRemoveSwapClaimAllowed(false); _mintProtocolFees(); _curveShift(); since this add single involves an implicit swap operation TokenReserve memory outTokenReserve = parseTokenReserveData(_outToken); uint256 swapFee = data.swapFee(); uint256 totalLp = totalSupply(); uint256 outAmountToken = MarketMath._calcOutAmountToken(outTokenReserve, totalLp, _inLp, swapFee); require(outAmountToken >= _minOutAmountToken, "INSUFFICIENT_TOKEN_OUT"); outTokenReserve.balance = outTokenReserve.balance.sub(outAmountToken); transfers[0].amount = outAmountToken; transfers[0].isOut = true; updateReserveData(outTokenReserve, _outToken); _burn(user, _inLp); emit Sync(xytBalance, xytWeight, tokenBalance);
349,109
[ 1, 6767, 326, 13667, 635, 29379, 316, 326, 6049, 3844, 434, 511, 52, 2430, 1377, 471, 8742, 1473, 18774, 56, 578, 3082, 2430, 18, 225, 389, 659, 1345, 1758, 434, 326, 1147, 716, 729, 14805, 358, 336, 1473, 225, 389, 267, 48, 84, 326, 5565, 3844, 434, 4501, 372, 24237, 1147, 716, 729, 14805, 358, 1378, 1473, 225, 389, 1154, 1182, 6275, 1345, 326, 5224, 434, 1147, 716, 729, 14805, 358, 336, 1473, 225, 8882, 10544, 3577, 3241, 445, 1674, 14719, 281, 603, 5376, 19, 312, 474, 1771, 1656, 281, 1865, 417, 353, 3550, 635, 279, 1661, 17, 22270, 871, 261, 4479, 4501, 372, 24237, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1206, 3882, 278, 48, 18988, 24237, 5281, 12, 203, 3639, 1758, 729, 16, 203, 3639, 1758, 389, 659, 1345, 16, 203, 3639, 2254, 5034, 389, 267, 48, 84, 16, 203, 3639, 2254, 5034, 389, 1154, 1182, 6275, 1345, 203, 565, 262, 3903, 3849, 1135, 261, 8579, 5912, 63, 22, 65, 3778, 29375, 13, 288, 203, 3639, 866, 986, 3288, 12521, 9762, 5042, 12, 5743, 1769, 203, 203, 3639, 389, 81, 474, 5752, 2954, 281, 5621, 203, 3639, 389, 16683, 10544, 5621, 203, 203, 5411, 3241, 333, 527, 2202, 29876, 3324, 392, 10592, 7720, 1674, 203, 3639, 3155, 607, 6527, 3778, 596, 1345, 607, 6527, 273, 1109, 1345, 607, 6527, 751, 24899, 659, 1345, 1769, 203, 203, 3639, 2254, 5034, 7720, 14667, 273, 501, 18, 22270, 14667, 5621, 203, 3639, 2254, 5034, 2078, 48, 84, 273, 2078, 3088, 1283, 5621, 203, 203, 3639, 2254, 5034, 596, 6275, 1345, 273, 203, 5411, 6622, 278, 10477, 6315, 12448, 1182, 6275, 1345, 12, 659, 1345, 607, 6527, 16, 2078, 48, 84, 16, 389, 267, 48, 84, 16, 7720, 14667, 1769, 203, 3639, 2583, 12, 659, 6275, 1345, 1545, 389, 1154, 1182, 6275, 1345, 16, 315, 706, 6639, 42, 1653, 7266, 2222, 67, 8412, 67, 5069, 8863, 203, 203, 3639, 596, 1345, 607, 6527, 18, 12296, 273, 596, 1345, 607, 6527, 18, 12296, 18, 1717, 12, 659, 6275, 1345, 1769, 203, 3639, 29375, 63, 20, 8009, 8949, 273, 596, 6275, 1345, 31, 203, 3639, 29375, 63, 20, 8009, 291, 1182, 273, 638, 31, 203, 203, 3639, 1089, 2 ]
pragma solidity ^0.4.24; /** @title PEpsilon * @author Daniel Babbev * * This contract implements a p + epsilon attack against the Kleros court. * The attack is described by VitaliK Buterin here: https://blog.ethereum.org/2015/01/28/p-epsilon-attack/ */ contract PEpsilon { Pinakion public pinakion; Kleros public court; uint public balance; uint public disputeID; uint public desiredOutcome; uint public epsilon; bool public settled; uint public maxAppeals; // The maximum number of appeals this cotracts promises to pay mapping (address => uint) public withdraw; // We'll use a withdraw pattern here to avoid multiple sends when a juror has voted multiple times. address public attacker; uint public remainingWithdraw; // Here we keep the total amount bribed jurors have available for withdraw. modifier onlyBy(address _account) {require(msg.sender == _account); _;} event AmountShift(uint val, uint epsilon ,address juror); event Log(uint val, address addr, string message); /** @dev Constructor. * @param _pinakion The PNK contract. * @param _kleros The Kleros court. * @param _disputeID The dispute we are targeting. * @param _desiredOutcome The desired ruling of the dispute. * @param _epsilon Jurors will be paid epsilon more for voting for the desiredOutcome. * @param _maxAppeals The maximum number of appeals this contract promises to pay out */ constructor(Pinakion _pinakion, Kleros _kleros, uint _disputeID, uint _desiredOutcome, uint _epsilon, uint _maxAppeals) public { pinakion = _pinakion; court = _kleros; disputeID = _disputeID; desiredOutcome = _desiredOutcome; epsilon = _epsilon; attacker = msg.sender; maxAppeals = _maxAppeals; } /** @dev Callback of approveAndCall - transfer pinakions in the contract. Should be called by the pinakion contract. TRUSTED. * The attacker has to deposit sufficiently large amount of PNK to cover the payouts to the jurors. * @param _from The address making the transfer. * @param _amount Amount of tokens to transfer to this contract (in basic units). */ function receiveApproval(address _from, uint _amount, address, bytes) public onlyBy(pinakion) { require(pinakion.transferFrom(_from, this, _amount)); balance += _amount; } /** @dev Jurors can withdraw their PNK from here */ function withdrawJuror() { withdrawSelect(msg.sender); } /** @dev Withdraw the funds of a given juror * @param _juror The address of the juror */ function withdrawSelect(address _juror) { uint amount = withdraw[_juror]; withdraw[_juror] = 0; balance = sub(balance, amount); // Could underflow remainingWithdraw = sub(remainingWithdraw, amount); // The juror receives d + p + e (deposit + p + epsilon) require(pinakion.transfer(_juror, amount)); } /** * @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 The attacker can withdraw their PNK from here after the bribe has been settled. */ function withdrawAttacker(){ require(settled); if (balance > remainingWithdraw) { // The remaning balance of PNK after settlement is transfered to the attacker. uint amount = balance - remainingWithdraw; balance = remainingWithdraw; require(pinakion.transfer(attacker, amount)); } } /** @dev Settles the p + e bribe with the jurors. * If the dispute is ruled differently from desiredOutcome: * The jurors who voted for desiredOutcome receive p + d + e in rewards from this contract. * If the dispute is ruled as in desiredOutcome: * The jurors don't receive anything from this contract. */ function settle() public { require(court.disputeStatus(disputeID) == Arbitrator.DisputeStatus.Solved); // The case must be solved. require(!settled); // This function can be executed only once. settled = true; // settle the bribe // From the dispute we get the # of appeals and the available choices var (, , appeals, choices, , , ,) = court.disputes(disputeID); if (court.currentRuling(disputeID) != desiredOutcome){ // Calculate the redistribution amounts. uint amountShift = court.getStakePerDraw(); uint winningChoice = court.getWinningChoice(disputeID, appeals); // Rewards are calculated as per the one shot token reparation. for (uint i=0; i <= (appeals > maxAppeals ? maxAppeals : appeals); i++){ // Loop each appeal and each vote. // Note that we don't check if the result was a tie becuse we are getting a funny compiler error: "stack is too deep" if we check. // TODO: Account for ties if (winningChoice != 0){ // votesLen is the length of the votes per each appeal. There is no getter function for that, so we have to calculate it here. // We must end up with the exact same value as if we would have called dispute.votes[i].length uint votesLen = 0; for (uint c = 0; c <= choices; c++) { // Iterate for each choice of the dispute. votesLen += court.getVoteCount(disputeID, i, c); } emit Log(amountShift, 0x0 ,"stakePerDraw"); emit Log(votesLen, 0x0, "votesLen"); uint totalToRedistribute = 0; uint nbCoherent = 0; // Now we will use votesLen as a substitute for dispute.votes[i].length for (uint j=0; j < votesLen; j++){ uint voteRuling = court.getVoteRuling(disputeID, i, j); address voteAccount = court.getVoteAccount(disputeID, i, j); emit Log(voteRuling, voteAccount, "voted"); if (voteRuling != winningChoice){ totalToRedistribute += amountShift; if (voteRuling == desiredOutcome){ // If the juror voted as we desired. // Transfer this juror back the penalty. withdraw[voteAccount] += amountShift + epsilon; remainingWithdraw += amountShift + epsilon; emit AmountShift(amountShift, epsilon, voteAccount); } } else { nbCoherent++; } } // toRedistribute is the amount each juror received when he voted coherently. uint toRedistribute = (totalToRedistribute - amountShift) / (nbCoherent + 1); // We use votesLen again as a substitute for dispute.votes[i].length for (j = 0; j < votesLen; j++){ voteRuling = court.getVoteRuling(disputeID, i, j); voteAccount = court.getVoteAccount(disputeID, i, j); if (voteRuling == desiredOutcome){ // Add the coherent juror reward to the total payout. withdraw[voteAccount] += toRedistribute; remainingWithdraw += toRedistribute; emit AmountShift(toRedistribute, 0, voteAccount); } } } } } } } /** * @title Kleros * @author Clément Lesaege - <[email protected]> * This code implements a simple version of Kleros. * Bug Bounties: This code hasn't undertaken a bug bounty program yet. */ pragma solidity ^0.4.24; contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } 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; } } /// @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 Pinakion 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 Pinakion 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 Pinakion /// @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 Pinakion( 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 = Pinakion(_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); doTransfer(msg.sender, _to, _amount); return true; } /// @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 require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } /// @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 { if (_amount == 0) { Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } 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 throws var previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // 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); } /// @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 the standard version to allow backward compatibility. /// @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); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } 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; Pinakion 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 function min(uint a, uint b) pure internal 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 { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // 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; } Pinakion token = Pinakion(_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 (Pinakion) { Pinakion newToken = new Pinakion( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract RNG{ /** @dev Contribute to the reward of a random number. * @param _block Block the random number is linked to. */ function contribute(uint _block) public payable; /** @dev Request a random number. * @param _block Block linked to the request. */ function requestRN(uint _block) public payable { contribute(_block); } /** @dev Get the random number. * @param _block Block the random number is linked to. * @return RN Random Number. If the number is not ready or has not been required 0 instead. */ function getRN(uint _block) public returns (uint RN); /** @dev Get a uncorrelated random number. Act like getRN but give a different number for each sender. * This is to prevent users from getting correlated numbers. * @param _block Block the random number is linked to. * @return RN Random Number. If the number is not ready or has not been required 0 instead. */ function getUncorrelatedRN(uint _block) public returns (uint RN) { uint baseRN=getRN(_block); if (baseRN==0) return 0; else return uint(keccak256(msg.sender,baseRN)); } } /** Simple Random Number Generator returning the blockhash. * Allows saving the random number for use in the future. * It allows the contract to still access the blockhash even after 256 blocks. * The first party to call the save function gets the reward. */ contract BlockHashRNG is RNG { mapping (uint => uint) public randomNumber; // randomNumber[block] is the random number for this block, 0 otherwise. mapping (uint => uint) public reward; // reward[block] is the amount to be paid to the party w. /** @dev Contribute to the reward of a random number. * @param _block Block the random number is linked to. */ function contribute(uint _block) public payable { reward[_block]+=msg.value; } /** @dev Return the random number. If it has not been saved and is still computable compute it. * @param _block Block the random number is linked to. * @return RN Random Number. If the number is not ready or has not been requested 0 instead. */ function getRN(uint _block) public returns (uint RN) { RN=randomNumber[_block]; if (RN==0){ saveRN(_block); return randomNumber[_block]; } else return RN; } /** @dev Save the random number for this blockhash and give the reward to the caller. * @param _block Block the random number is linked to. */ function saveRN(uint _block) public { if (blockhash(_block) != 0x0) randomNumber[_block] = uint(blockhash(_block)); if (randomNumber[_block] != 0) { // If the number is set. uint rewardToSend = reward[_block]; reward[_block] = 0; msg.sender.send(rewardToSend); // Note that the use of send is on purpose as we don't want to block in case msg.sender has a fallback issue. } } } /** Random Number Generator returning the blockhash with a backup behaviour. * Allows saving the random number for use in the future. * It allows the contract to still access the blockhash even after 256 blocks. * The first party to call the save function gets the reward. * If no one calls the contract within 256 blocks, the contract fallback in returning the blockhash of the previous block. */ contract BlockHashRNGFallback is BlockHashRNG { /** @dev Save the random number for this blockhash and give the reward to the caller. * @param _block Block the random number is linked to. */ function saveRN(uint _block) public { if (_block<block.number && randomNumber[_block]==0) {// If the random number is not already set and can be. if (blockhash(_block)!=0x0) // Normal case. randomNumber[_block]=uint(blockhash(_block)); else // The contract was not called in time. Fallback to returning previous blockhash. randomNumber[_block]=uint(blockhash(block.number-1)); } if (randomNumber[_block] != 0) { // If the random number is set. uint rewardToSend=reward[_block]; reward[_block]=0; msg.sender.send(rewardToSend); // Note that the use of send is on purpose as we don't want to block in case the msg.sender has a fallback issue. } } } /** @title Arbitrable * Arbitrable abstract contract. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. * -Allow dispute creation. For this a function must: * -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); * -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); */ contract Arbitrable{ Arbitrator public arbitrator; bytes public arbitratorExtraData; // Extra data to require particular dispute and appeal behaviour. modifier onlyArbitrator {require(msg.sender==address(arbitrator)); _;} /** @dev To be raised when a ruling is given. * @param _arbitrator The arbitrator giving the ruling. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling The ruling which was given. */ event Ruling(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling); /** @dev To be emmited when meta-evidence is submitted. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidence A link to the meta-evidence JSON. */ event MetaEvidence(uint indexed _metaEvidenceID, string _evidence); /** @dev To be emmited when a dispute is created to link the correct meta-evidence to the disputeID * @param _arbitrator The arbitrator of the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _metaEvidenceID Unique identifier of meta-evidence. */ event Dispute(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID); /** @dev To be raised when evidence are submitted. Should point to the ressource (evidences are not to be stored on chain due to gas considerations). * @param _arbitrator The arbitrator of the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party. * @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json. */ event Evidence(Arbitrator indexed _arbitrator, uint indexed _disputeID, address _party, string _evidence); /** @dev Constructor. Choose the arbitrator. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. */ constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public onlyArbitrator { emit Ruling(Arbitrator(msg.sender),_disputeID,_ruling); executeRuling(_disputeID,_ruling); } /** @dev Execute a ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal; } /** @title Arbitrator * Arbitrator abstract contract. * When developing arbitrator contracts we need to: * -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, use nbDisputes). * -Define the functions for cost display (arbitrationCost and appealCost). * -Allow giving rulings. For this a function must call arbitrable.rule(disputeID,ruling). */ contract Arbitrator{ enum DisputeStatus {Waiting, Appealable, Solved} modifier requireArbitrationFee(bytes _extraData) {require(msg.value>=arbitrationCost(_extraData)); _;} modifier requireAppealFee(uint _disputeID, bytes _extraData) {require(msg.value>=appealCost(_disputeID, _extraData)); _;} /** @dev To be raised when a dispute can be appealed. * @param _disputeID ID of the dispute. */ event AppealPossible(uint _disputeID); /** @dev To be raised when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint indexed _disputeID, Arbitrable _arbitrable); /** @dev To be raised when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint indexed _disputeID, Arbitrable _arbitrable); /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes _extraData) public requireArbitrationFee(_extraData) payable returns(uint disputeID) {} /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function arbitrationCost(bytes _extraData) public constant returns(uint fee); /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint _disputeID, bytes _extraData) public requireAppealFee(_disputeID,_extraData) payable { emit AppealDecision(_disputeID, Arbitrable(msg.sender)); } /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function appealCost(uint _disputeID, bytes _extraData) public constant returns(uint fee); /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) public constant returns(DisputeStatus status); /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint _disputeID) public constant returns(uint ruling); } contract Kleros is Arbitrator, ApproveAndCallFallBack { // **************************** // // * Contract variables * // // **************************** // // Variables which should not change after initialization. Pinakion public pinakion; uint public constant NON_PAYABLE_AMOUNT = (2**256 - 2) / 2; // An astronomic amount, practically can't be paid. // Variables which will subject to the governance mechanism. // Note they will only be able to be changed during the activation period (because a session assumes they don't change after it). RNG public rng; // Random Number Generator used to draw jurors. uint public arbitrationFeePerJuror = 0.05 ether; // The fee which will be paid to each juror. uint16 public defaultNumberJuror = 3; // Number of drawn jurors unless specified otherwise. uint public minActivatedToken = 0.1 * 1e18; // Minimum of tokens to be activated (in basic units). uint[5] public timePerPeriod; // The minimum time each period lasts (seconds). uint public alpha = 2000; // alpha in ‱ (1 / 10 000). uint constant ALPHA_DIVISOR = 1e4; // Amount we need to divided alpha in ‱ to get the float value of alpha. uint public maxAppeals = 5; // Number of times a dispute can be appealed. When exceeded appeal cost becomes NON_PAYABLE_AMOUNT. // Initially, the governor will be an address controlled by the Kleros team. At a later stage, // the governor will be switched to a governance contract with liquid voting. address public governor; // Address of the governor contract. // Variables changing during day to day interaction. uint public session = 1; // Current session of the court. uint public lastPeriodChange; // The last time we changed of period (seconds). uint public segmentSize; // Size of the segment of activated tokens. uint public rnBlock; // The block linked with the RN which is requested. uint public randomNumber; // Random number of the session. enum Period { Activation, // When juror can deposit their tokens and parties give evidences. Draw, // When jurors are drawn at random, note that this period is fast. Vote, // Where jurors can vote on disputes. Appeal, // When parties can appeal the rulings. Execution // When where token redistribution occurs and Kleros call the arbitrated contracts. } Period public period; struct Juror { uint balance; // The amount of tokens the contract holds for this juror. uint atStake; // Total number of tokens the jurors can loose in disputes they are drawn in. Those tokens are locked. Note that we can have atStake > balance but it should be statistically unlikely and does not pose issues. uint lastSession; // Last session the tokens were activated. uint segmentStart; // Start of the segment of activated tokens. uint segmentEnd; // End of the segment of activated tokens. } mapping (address => Juror) public jurors; struct Vote { address account; // The juror who casted the vote. uint ruling; // The ruling which was given. } struct VoteCounter { uint winningChoice; // The choice which currently has the highest amount of votes. Is 0 in case of a tie. uint winningCount; // The number of votes for winningChoice. Or for the choices which are tied. mapping (uint => uint) voteCount; // voteCount[choice] is the number of votes for choice. } enum DisputeState { Open, // The dispute is opened but the outcome is not available yet (this include when jurors voted but appeal is still possible). Resolving, // The token repartition has started. Note that if it's done in just one call, this state is skipped. Executable, // The arbitrated contract can be called to enforce the decision. Executed // Everything has been done and the dispute can't be interacted with anymore. } struct Dispute { Arbitrable arbitrated; // Contract to be arbitrated. uint session; // First session the dispute was schedule. uint appeals; // Number of appeals. uint choices; // The number of choices available to the jurors. uint16 initialNumberJurors; // The initial number of jurors. uint arbitrationFeePerJuror; // The fee which will be paid to each juror. DisputeState state; // The state of the dispute. Vote[][] votes; // The votes in the form vote[appeals][voteID]. VoteCounter[] voteCounter; // The vote counters in the form voteCounter[appeals]. mapping (address => uint) lastSessionVote; // Last session a juror has voted on this dispute. Is 0 if he never did. uint currentAppealToRepartition; // The current appeal we are repartitioning. AppealsRepartitioned[] appealsRepartitioned; // Track a partially repartitioned appeal in the form AppealsRepartitioned[appeal]. } enum RepartitionStage { // State of the token repartition if oneShotTokenRepartition would throw because there are too many votes. Incoherent, Coherent, AtStake, Complete } struct AppealsRepartitioned { uint totalToRedistribute; // Total amount of tokens we have to redistribute. uint nbCoherent; // Number of coherent jurors for session. uint currentIncoherentVote; // Current vote for the incoherent loop. uint currentCoherentVote; // Current vote we need to count. uint currentAtStakeVote; // Current vote we need to count. RepartitionStage stage; // Use with multipleShotTokenRepartition if oneShotTokenRepartition would throw. } Dispute[] public disputes; // **************************** // // * Events * // // **************************** // /** @dev Emitted when we pass to a new period. * @param _period The new period. * @param _session The current session. */ event NewPeriod(Period _period, uint indexed _session); /** @dev Emitted when a juror wins or loses tokens. * @param _account The juror affected. * @param _disputeID The ID of the dispute. * @param _amount The amount of parts of token which was won. Can be negative for lost amounts. */ event TokenShift(address indexed _account, uint _disputeID, int _amount); /** @dev Emited when a juror wins arbitration fees. * @param _account The account affected. * @param _disputeID The ID of the dispute. * @param _amount The amount of weis which was won. */ event ArbitrationReward(address indexed _account, uint _disputeID, uint _amount); // **************************** // // * Modifiers * // // **************************** // modifier onlyBy(address _account) {require(msg.sender == _account); _;} modifier onlyDuring(Period _period) {require(period == _period); _;} modifier onlyGovernor() {require(msg.sender == governor); _;} /** @dev Constructor. * @param _pinakion The address of the pinakion contract. * @param _rng The random number generator which will be used. * @param _timePerPeriod The minimal time for each period (seconds). * @param _governor Address of the governor contract. */ constructor(Pinakion _pinakion, RNG _rng, uint[5] _timePerPeriod, address _governor) public { pinakion = _pinakion; rng = _rng; lastPeriodChange = now; timePerPeriod = _timePerPeriod; governor = _governor; } // **************************** // // * Functions interacting * // // * with Pinakion contract * // // **************************** // /** @dev Callback of approveAndCall - transfer pinakions of a juror in the contract. Should be called by the pinakion contract. TRUSTED. * @param _from The address making the transfer. * @param _amount Amount of tokens to transfer to Kleros (in basic units). */ function receiveApproval(address _from, uint _amount, address, bytes) public onlyBy(pinakion) { require(pinakion.transferFrom(_from, this, _amount)); jurors[_from].balance += _amount; } /** @dev Withdraw tokens. Note that we can't withdraw the tokens which are still atStake. * Jurors can't withdraw their tokens if they have deposited some during this session. * This is to prevent jurors from withdrawing tokens they could loose. * @param _value The amount to withdraw. */ function withdraw(uint _value) public { Juror storage juror = jurors[msg.sender]; require(juror.atStake <= juror.balance); // Make sure that there is no more at stake than owned to avoid overflow. require(_value <= juror.balance-juror.atStake); require(juror.lastSession != session); juror.balance -= _value; require(pinakion.transfer(msg.sender,_value)); } // **************************** // // * Court functions * // // * Modifying the state * // // **************************** // /** @dev To call to go to a new period. TRUSTED. */ function passPeriod() public { require(now-lastPeriodChange >= timePerPeriod[uint8(period)]); if (period == Period.Activation) { rnBlock = block.number + 1; rng.requestRN(rnBlock); period = Period.Draw; } else if (period == Period.Draw) { randomNumber = rng.getUncorrelatedRN(rnBlock); require(randomNumber != 0); period = Period.Vote; } else if (period == Period.Vote) { period = Period.Appeal; } else if (period == Period.Appeal) { period = Period.Execution; } else if (period == Period.Execution) { period = Period.Activation; ++session; segmentSize = 0; rnBlock = 0; randomNumber = 0; } lastPeriodChange = now; NewPeriod(period, session); } /** @dev Deposit tokens in order to have chances of being drawn. Note that once tokens are deposited, * there is no possibility of depositing more. * @param _value Amount of tokens (in basic units) to deposit. */ function activateTokens(uint _value) public onlyDuring(Period.Activation) { Juror storage juror = jurors[msg.sender]; require(_value <= juror.balance); require(_value >= minActivatedToken); require(juror.lastSession != session); // Verify that tokens were not already activated for this session. juror.lastSession = session; juror.segmentStart = segmentSize; segmentSize += _value; juror.segmentEnd = segmentSize; } /** @dev Vote a ruling. Juror must input the draw ID he was drawn. * Note that the complexity is O(d), where d is amount of times the juror was drawn. * Since being drawn multiple time is a rare occurrence and that a juror can always vote with less weight than it has, it is not a problem. * But note that it can lead to arbitration fees being kept by the contract and never distributed. * @param _disputeID The ID of the dispute the juror was drawn. * @param _ruling The ruling given. * @param _draws The list of draws the juror was drawn. Draw numbering starts at 1 and the numbers should be increasing. */ function voteRuling(uint _disputeID, uint _ruling, uint[] _draws) public onlyDuring(Period.Vote) { Dispute storage dispute = disputes[_disputeID]; Juror storage juror = jurors[msg.sender]; VoteCounter storage voteCounter = dispute.voteCounter[dispute.appeals]; require(dispute.lastSessionVote[msg.sender] != session); // Make sure juror hasn't voted yet. require(_ruling <= dispute.choices); // Note that it throws if the draws are incorrect. require(validDraws(msg.sender, _disputeID, _draws)); dispute.lastSessionVote[msg.sender] = session; voteCounter.voteCount[_ruling] += _draws.length; if (voteCounter.winningCount < voteCounter.voteCount[_ruling]) { voteCounter.winningCount = voteCounter.voteCount[_ruling]; voteCounter.winningChoice = _ruling; } else if (voteCounter.winningCount==voteCounter.voteCount[_ruling] && _draws.length!=0) { // Verify draw length to be non-zero to avoid the possibility of setting tie by casting 0 votes. voteCounter.winningChoice = 0; // It's currently a tie. } for (uint i = 0; i < _draws.length; ++i) { dispute.votes[dispute.appeals].push(Vote({ account: msg.sender, ruling: _ruling })); } juror.atStake += _draws.length * getStakePerDraw(); uint feeToPay = _draws.length * dispute.arbitrationFeePerJuror; msg.sender.transfer(feeToPay); ArbitrationReward(msg.sender, _disputeID, feeToPay); } /** @dev Steal part of the tokens and the arbitration fee of a juror who failed to vote. * Note that a juror who voted but without all his weight can't be penalized. * It is possible to not penalize with the maximum weight. * But note that it can lead to arbitration fees being kept by the contract and never distributed. * @param _jurorAddress Address of the juror to steal tokens from. * @param _disputeID The ID of the dispute the juror was drawn. * @param _draws The list of draws the juror was drawn. Numbering starts at 1 and the numbers should be increasing. */ function penalizeInactiveJuror(address _jurorAddress, uint _disputeID, uint[] _draws) public { Dispute storage dispute = disputes[_disputeID]; Juror storage inactiveJuror = jurors[_jurorAddress]; require(period > Period.Vote); require(dispute.lastSessionVote[_jurorAddress] != session); // Verify the juror hasn't voted. dispute.lastSessionVote[_jurorAddress] = session; // Update last session to avoid penalizing multiple times. require(validDraws(_jurorAddress, _disputeID, _draws)); uint penality = _draws.length * minActivatedToken * 2 * alpha / ALPHA_DIVISOR; penality = (penality < inactiveJuror.balance) ? penality : inactiveJuror.balance; // Make sure the penality is not higher than the balance. inactiveJuror.balance -= penality; TokenShift(_jurorAddress, _disputeID, -int(penality)); jurors[msg.sender].balance += penality / 2; // Give half of the penalty to the caller. TokenShift(msg.sender, _disputeID, int(penality / 2)); jurors[governor].balance += penality / 2; // The other half to the governor. TokenShift(governor, _disputeID, int(penality / 2)); msg.sender.transfer(_draws.length*dispute.arbitrationFeePerJuror); // Give the arbitration fees to the caller. } /** @dev Execute all the token repartition. * Note that this function could consume to much gas if there is too much votes. * It is O(v), where v is the number of votes for this dispute. * In the next version, there will also be a function to execute it in multiple calls * (but note that one shot execution, if possible, is less expensive). * @param _disputeID ID of the dispute. */ function oneShotTokenRepartition(uint _disputeID) public onlyDuring(Period.Execution) { Dispute storage dispute = disputes[_disputeID]; require(dispute.state == DisputeState.Open); require(dispute.session+dispute.appeals <= session); uint winningChoice = dispute.voteCounter[dispute.appeals].winningChoice; uint amountShift = getStakePerDraw(); for (uint i = 0; i <= dispute.appeals; ++i) { // If the result is not a tie, some parties are incoherent. Note that 0 (refuse to arbitrate) winning is not a tie. // Result is a tie if the winningChoice is 0 (refuse to arbitrate) and the choice 0 is not the most voted choice. // Note that in case of a "tie" among some choices including 0, parties who did not vote 0 are considered incoherent. if (winningChoice!=0 || (dispute.voteCounter[dispute.appeals].voteCount[0] == dispute.voteCounter[dispute.appeals].winningCount)) { uint totalToRedistribute = 0; uint nbCoherent = 0; // First loop to penalize the incoherent votes. for (uint j = 0; j < dispute.votes[i].length; ++j) { Vote storage vote = dispute.votes[i][j]; if (vote.ruling != winningChoice) { Juror storage juror = jurors[vote.account]; uint penalty = amountShift<juror.balance ? amountShift : juror.balance; juror.balance -= penalty; TokenShift(vote.account, _disputeID, int(-penalty)); totalToRedistribute += penalty; } else { ++nbCoherent; } } if (nbCoherent == 0) { // No one was coherent at this stage. Give the tokens to the governor. jurors[governor].balance += totalToRedistribute; TokenShift(governor, _disputeID, int(totalToRedistribute)); } else { // otherwise, redistribute them. uint toRedistribute = totalToRedistribute / nbCoherent; // Note that few fractions of tokens can be lost but due to the high amount of decimals we don't care. // Second loop to redistribute. for (j = 0; j < dispute.votes[i].length; ++j) { vote = dispute.votes[i][j]; if (vote.ruling == winningChoice) { juror = jurors[vote.account]; juror.balance += toRedistribute; TokenShift(vote.account, _disputeID, int(toRedistribute)); } } } } // Third loop to lower the atStake in order to unlock tokens. for (j = 0; j < dispute.votes[i].length; ++j) { vote = dispute.votes[i][j]; juror = jurors[vote.account]; juror.atStake -= amountShift; // Note that it can't underflow due to amountShift not changing between vote and redistribution. } } dispute.state = DisputeState.Executable; // Since it was solved in one shot, go directly to the executable step. } /** @dev Execute token repartition on a dispute for a specific number of votes. * This should only be called if oneShotTokenRepartition will throw because there are too many votes (will use too much gas). * Note that There are 3 iterations per vote. e.g. A dispute with 1 appeal (2 sessions) and 3 votes per session will have 18 iterations * @param _disputeID ID of the dispute. * @param _maxIterations the maxium number of votes to repartition in this iteration */ function multipleShotTokenRepartition(uint _disputeID, uint _maxIterations) public onlyDuring(Period.Execution) { Dispute storage dispute = disputes[_disputeID]; require(dispute.state <= DisputeState.Resolving); require(dispute.session+dispute.appeals <= session); dispute.state = DisputeState.Resolving; // Mark as resolving so oneShotTokenRepartition cannot be called on dispute. uint winningChoice = dispute.voteCounter[dispute.appeals].winningChoice; uint amountShift = getStakePerDraw(); uint currentIterations = 0; // Total votes we have repartitioned this iteration. for (uint i = dispute.currentAppealToRepartition; i <= dispute.appeals; ++i) { // Allocate space for new AppealsRepartitioned. if (dispute.appealsRepartitioned.length < i+1) { dispute.appealsRepartitioned.length++; } // If the result is a tie, no parties are incoherent and no need to move tokens. Note that 0 (refuse to arbitrate) winning is not a tie. if (winningChoice==0 && (dispute.voteCounter[dispute.appeals].voteCount[0] != dispute.voteCounter[dispute.appeals].winningCount)) { // If ruling is a tie we can skip to at stake. dispute.appealsRepartitioned[i].stage = RepartitionStage.AtStake; } // First loop to penalize the incoherent votes. if (dispute.appealsRepartitioned[i].stage == RepartitionStage.Incoherent) { for (uint j = dispute.appealsRepartitioned[i].currentIncoherentVote; j < dispute.votes[i].length; ++j) { if (currentIterations >= _maxIterations) { return; } Vote storage vote = dispute.votes[i][j]; if (vote.ruling != winningChoice) { Juror storage juror = jurors[vote.account]; uint penalty = amountShift<juror.balance ? amountShift : juror.balance; juror.balance -= penalty; TokenShift(vote.account, _disputeID, int(-penalty)); dispute.appealsRepartitioned[i].totalToRedistribute += penalty; } else { ++dispute.appealsRepartitioned[i].nbCoherent; } ++dispute.appealsRepartitioned[i].currentIncoherentVote; ++currentIterations; } dispute.appealsRepartitioned[i].stage = RepartitionStage.Coherent; } // Second loop to reward coherent voters if (dispute.appealsRepartitioned[i].stage == RepartitionStage.Coherent) { if (dispute.appealsRepartitioned[i].nbCoherent == 0) { // No one was coherent at this stage. Give the tokens to the governor. jurors[governor].balance += dispute.appealsRepartitioned[i].totalToRedistribute; TokenShift(governor, _disputeID, int(dispute.appealsRepartitioned[i].totalToRedistribute)); dispute.appealsRepartitioned[i].stage = RepartitionStage.AtStake; } else { // Otherwise, redistribute them. uint toRedistribute = dispute.appealsRepartitioned[i].totalToRedistribute / dispute.appealsRepartitioned[i].nbCoherent; // Note that few fractions of tokens can be lost but due to the high amount of decimals we don't care. // Second loop to redistribute. for (j = dispute.appealsRepartitioned[i].currentCoherentVote; j < dispute.votes[i].length; ++j) { if (currentIterations >= _maxIterations) { return; } vote = dispute.votes[i][j]; if (vote.ruling == winningChoice) { juror = jurors[vote.account]; juror.balance += toRedistribute; TokenShift(vote.account, _disputeID, int(toRedistribute)); } ++currentIterations; ++dispute.appealsRepartitioned[i].currentCoherentVote; } dispute.appealsRepartitioned[i].stage = RepartitionStage.AtStake; } } if (dispute.appealsRepartitioned[i].stage == RepartitionStage.AtStake) { // Third loop to lower the atStake in order to unlock tokens. for (j = dispute.appealsRepartitioned[i].currentAtStakeVote; j < dispute.votes[i].length; ++j) { if (currentIterations >= _maxIterations) { return; } vote = dispute.votes[i][j]; juror = jurors[vote.account]; juror.atStake -= amountShift; // Note that it can't underflow due to amountShift not changing between vote and redistribution. ++currentIterations; ++dispute.appealsRepartitioned[i].currentAtStakeVote; } dispute.appealsRepartitioned[i].stage = RepartitionStage.Complete; } if (dispute.appealsRepartitioned[i].stage == RepartitionStage.Complete) { ++dispute.currentAppealToRepartition; } } dispute.state = DisputeState.Executable; } // **************************** // // * Court functions * // // * Constant and Pure * // // **************************** // /** @dev Return the amount of jurors which are or will be drawn in the dispute. * The number of jurors is doubled and 1 is added at each appeal. We have proven the formula by recurrence. * This avoid having a variable number of jurors which would be updated in order to save gas. * @param _disputeID The ID of the dispute we compute the amount of jurors. * @return nbJurors The number of jurors which are drawn. */ function amountJurors(uint _disputeID) public view returns (uint nbJurors) { Dispute storage dispute = disputes[_disputeID]; return (dispute.initialNumberJurors + 1) * 2**dispute.appeals - 1; } /** @dev Must be used to verify that a juror has been draw at least _draws.length times. * We have to require the user to specify the draws that lead the juror to be drawn. * Because doing otherwise (looping through all draws) could consume too much gas. * @param _jurorAddress Address of the juror we want to verify draws. * @param _disputeID The ID of the dispute the juror was drawn. * @param _draws The list of draws the juror was drawn. It draw numbering starts at 1 and the numbers should be increasing. * Note that in most cases this list will just contain 1 number. * @param valid true if the draws are valid. */ function validDraws(address _jurorAddress, uint _disputeID, uint[] _draws) public view returns (bool valid) { uint draw = 0; Juror storage juror = jurors[_jurorAddress]; Dispute storage dispute = disputes[_disputeID]; uint nbJurors = amountJurors(_disputeID); if (juror.lastSession != session) return false; // Make sure that the tokens were deposited for this session. if (dispute.session+dispute.appeals != session) return false; // Make sure there is currently a dispute. if (period <= Period.Draw) return false; // Make sure that jurors are already drawn. for (uint i = 0; i < _draws.length; ++i) { if (_draws[i] <= draw) return false; // Make sure that draws are always increasing to avoid someone inputing the same multiple times. draw = _draws[i]; if (draw > nbJurors) return false; uint position = uint(keccak256(randomNumber, _disputeID, draw)) % segmentSize; // Random position on the segment for draw. require(position >= juror.segmentStart); require(position < juror.segmentEnd); } return true; } // **************************** // // * Arbitrator functions * // // * Modifying the state * // // **************************** // /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Null for the default number. Otherwise, first 16 bytes will be used to return the number of jurors. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes _extraData) public payable returns (uint disputeID) { uint16 nbJurors = extraDataToNbJurors(_extraData); require(msg.value >= arbitrationCost(_extraData)); disputeID = disputes.length++; Dispute storage dispute = disputes[disputeID]; dispute.arbitrated = Arbitrable(msg.sender); if (period < Period.Draw) // If drawing did not start schedule it for the current session. dispute.session = session; else // Otherwise schedule it for the next one. dispute.session = session+1; dispute.choices = _choices; dispute.initialNumberJurors = nbJurors; dispute.arbitrationFeePerJuror = arbitrationFeePerJuror; // We store it as the general fee can be changed through the governance mechanism. dispute.votes.length++; dispute.voteCounter.length++; DisputeCreation(disputeID, Arbitrable(msg.sender)); return disputeID; } /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Standard but not used by this contract. */ function appeal(uint _disputeID, bytes _extraData) public payable onlyDuring(Period.Appeal) { super.appeal(_disputeID,_extraData); Dispute storage dispute = disputes[_disputeID]; require(msg.value >= appealCost(_disputeID, _extraData)); require(dispute.session+dispute.appeals == session); // Dispute of the current session. require(dispute.arbitrated == msg.sender); dispute.appeals++; dispute.votes.length++; dispute.voteCounter.length++; } /** @dev Execute the ruling of a dispute which is in the state executable. UNTRUSTED. * @param disputeID ID of the dispute to execute the ruling. */ function executeRuling(uint disputeID) public { Dispute storage dispute = disputes[disputeID]; require(dispute.state == DisputeState.Executable); dispute.state = DisputeState.Executed; dispute.arbitrated.rule(disputeID, dispute.voteCounter[dispute.appeals].winningChoice); } // **************************** // // * Arbitrator functions * // // * Constant and pure * // // **************************** // /** @dev Compute the cost of arbitration. It is recommended not to increase it often, * as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Null for the default number. Other first 16 bits will be used to return the number of jurors. * @return fee Amount to be paid. */ function arbitrationCost(bytes _extraData) public view returns (uint fee) { return extraDataToNbJurors(_extraData) * arbitrationFeePerJuror; } /** @dev Compute the cost of appeal. It is recommended not to increase it often, * as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Is not used there. * @return fee Amount to be paid. */ function appealCost(uint _disputeID, bytes _extraData) public view returns (uint fee) { Dispute storage dispute = disputes[_disputeID]; if(dispute.appeals >= maxAppeals) return NON_PAYABLE_AMOUNT; return (2*amountJurors(_disputeID) + 1) * dispute.arbitrationFeePerJuror; } /** @dev Compute the amount of jurors to be drawn. * @param _extraData Null for the default number. Other first 16 bits will be used to return the number of jurors. * Note that it does not check that the number of jurors is odd, but users are advised to choose a odd number of jurors. */ function extraDataToNbJurors(bytes _extraData) internal view returns (uint16 nbJurors) { if (_extraData.length < 2) return defaultNumberJuror; else return (uint16(_extraData[0]) << 8) + uint16(_extraData[1]); } /** @dev Compute the minimum activated pinakions in alpha. * Note there may be multiple draws for a single user on a single dispute. */ function getStakePerDraw() public view returns (uint minActivatedTokenInAlpha) { return (alpha * minActivatedToken) / ALPHA_DIVISOR; } // **************************** // // * Constant getters * // // **************************** // /** @dev Getter for account in Vote. * @param _disputeID ID of the dispute. * @param _appeals Which appeal (or 0 for the initial session). * @param _voteID The ID of the vote for this appeal (or initial session). * @return account The address of the voter. */ function getVoteAccount(uint _disputeID, uint _appeals, uint _voteID) public view returns (address account) { return disputes[_disputeID].votes[_appeals][_voteID].account; } /** @dev Getter for ruling in Vote. * @param _disputeID ID of the dispute. * @param _appeals Which appeal (or 0 for the initial session). * @param _voteID The ID of the vote for this appeal (or initial session). * @return ruling The ruling given by the voter. */ function getVoteRuling(uint _disputeID, uint _appeals, uint _voteID) public view returns (uint ruling) { return disputes[_disputeID].votes[_appeals][_voteID].ruling; } /** @dev Getter for winningChoice in VoteCounter. * @param _disputeID ID of the dispute. * @param _appeals Which appeal (or 0 for the initial session). * @return winningChoice The currently winning choice (or 0 if it's tied). Note that 0 can also be return if the majority refuses to arbitrate. */ function getWinningChoice(uint _disputeID, uint _appeals) public view returns (uint winningChoice) { return disputes[_disputeID].voteCounter[_appeals].winningChoice; } /** @dev Getter for winningCount in VoteCounter. * @param _disputeID ID of the dispute. * @param _appeals Which appeal (or 0 for the initial session). * @return winningCount The amount of votes the winning choice (or those who are tied) has. */ function getWinningCount(uint _disputeID, uint _appeals) public view returns (uint winningCount) { return disputes[_disputeID].voteCounter[_appeals].winningCount; } /** @dev Getter for voteCount in VoteCounter. * @param _disputeID ID of the dispute. * @param _appeals Which appeal (or 0 for the initial session). * @param _choice The choice. * @return voteCount The amount of votes the winning choice (or those who are tied) has. */ function getVoteCount(uint _disputeID, uint _appeals, uint _choice) public view returns (uint voteCount) { return disputes[_disputeID].voteCounter[_appeals].voteCount[_choice]; } /** @dev Getter for lastSessionVote in Dispute. * @param _disputeID ID of the dispute. * @param _juror The juror we want to get the last session he voted. * @return lastSessionVote The last session the juror voted. */ function getLastSessionVote(uint _disputeID, address _juror) public view returns (uint lastSessionVote) { return disputes[_disputeID].lastSessionVote[_juror]; } /** @dev Is the juror drawn in the draw of the dispute. * @param _disputeID ID of the dispute. * @param _juror The juror. * @param _draw The draw. Note that it starts at 1. * @return drawn True if the juror is drawn, false otherwise. */ function isDrawn(uint _disputeID, address _juror, uint _draw) public view returns (bool drawn) { Dispute storage dispute = disputes[_disputeID]; Juror storage juror = jurors[_juror]; if (juror.lastSession != session || (dispute.session+dispute.appeals != session) || period<=Period.Draw || _draw>amountJurors(_disputeID) || _draw==0 || segmentSize==0 ) { return false; } else { uint position = uint(keccak256(randomNumber,_disputeID,_draw)) % segmentSize; return (position >= juror.segmentStart) && (position < juror.segmentEnd); } } /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The current ruling which will be given if there is no appeal. If it is not available, return 0. */ function currentRuling(uint _disputeID) public view returns (uint ruling) { Dispute storage dispute = disputes[_disputeID]; return dispute.voteCounter[dispute.appeals].winningChoice; } /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) public view returns (DisputeStatus status) { Dispute storage dispute = disputes[_disputeID]; if (dispute.session+dispute.appeals < session) // Dispute of past session. return DisputeStatus.Solved; else if(dispute.session+dispute.appeals == session) { // Dispute of current session. if (dispute.state == DisputeState.Open) { if (period < Period.Appeal) return DisputeStatus.Waiting; else if (period == Period.Appeal) return DisputeStatus.Appealable; else return DisputeStatus.Solved; } else return DisputeStatus.Solved; } else return DisputeStatus.Waiting; // Dispute for future session. } // **************************** // // * Governor Functions * // // **************************** // /** @dev General call function where the contract execute an arbitrary call with data and ETH following governor orders. * @param _data Transaction data. * @param _value Transaction value. * @param _target Transaction target. */ function executeOrder(bytes32 _data, uint _value, address _target) public onlyGovernor { _target.call.value(_value)(_data); } /** @dev Setter for rng. * @param _rng An instance of RNG. */ function setRng(RNG _rng) public onlyGovernor { rng = _rng; } /** @dev Setter for arbitrationFeePerJuror. * @param _arbitrationFeePerJuror The fee which will be paid to each juror. */ function setArbitrationFeePerJuror(uint _arbitrationFeePerJuror) public onlyGovernor { arbitrationFeePerJuror = _arbitrationFeePerJuror; } /** @dev Setter for defaultNumberJuror. * @param _defaultNumberJuror Number of drawn jurors unless specified otherwise. */ function setDefaultNumberJuror(uint16 _defaultNumberJuror) public onlyGovernor { defaultNumberJuror = _defaultNumberJuror; } /** @dev Setter for minActivatedToken. * @param _minActivatedToken Minimum of tokens to be activated (in basic units). */ function setMinActivatedToken(uint _minActivatedToken) public onlyGovernor { minActivatedToken = _minActivatedToken; } /** @dev Setter for timePerPeriod. * @param _timePerPeriod The minimum time each period lasts (seconds). */ function setTimePerPeriod(uint[5] _timePerPeriod) public onlyGovernor { timePerPeriod = _timePerPeriod; } /** @dev Setter for alpha. * @param _alpha Alpha in ‱. */ function setAlpha(uint _alpha) public onlyGovernor { alpha = _alpha; } /** @dev Setter for maxAppeals. * @param _maxAppeals Number of times a dispute can be appealed. When exceeded appeal cost becomes NON_PAYABLE_AMOUNT. */ function setMaxAppeals(uint _maxAppeals) public onlyGovernor { maxAppeals = _maxAppeals; } /** @dev Setter for governor. * @param _governor Address of the governor contract. */ function setGovernor(address _governor) public onlyGovernor { governor = _governor; } }
The number of choices available to the jurors.
uint choices;
1,073,754
[ 1, 1986, 1300, 434, 7246, 2319, 358, 326, 525, 295, 1383, 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 ]
[ 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, 2254, 7246, 31, 1171, 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, -100 ]
./full_match/80001/0xBB7a4eB5478CFF80FEF20d96526e221a5e0526f3/sources/contracts/UpdateStruct.sol
battle was a tie - send original waver back
function redeemEarnings(uint _battleNumber) public payable { Battle storage indBattle = battles[_battleNumber]; require(indBattle.winnerOfGulag!=0,"Sorry, this Gulag either hasn't finished or hasn't started yet"); require (indBattle.battleStarted==true,"Battle hasn't even started yet"); require (indBattle.wagerPeriodOver==true,"Wager period hasn't finished yet"); if (indBattle.winnerOfGulag==3) { require(wagerByAdressForEachBattle[msg.sender][_battleNumber]>0,"Sorry, you didn't wager on this gulag"); require(wagerByAddressForEachBattleByFighter[msg.sender][_battleNumber][0]>0,"Sorry, you didn't wager on the winner (creator) of this gulag"); payable(msg.sender).transfer(wagerByAdressForEachBattle[msg.sender][_battleNumber]); } else if (indBattle.winnerOfGulag==1) { require(wagerByAdressForEachBattle[msg.sender][_battleNumber]>0,"Sorry, you didn't wager on this gulag"); require(wagerByAddressForEachBattleByFighter[msg.sender][_battleNumber][0]>0,"Sorry, you didn't wager on the winner (creator) of this gulag"); uint redeemableFractionOfLosingPot = (wagerByAddressForEachBattleByFighter[msg.sender][_battleNumber][0]/mappedTotalWagerAmountByBattleForCreator[_battleNumber]*mappedTotalWagerAmountByBattleForChallenger[_battleNumber]); payable(msg.sender).transfer(wagerByAddressForEachBattleByFighter[msg.sender][_battleNumber][0]+redeemableFractionOfLosingPot); } else if (indBattle.winnerOfGulag==2) { require(wagerByAdressForEachBattle[msg.sender][_battleNumber]>0,"Sorry, you didn't wager on the winner of this gulag"); require(wagerByAddressForEachBattleByFighter[msg.sender][_battleNumber][1]>0,"Sorry, you didn't wager on the winner (challenger) of this gulag"); uint redeemableFractionOfLosingPot = (wagerByAddressForEachBattleByFighter[msg.sender][_battleNumber][1]/mappedTotalWagerAmountByBattleForChallenger[_battleNumber]*mappedTotalWagerAmountByBattleForChallenger[_battleNumber]); payable(msg.sender).transfer(wagerByAddressForEachBattleByFighter[msg.sender][_battleNumber][1]+redeemableFractionOfLosingPot); } }
5,661,342
[ 1, 70, 4558, 298, 1703, 279, 25318, 300, 1366, 2282, 341, 21851, 1473, 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, 283, 24903, 41, 1303, 899, 12, 11890, 389, 70, 4558, 298, 1854, 13, 1071, 8843, 429, 288, 203, 3639, 605, 4558, 298, 2502, 1547, 38, 4558, 298, 273, 324, 4558, 1040, 63, 67, 70, 4558, 298, 1854, 15533, 203, 3639, 2583, 12, 728, 38, 4558, 298, 18, 91, 7872, 951, 43, 332, 346, 5, 33, 20, 10837, 28898, 16, 333, 611, 332, 346, 3344, 13342, 1404, 6708, 578, 13342, 1404, 5746, 4671, 8863, 203, 3639, 2583, 261, 728, 38, 4558, 298, 18, 70, 4558, 298, 9217, 631, 3767, 10837, 38, 4558, 298, 13342, 1404, 5456, 5746, 4671, 8863, 203, 3639, 2583, 261, 728, 38, 4558, 298, 18, 91, 6817, 5027, 4851, 631, 3767, 10837, 59, 6817, 3879, 13342, 1404, 6708, 4671, 8863, 203, 3639, 309, 261, 728, 38, 4558, 298, 18, 91, 7872, 951, 43, 332, 346, 631, 23, 13, 288, 203, 5411, 2583, 12, 91, 6817, 858, 1871, 663, 1290, 3442, 38, 4558, 298, 63, 3576, 18, 15330, 6362, 67, 70, 4558, 298, 1854, 65, 34, 20, 10837, 28898, 16, 1846, 10242, 1404, 341, 6817, 603, 333, 314, 332, 346, 8863, 203, 5411, 2583, 12, 91, 6817, 858, 1887, 1290, 3442, 38, 4558, 298, 858, 42, 18117, 63, 3576, 18, 15330, 6362, 67, 70, 4558, 298, 1854, 6362, 20, 65, 34, 20, 10837, 28898, 16, 1846, 10242, 1404, 341, 6817, 603, 326, 5657, 1224, 261, 20394, 13, 434, 333, 314, 332, 346, 8863, 203, 5411, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 91, 6817, 858, 1871, 663, 1290, 3442, 2 ]
pragma solidity ^0.4.21; // File: contracts/ISimpleCrowdsale.sol interface ISimpleCrowdsale { function getSoftCap() external view returns(uint256); function isContributorInLists(address contributorAddress) external view returns(bool); function processReservationFundContribution( address contributor, uint256 tokenAmount, uint256 tokenBonusAmount ) external payable; } // File: contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract. */ function Ownable(address _owner) public { owner = _owner == address(0) ? msg.sender : _owner; } /** * @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 != owner); newOwner = _newOwner; } /** * @dev confirm ownership by a new owner */ function confirmOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = 0x0; } } // File: contracts/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @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; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: contracts/fund/ICrowdsaleFund.sol /** * @title ICrowdsaleFund * @dev Fund methods used by crowdsale contract */ interface ICrowdsaleFund { /** * @dev Function accepts user`s contributed ether and logs contribution * @param contributor Contributor wallet address. */ function processContribution(address contributor) external payable; /** * @dev Function is called on the end of successful crowdsale */ function onCrowdsaleEnd() external; /** * @dev Function is called if crowdsale failed to reach soft cap */ function enableCrowdsaleRefund() external; } // File: contracts/fund/ICrowdsaleReservationFund.sol /** * @title ICrowdsaleReservationFund * @dev ReservationFund methods used by crowdsale contract */ interface ICrowdsaleReservationFund { /** * @dev Check if contributor has transactions */ function canCompleteContribution(address contributor) external returns(bool); /** * @dev Complete contribution * @param contributor Contributor`s address */ function completeContribution(address contributor) external; /** * @dev Function accepts user`s contributed ether and amount of tokens to issue * @param contributor Contributor wallet address. * @param _tokensToIssue Token amount to issue * @param _bonusTokensToIssue Bonus token amount to issue */ function processContribution(address contributor, uint256 _tokensToIssue, uint256 _bonusTokensToIssue) external payable; /** * @dev Function returns current user`s contributed ether amount */ function contributionsOf(address contributor) external returns(uint256); /** * @dev Function is called on the end of successful crowdsale */ function onCrowdsaleEnd() external; } // File: contracts/token/IERC20Token.sol /** * @title IERC20Token - ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract IERC20Token { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256 balance); 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); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // File: contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ contract SafeMath { /** * @dev constructor */ function SafeMath() public { } function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(a >= b); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/token/LockedTokens.sol /** * @title LockedTokens * @dev Lock tokens for certain period of time */ contract LockedTokens is SafeMath { struct Tokens { uint256 amount; uint256 lockEndTime; bool released; } event TokensUnlocked(address _to, uint256 _value); IERC20Token public token; address public crowdsaleAddress; mapping(address => Tokens[]) public walletTokens; /** * @dev LockedTokens constructor * @param _token ERC20 compatible token contract * @param _crowdsaleAddress Crowdsale contract address */ function LockedTokens(IERC20Token _token, address _crowdsaleAddress) public { token = _token; crowdsaleAddress = _crowdsaleAddress; } /** * @dev Functions locks tokens * @param _to Wallet address to transfer tokens after _lockEndTime * @param _amount Amount of tokens to lock * @param _lockEndTime End of lock period */ function addTokens(address _to, uint256 _amount, uint256 _lockEndTime) external { require(msg.sender == crowdsaleAddress); walletTokens[_to].push(Tokens({amount: _amount, lockEndTime: _lockEndTime, released: false})); } /** * @dev Called by owner of locked tokens to release them */ function releaseTokens() public { require(walletTokens[msg.sender].length > 0); for(uint256 i = 0; i < walletTokens[msg.sender].length; i++) { if(!walletTokens[msg.sender][i].released && now >= walletTokens[msg.sender][i].lockEndTime) { walletTokens[msg.sender][i].released = true; token.transfer(msg.sender, walletTokens[msg.sender][i].amount); TokensUnlocked(msg.sender, walletTokens[msg.sender][i].amount); } } } } // File: contracts/ownership/MultiOwnable.sol /** * @title MultiOwnable * @dev The MultiOwnable contract has owners addresses and provides basic authorization control * functions, this simplifies the implementation of "users permissions". */ contract MultiOwnable { address public manager; // address used to set owners address[] public owners; mapping(address => bool) public ownerByAddress; event SetOwners(address[] owners); modifier onlyOwner() { require(ownerByAddress[msg.sender] == true); _; } /** * @dev MultiOwnable constructor sets the manager */ function MultiOwnable() public { manager = msg.sender; } /** * @dev Function to set owners addresses */ function setOwners(address[] _owners) public { require(msg.sender == manager); _setOwners(_owners); } function _setOwners(address[] _owners) internal { for(uint256 i = 0; i < owners.length; i++) { ownerByAddress[owners[i]] = false; } for(uint256 j = 0; j < _owners.length; j++) { ownerByAddress[_owners[j]] = true; } owners = _owners; SetOwners(_owners); } function getOwners() public constant returns (address[]) { return owners; } } // File: contracts/token/ERC20Token.sol /** * @title ERC20Token - ERC20 base implementation * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Token is IERC20Token, SafeMath { mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(balances[msg.sender] >= _value); balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256) { return allowed[_owner][_spender]; } } // File: contracts/token/ITokenEventListener.sol /** * @title ITokenEventListener * @dev Interface which should be implemented by token listener */ interface ITokenEventListener { /** * @dev Function is called after token transfer/transferFrom * @param _from Sender address * @param _to Receiver address * @param _value Amount of tokens */ function onTokenTransfer(address _from, address _to, uint256 _value) external; } // File: contracts/token/ManagedToken.sol /** * @title ManagedToken * @dev ERC20 compatible token with issue and destroy facilities * @dev All transfers can be monitored by token event listener */ contract ManagedToken is ERC20Token, MultiOwnable { bool public allowTransfers = false; bool public issuanceFinished = false; ITokenEventListener public eventListener; event AllowTransfersChanged(bool _newState); event Issue(address indexed _to, uint256 _value); event Destroy(address indexed _from, uint256 _value); event IssuanceFinished(); modifier transfersAllowed() { require(allowTransfers); _; } modifier canIssue() { require(!issuanceFinished); _; } /** * @dev ManagedToken constructor * @param _listener Token listener(address can be 0x0) * @param _owners Owners list */ function ManagedToken(address _listener, address[] _owners) public { if(_listener != address(0)) { eventListener = ITokenEventListener(_listener); } _setOwners(_owners); } /** * @dev Enable/disable token transfers. Can be called only by owners * @param _allowTransfers True - allow False - disable */ function setAllowTransfers(bool _allowTransfers) external onlyOwner { allowTransfers = _allowTransfers; AllowTransfersChanged(_allowTransfers); } /** * @dev Set/remove token event listener * @param _listener Listener address (Contract must implement ITokenEventListener interface) */ function setListener(address _listener) public onlyOwner { if(_listener != address(0)) { eventListener = ITokenEventListener(_listener); } else { delete eventListener; } } function transfer(address _to, uint256 _value) public transfersAllowed returns (bool) { bool success = super.transfer(_to, _value); if(hasListener() && success) { eventListener.onTokenTransfer(msg.sender, _to, _value); } return success; } function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool) { bool success = super.transferFrom(_from, _to, _value); if(hasListener() && success) { eventListener.onTokenTransfer(_from, _to, _value); } return success; } function hasListener() internal view returns(bool) { if(eventListener == address(0)) { return false; } return true; } /** * @dev Issue tokens to specified wallet * @param _to Wallet address * @param _value Amount of tokens */ function issue(address _to, uint256 _value) external onlyOwner canIssue { totalSupply = safeAdd(totalSupply, _value); balances[_to] = safeAdd(balances[_to], _value); Issue(_to, _value); Transfer(address(0), _to, _value); } /** * @dev Destroy tokens on specified address (Called by owner or token holder) * @dev Fund contract address must be in the list of owners to burn token during refund * @param _from Wallet address * @param _value Amount of tokens to destroy */ function destroy(address _from, uint256 _value) external { require(ownerByAddress[msg.sender] || msg.sender == _from); require(balances[_from] >= _value); totalSupply = safeSub(totalSupply, _value); balances[_from] = safeSub(balances[_from], _value); Transfer(_from, address(0), _value); Destroy(_from, _value); } /** * @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 OpenZeppelin StandardToken.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, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = safeAdd(allowed[msg.sender][_spender], _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 OpenZeppelin StandardToken.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, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = safeSub(oldValue, _subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Finish token issuance * @return True if success */ function finishIssuance() public onlyOwner returns (bool) { issuanceFinished = true; IssuanceFinished(); return true; } } // File: contracts/token/TransferLimitedToken.sol /** * @title TransferLimitedToken * @dev Token with ability to limit transfers within wallets included in limitedWallets list for certain period of time */ contract TransferLimitedToken is ManagedToken { uint256 public constant LIMIT_TRANSFERS_PERIOD = 365 days; mapping(address => bool) public limitedWallets; uint256 public limitEndDate; address public limitedWalletsManager; bool public isLimitEnabled; event TransfersEnabled(); modifier onlyManager() { require(msg.sender == limitedWalletsManager); _; } /** * @dev Check if transfer between addresses is available * @param _from From address * @param _to To address */ modifier canTransfer(address _from, address _to) { require(now >= limitEndDate || !isLimitEnabled || (!limitedWallets[_from] && !limitedWallets[_to])); _; } /** * @dev TransferLimitedToken constructor * @param _limitStartDate Limit start date * @param _listener Token listener(address can be 0x0) * @param _owners Owners list * @param _limitedWalletsManager Address used to add/del wallets from limitedWallets */ function TransferLimitedToken( uint256 _limitStartDate, address _listener, address[] _owners, address _limitedWalletsManager ) public ManagedToken(_listener, _owners) { limitEndDate = _limitStartDate + LIMIT_TRANSFERS_PERIOD; isLimitEnabled = true; limitedWalletsManager = _limitedWalletsManager; } /** * @dev Enable token transfers */ function enableTransfers() public { require(msg.sender == limitedWalletsManager); allowTransfers = true; TransfersEnabled(); } /** * @dev Add address to limitedWallets * @dev Can be called only by manager */ function addLimitedWalletAddress(address _wallet) public { require(msg.sender == limitedWalletsManager || ownerByAddress[msg.sender]); limitedWallets[_wallet] = true; } /** * @dev Del address from limitedWallets * @dev Can be called only by manager */ function delLimitedWalletAddress(address _wallet) public onlyManager { limitedWallets[_wallet] = false; } /** * @dev Disable transfer limit manually. Can be called only by manager */ function disableLimit() public onlyManager { isLimitEnabled = false; } function transfer(address _to, uint256 _value) public canTransfer(msg.sender, _to) returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public canTransfer(_from, _to) returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public canTransfer(msg.sender, _spender) returns (bool) { return super.approve(_spender,_value); } } // File: contracts/Crowdsale.sol contract TheAbyssDAICO is Ownable, SafeMath, Pausable, ISimpleCrowdsale { enum AdditionalBonusState { Unavailable, Active, Applied } uint256 public constant ADDITIONAL_BONUS_NUM = 3; uint256 public constant ADDITIONAL_BONUS_DENOM = 100; uint256 public constant ETHER_MIN_CONTRIB = 0.2 ether; uint256 public constant ETHER_MAX_CONTRIB = 20 ether; uint256 public constant ETHER_MIN_CONTRIB_PRIVATE = 100 ether; uint256 public constant ETHER_MAX_CONTRIB_PRIVATE = 3000 ether; uint256 public constant ETHER_MIN_CONTRIB_USA = 0.2 ether; uint256 public constant ETHER_MAX_CONTRIB_USA = 20 ether; uint256 public constant SALE_START_TIME = 1524060000; // 18.04.2018 14:00:00 UTC uint256 public constant SALE_END_TIME = 1526479200; // 16.05.2018 14:00:00 UTC uint256 public constant BONUS_WINDOW_1_END_TIME = SALE_START_TIME + 2 days; uint256 public constant BONUS_WINDOW_2_END_TIME = SALE_START_TIME + 7 days; uint256 public constant BONUS_WINDOW_3_END_TIME = SALE_START_TIME + 14 days; uint256 public constant BONUS_WINDOW_4_END_TIME = SALE_START_TIME + 21 days; uint256 public constant MAX_CONTRIB_CHECK_END_TIME = SALE_START_TIME + 1 days; uint256 public constant BNB_TOKEN_PRICE_NUM = 169; uint256 public constant BNB_TOKEN_PRICE_DENOM = 1; uint256 public tokenPriceNum = 0; uint256 public tokenPriceDenom = 0; TransferLimitedToken public token; ICrowdsaleFund public fund; ICrowdsaleReservationFund public reservationFund; LockedTokens public lockedTokens; mapping(address => bool) public whiteList; mapping(address => bool) public privilegedList; mapping(address => AdditionalBonusState) public additionalBonusOwnerState; mapping(address => uint256) public userTotalContributed; address public bnbTokenWallet; address public referralTokenWallet; address public foundationTokenWallet; address public advisorsTokenWallet; address public companyTokenWallet; address public reserveTokenWallet; address public bountyTokenWallet; uint256 public totalEtherContributed = 0; uint256 public rawTokenSupply = 0; // BNB IERC20Token public bnbToken; uint256 public BNB_HARD_CAP = 300000 ether; // 300K BNB uint256 public BNB_MIN_CONTRIB = 1000 ether; // 1K BNB mapping(address => uint256) public bnbContributions; uint256 public totalBNBContributed = 0; bool public bnbWithdrawEnabled = false; uint256 public hardCap = 0; // World hard cap will be set right before Token Sale uint256 public softCap = 0; // World soft cap will be set right before Token Sale bool public bnbRefundEnabled = false; event LogContribution(address contributor, uint256 amountWei, uint256 tokenAmount, uint256 tokenBonus, bool additionalBonusApplied, uint256 timestamp); event ReservationFundContribution(address contributor, uint256 amountWei, uint256 tokensToIssue, uint256 bonusTokensToIssue, uint256 timestamp); event LogBNBContribution(address contributor, uint256 amountBNB, uint256 tokenAmount, uint256 tokenBonus, bool additionalBonusApplied, uint256 timestamp); modifier checkContribution() { require(isValidContribution()); _; } modifier checkBNBContribution() { require(isValidBNBContribution()); _; } modifier checkCap() { require(validateCap()); _; } modifier checkTime() { require(now >= SALE_START_TIME && now <= SALE_END_TIME); _; } function TheAbyssDAICO( address bnbTokenAddress, address tokenAddress, address fundAddress, address reservationFundAddress, address _bnbTokenWallet, address _referralTokenWallet, address _foundationTokenWallet, address _advisorsTokenWallet, address _companyTokenWallet, address _reserveTokenWallet, address _bountyTokenWallet, address _owner ) public Ownable(_owner) { require(tokenAddress != address(0)); bnbToken = IERC20Token(bnbTokenAddress); token = TransferLimitedToken(tokenAddress); fund = ICrowdsaleFund(fundAddress); reservationFund = ICrowdsaleReservationFund(reservationFundAddress); bnbTokenWallet = _bnbTokenWallet; referralTokenWallet = _referralTokenWallet; foundationTokenWallet = _foundationTokenWallet; advisorsTokenWallet = _advisorsTokenWallet; companyTokenWallet = _companyTokenWallet; reserveTokenWallet = _reserveTokenWallet; bountyTokenWallet = _bountyTokenWallet; } /** * @dev check if address can contribute */ function isContributorInLists(address contributor) external view returns(bool) { return whiteList[contributor] || privilegedList[contributor] || token.limitedWallets(contributor); } /** * @dev check contribution amount and time */ function isValidContribution() internal view returns(bool) { uint256 currentUserContribution = safeAdd(msg.value, userTotalContributed[msg.sender]); if(whiteList[msg.sender] && msg.value >= ETHER_MIN_CONTRIB) { if(now <= MAX_CONTRIB_CHECK_END_TIME && currentUserContribution > ETHER_MAX_CONTRIB ) { return false; } return true; } if(privilegedList[msg.sender] && msg.value >= ETHER_MIN_CONTRIB_PRIVATE) { if(now <= MAX_CONTRIB_CHECK_END_TIME && currentUserContribution > ETHER_MAX_CONTRIB_PRIVATE ) { return false; } return true; } if(token.limitedWallets(msg.sender) && msg.value >= ETHER_MIN_CONTRIB_USA) { if(now <= MAX_CONTRIB_CHECK_END_TIME && currentUserContribution > ETHER_MAX_CONTRIB_USA) { return false; } return true; } return false; } /** * @dev Check hard cap overflow */ function validateCap() internal view returns(bool){ if(msg.value <= safeSub(hardCap, totalEtherContributed)) { return true; } return false; } /** * @dev Set token price once before start of crowdsale */ function setTokenPrice(uint256 _tokenPriceNum, uint256 _tokenPriceDenom) public onlyOwner { require(tokenPriceNum == 0 && tokenPriceDenom == 0); require(_tokenPriceNum > 0 && _tokenPriceDenom > 0); tokenPriceNum = _tokenPriceNum; tokenPriceDenom = _tokenPriceDenom; } /** * @dev Set hard cap. * @param _hardCap - Hard cap value */ function setHardCap(uint256 _hardCap) public onlyOwner { require(hardCap == 0); hardCap = _hardCap; } /** * @dev Set soft cap. * @param _softCap - Soft cap value */ function setSoftCap(uint256 _softCap) public onlyOwner { require(softCap == 0); softCap = _softCap; } /** * @dev Get soft cap amount **/ function getSoftCap() external view returns(uint256) { return softCap; } /** * @dev Check bnb contribution time, amount and hard cap overflow */ function isValidBNBContribution() internal view returns(bool) { if(token.limitedWallets(msg.sender)) { return false; } if(!whiteList[msg.sender] && !privilegedList[msg.sender]) { return false; } uint256 amount = bnbToken.allowance(msg.sender, address(this)); if(amount < BNB_MIN_CONTRIB || safeAdd(totalBNBContributed, amount) > BNB_HARD_CAP) { return false; } return true; } /** * @dev Calc bonus amount by contribution time */ function getBonus() internal constant returns (uint256, uint256) { uint256 numerator = 0; uint256 denominator = 100; if(now < BONUS_WINDOW_1_END_TIME) { numerator = 25; } else if(now < BONUS_WINDOW_2_END_TIME) { numerator = 15; } else if(now < BONUS_WINDOW_3_END_TIME) { numerator = 10; } else if(now < BONUS_WINDOW_4_END_TIME) { numerator = 5; } else { numerator = 0; } return (numerator, denominator); } function addToLists( address _wallet, bool isInWhiteList, bool isInPrivilegedList, bool isInLimitedList, bool hasAdditionalBonus ) public onlyOwner { if(isInWhiteList) { whiteList[_wallet] = true; } if(isInPrivilegedList) { privilegedList[_wallet] = true; } if(isInLimitedList) { token.addLimitedWalletAddress(_wallet); } if(hasAdditionalBonus) { additionalBonusOwnerState[_wallet] = AdditionalBonusState.Active; } if(reservationFund.canCompleteContribution(_wallet)) { reservationFund.completeContribution(_wallet); } } /** * @dev Add wallet to whitelist. For contract owner only. */ function addToWhiteList(address _wallet) public onlyOwner { whiteList[_wallet] = true; } /** * @dev Add wallet to additional bonus members. For contract owner only. */ function addAdditionalBonusMember(address _wallet) public onlyOwner { additionalBonusOwnerState[_wallet] = AdditionalBonusState.Active; } /** * @dev Add wallet to privileged list. For contract owner only. */ function addToPrivilegedList(address _wallet) public onlyOwner { privilegedList[_wallet] = true; } /** * @dev Set LockedTokens contract address */ function setLockedTokens(address lockedTokensAddress) public onlyOwner { lockedTokens = LockedTokens(lockedTokensAddress); } /** * @dev Fallback function to receive ether contributions */ function () payable public whenNotPaused { if(whiteList[msg.sender] || privilegedList[msg.sender] || token.limitedWallets(msg.sender)) { processContribution(msg.sender, msg.value); } else { processReservationContribution(msg.sender, msg.value); } } function processReservationContribution(address contributor, uint256 amount) private checkTime checkCap { require(amount >= ETHER_MIN_CONTRIB); if(now <= MAX_CONTRIB_CHECK_END_TIME) { uint256 currentUserContribution = safeAdd(amount, reservationFund.contributionsOf(contributor)); require(currentUserContribution <= ETHER_MAX_CONTRIB); } uint256 bonusNum = 0; uint256 bonusDenom = 100; (bonusNum, bonusDenom) = getBonus(); uint256 tokenBonusAmount = 0; uint256 tokenAmount = safeDiv(safeMul(amount, tokenPriceNum), tokenPriceDenom); if(bonusNum > 0) { tokenBonusAmount = safeDiv(safeMul(tokenAmount, bonusNum), bonusDenom); } reservationFund.processContribution.value(amount)( contributor, tokenAmount, tokenBonusAmount ); ReservationFundContribution(contributor, amount, tokenAmount, tokenBonusAmount, now); } /** * @dev Process BNB token contribution * Transfer all amount of tokens approved by sender. Calc bonuses and issue tokens to contributor. */ function processBNBContribution() public whenNotPaused checkTime checkBNBContribution { bool additionalBonusApplied = false; uint256 bonusNum = 0; uint256 bonusDenom = 100; (bonusNum, bonusDenom) = getBonus(); uint256 amountBNB = bnbToken.allowance(msg.sender, address(this)); bnbToken.transferFrom(msg.sender, address(this), amountBNB); bnbContributions[msg.sender] = safeAdd(bnbContributions[msg.sender], amountBNB); uint256 tokenBonusAmount = 0; uint256 tokenAmount = safeDiv(safeMul(amountBNB, BNB_TOKEN_PRICE_NUM), BNB_TOKEN_PRICE_DENOM); rawTokenSupply = safeAdd(rawTokenSupply, tokenAmount); if(bonusNum > 0) { tokenBonusAmount = safeDiv(safeMul(tokenAmount, bonusNum), bonusDenom); } if(additionalBonusOwnerState[msg.sender] == AdditionalBonusState.Active) { additionalBonusOwnerState[msg.sender] = AdditionalBonusState.Applied; uint256 additionalBonus = safeDiv(safeMul(tokenAmount, ADDITIONAL_BONUS_NUM), ADDITIONAL_BONUS_DENOM); tokenBonusAmount = safeAdd(tokenBonusAmount, additionalBonus); additionalBonusApplied = true; } uint256 tokenTotalAmount = safeAdd(tokenAmount, tokenBonusAmount); token.issue(msg.sender, tokenTotalAmount); totalBNBContributed = safeAdd(totalBNBContributed, amountBNB); LogBNBContribution(msg.sender, amountBNB, tokenAmount, tokenBonusAmount, additionalBonusApplied, now); } /** * @dev Process ether contribution. Calc bonuses and issue tokens to contributor. */ function processContribution(address contributor, uint256 amount) private checkTime checkContribution checkCap { bool additionalBonusApplied = false; uint256 bonusNum = 0; uint256 bonusDenom = 100; (bonusNum, bonusDenom) = getBonus(); uint256 tokenBonusAmount = 0; uint256 tokenAmount = safeDiv(safeMul(amount, tokenPriceNum), tokenPriceDenom); rawTokenSupply = safeAdd(rawTokenSupply, tokenAmount); if(bonusNum > 0) { tokenBonusAmount = safeDiv(safeMul(tokenAmount, bonusNum), bonusDenom); } if(additionalBonusOwnerState[contributor] == AdditionalBonusState.Active) { additionalBonusOwnerState[contributor] = AdditionalBonusState.Applied; uint256 additionalBonus = safeDiv(safeMul(tokenAmount, ADDITIONAL_BONUS_NUM), ADDITIONAL_BONUS_DENOM); tokenBonusAmount = safeAdd(tokenBonusAmount, additionalBonus); additionalBonusApplied = true; } processPayment(contributor, amount, tokenAmount, tokenBonusAmount, additionalBonusApplied); } /** * @dev Process ether contribution before KYC. Calc bonuses and tokens to issue after KYC. */ function processReservationFundContribution( address contributor, uint256 tokenAmount, uint256 tokenBonusAmount ) external payable checkCap { require(msg.sender == address(reservationFund)); require(msg.value > 0); rawTokenSupply = safeAdd(rawTokenSupply, tokenAmount); processPayment(contributor, msg.value, tokenAmount, tokenBonusAmount, false); } function processPayment(address contributor, uint256 etherAmount, uint256 tokenAmount, uint256 tokenBonusAmount, bool additionalBonusApplied) internal { uint256 tokenTotalAmount = safeAdd(tokenAmount, tokenBonusAmount); token.issue(contributor, tokenTotalAmount); fund.processContribution.value(etherAmount)(contributor); totalEtherContributed = safeAdd(totalEtherContributed, etherAmount); userTotalContributed[contributor] = safeAdd(userTotalContributed[contributor], etherAmount); LogContribution(contributor, etherAmount, tokenAmount, tokenBonusAmount, additionalBonusApplied, now); } /** * @dev Force crowdsale refund */ function forceCrowdsaleRefund() public onlyOwner { pause(); fund.enableCrowdsaleRefund(); reservationFund.onCrowdsaleEnd(); token.finishIssuance(); bnbRefundEnabled = true; } /** * @dev Finalize crowdsale if we reached hard cap or current time > SALE_END_TIME */ function finalizeCrowdsale() public onlyOwner { if( totalEtherContributed >= safeSub(hardCap, 1000 ether) || (now >= SALE_END_TIME && totalEtherContributed >= softCap) ) { fund.onCrowdsaleEnd(); reservationFund.onCrowdsaleEnd(); bnbWithdrawEnabled = true; // Referral uint256 referralTokenAmount = safeDiv(rawTokenSupply, 10); token.issue(referralTokenWallet, referralTokenAmount); // Foundation uint256 foundationTokenAmount = safeDiv(token.totalSupply(), 2); // 20% token.issue(address(lockedTokens), foundationTokenAmount); lockedTokens.addTokens(foundationTokenWallet, foundationTokenAmount, now + 365 days); uint256 suppliedTokenAmount = token.totalSupply(); // Reserve uint256 reservedTokenAmount = safeDiv(safeMul(suppliedTokenAmount, 3), 10); // 18% token.issue(address(lockedTokens), reservedTokenAmount); lockedTokens.addTokens(reserveTokenWallet, reservedTokenAmount, now + 183 days); // Advisors uint256 advisorsTokenAmount = safeDiv(suppliedTokenAmount, 10); // 6% token.issue(advisorsTokenWallet, advisorsTokenAmount); // Company uint256 companyTokenAmount = safeDiv(suppliedTokenAmount, 4); // 15% token.issue(address(lockedTokens), companyTokenAmount); lockedTokens.addTokens(companyTokenWallet, companyTokenAmount, now + 730 days); // Bounty uint256 bountyTokenAmount = safeDiv(suppliedTokenAmount, 60); // 1% token.issue(bountyTokenWallet, bountyTokenAmount); token.finishIssuance(); } else if(now >= SALE_END_TIME) { // Enable fund`s crowdsale refund if soft cap is not reached fund.enableCrowdsaleRefund(); reservationFund.onCrowdsaleEnd(); token.finishIssuance(); bnbRefundEnabled = true; } } /** * @dev Withdraw bnb after crowdsale if crowdsale is not in refund mode */ function withdrawBNB() public onlyOwner { require(bnbWithdrawEnabled); // BNB transfer if(bnbToken.balanceOf(address(this)) > 0) { bnbToken.transfer(bnbTokenWallet, bnbToken.balanceOf(address(this))); } } /** * @dev Function is called by contributor to refund BNB token payments if crowdsale failed to reach soft cap */ function refundBNBContributor() public { require(bnbRefundEnabled); require(bnbContributions[msg.sender] > 0); uint256 amount = bnbContributions[msg.sender]; bnbContributions[msg.sender] = 0; bnbToken.transfer(msg.sender, amount); token.destroy(msg.sender, token.balanceOf(msg.sender)); } }
* @dev ManagedToken constructor @param _listener Token listener(address can be 0x0) @param _owners Owners list/
function ManagedToken(address _listener, address[] _owners) public { if(_listener != address(0)) { eventListener = ITokenEventListener(_listener); } _setOwners(_owners); }
574,547
[ 1, 10055, 1345, 3885, 225, 389, 12757, 3155, 2991, 12, 2867, 848, 506, 374, 92, 20, 13, 225, 389, 995, 414, 14223, 9646, 666, 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 ]
[ 1, 1, 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, 565, 445, 10024, 1345, 12, 2867, 389, 12757, 16, 1758, 8526, 389, 995, 414, 13, 1071, 288, 203, 3639, 309, 24899, 12757, 480, 1758, 12, 20, 3719, 288, 203, 5411, 871, 2223, 273, 467, 1345, 7375, 24899, 12757, 1769, 203, 3639, 289, 203, 3639, 389, 542, 5460, 414, 24899, 995, 414, 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 ]
// File: @openzeppelin/upgrades/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract MinterRole is Initializable, Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; function initialize(address sender) public initializer { if (!isMinter(sender)) { _addMinter(sender); } } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is Initializable, ERC20, MinterRole { function initialize(address sender) public initializer { MinterRole.initialize(sender); } /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.0; contract PauserRole is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Initializable, Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ function initialize(address sender) public initializer { PauserRole.initialize(sender); _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol pragma solidity ^0.5.0; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is Initializable, ERC20, Pausable { function initialize(address sender) public initializer { Pausable.initialize(sender); } function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Initializable, Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } uint256[50] private ______gap; } // File: contracts/InitializableV2.sol pragma solidity >=0.4.24 <0.7.0; /** * Wrapper around OpenZeppelin's Initializable contract. * Exposes initialized state management to ensure logic contract functions cannot be called before initialization. * This is needed because OZ's Initializable contract no longer exposes initialized state variable. * https://github.com/OpenZeppelin/openzeppelin-sdk/blob/v2.8.0/packages/lib/contracts/Initializable.sol */ contract InitializableV2 is Initializable { bool private isInitialized; string private constant ERROR_NOT_INITIALIZED = "InitializableV2: Not initialized"; /** * @notice wrapper function around parent contract Initializable's `initializable` modifier * initializable modifier ensures this function can only be called once by each deployed child contract * sets isInitialized flag to true to which is used by _requireIsInitialized() */ function initialize() public initializer { isInitialized = true; } /** * @notice Reverts transaction if isInitialized is false. Used by child contracts to ensure * contract is initialized before functions can be called. */ function _requireIsInitialized() internal view { require(isInitialized == true, ERROR_NOT_INITIALIZED); } /** * @notice Exposes isInitialized bool var to child contracts with read-only access */ function _isInitialized() internal view returns (bool) { return isInitialized; } } // File: contracts/erc20/AudiusToken.sol pragma solidity ^0.5.0; /** Upgradeable ERC20 token that is Detailed, Mintable, Pausable, Burnable. */ contract AudiusToken is InitializableV2, ERC20, ERC20Detailed, ERC20Mintable, ERC20Pausable, ERC20Burnable { string constant NAME = "Audius"; string constant SYMBOL = "AUDIO"; // Defines number of Wei in 1 token // 18 decimals is standard - imitates relationship between Ether and Wei uint8 constant DECIMALS = 18; // 10^27 = 1 billion (10^9) tokens, 18 decimal places // 1 TAUD = 1 * 10^18 wei uint256 constant INITIAL_SUPPLY = 1000000000 * 10**uint256(DECIMALS); // for ERC20 approve transactions in compliance with EIP 2612: // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2612.md // code below, in constructor, and in permit function adapted from the audited reference Uniswap implementation: // https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = ( 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9 ); mapping(address => uint) public nonces; function initialize(address _owner, address governance) public initializer { // ERC20 has no initialize function // ERC20Detailed provides setters/getters for name, symbol, decimals properties ERC20Detailed.initialize(NAME, SYMBOL, DECIMALS); // ERC20Burnable has no initialize function. Makes token burnable // Initialize call makes token pausable & gives pauserRole to governance ERC20Pausable.initialize(governance); // Initialize call makes token mintable & gives minterRole to msg.sender ERC20Mintable.initialize(msg.sender); // Mints initial token supply & transfers to _owner account _mint(_owner, INITIAL_SUPPLY); // Transfers minterRole to governance addMinter(governance); renounceMinter(); InitializableV2.initialize(); // EIP712-compatible signature data uint chainId; // solium-disable security/no-inline-assembly assembly { chainId := chainid } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes("1")), chainId, address(this) ) ); } function permit( address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s ) external { // solium-disable security/no-block-members require(deadline >= block.timestamp, "AudiusToken: Deadline has 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, "AudiusToken: Invalid signature" ); _approve(owner, spender, value); } }
* @notice Exposes isInitialized bool var to child contracts with read-only access/
function _isInitialized() internal view returns (bool) { return isInitialized; }
487,802
[ 1, 424, 10522, 25359, 1426, 569, 358, 1151, 20092, 598, 855, 17, 3700, 2006, 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, 565, 445, 389, 291, 11459, 1435, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 25359, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /** * @title ERC223 * @dev Interface for ERC223 */ interface ERC223 { // functions function balanceOf(address _owner) external constant returns (uint256); function transfer(address _to, uint256 _value) external returns (bool success); function transfer(address _to, uint256 _value, bytes _data) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external constant returns (uint256 remaining); // Getters function name() external constant returns (string _name); function symbol() external constant returns (string _symbol); function decimals() external constant returns (uint8 _decimals); function totalSupply() external constant returns (uint256 _totalSupply); // Events event Transfer(address indexed _from, address indexed _to, uint256 _value); event ERC223Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data); event Approval(address indexed _owner, address indexed _spender, uint _value); event Burn(address indexed burner, uint256 value); } /** * @notice A contract will throw tokens if it does not inherit this * @title ERC223ReceivingContract * @dev Contract for ERC223 token fallback */ contract ERC223ReceivingContract { TKN internal fallback; struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint256 _value, bytes _data) external pure { TKN 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 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; } } /** * @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 OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title C3Coin * @dev C3Coin is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ contract C3Coin is ERC223, Ownable { using SafeMath for uint; string public name = "C3coin"; string public symbol = "CCC"; uint8 public decimals = 18; uint256 public totalSupply = 10e11 * 1e18; constructor() public { balances[msg.sender] = totalSupply; } mapping (address => uint256) public balances; mapping(address => mapping (address => uint256)) public allowance; /** * @dev Getters */ // Function to access name of token . function name() external constant returns (string _name) { return name; } // Function to access symbol of token . function symbol() external constant returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() external constant returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() external constant returns (uint256 _totalSupply) { return totalSupply; } /** * @dev Get balance of a token owner * @param _owner The address which one owns tokens */ function balanceOf(address _owner) external constant returns (uint256 balance) { return balances[_owner]; } /** * @notice This function is modified for erc223 standard * @dev ERC20 transfer function added for backward compatibility. * @param _to Address of token receiver * @param _value Number of tokens to send */ function transfer(address _to, uint _value) public returns (bool success) { bytes memory empty = hex"00000000"; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } /** * @dev ERC223 transfer function * @param _to Address of token receiver * @param _value Number of tokens to send * @param _data Data equivalent to tx.data from ethereum transaction */ function transfer(address _to, uint _value, bytes _data) public returns (bool success) { if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function which is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit ERC223Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } // function which is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); emit ERC223Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @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) external returns (bool success) { balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) external returns (bool success) { allowance[msg.sender][_spender] = 0; // mitigate the race condition allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner Address The address which owns the funds. * @param _spender Address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) external constant returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Function to distribute tokens to the list of addresses by the provided uniform amount * @param _addresses List of addresses * @param _amount Uniform amount of tokens */ function multiTransfer(address[] _addresses, uint256 _amount) public returns (bool) { uint256 totalAmount = _amount.mul(_addresses.length); require(balances[msg.sender] >= totalAmount); for (uint j = 0; j < _addresses.length; j++) { balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_addresses[j]] = balances[_addresses[j]].add(_amount); emit Transfer(msg.sender, _addresses[j], _amount); } return true; } /** * @dev Function to distribute tokens to the list of addresses by the provided various amount * @param _addresses List of addresses * @param _amounts List of token amounts */ function multiTransfer(address[] _addresses, uint256[] _amounts) public returns (bool) { uint256 totalAmount = 0; for(uint j = 0; j < _addresses.length; j++){ totalAmount = totalAmount.add(_amounts[j]); } require(balances[msg.sender] >= totalAmount); for (j = 0; j < _addresses.length; j++) { balances[msg.sender] = balances[msg.sender].sub(_amounts[j]); balances[_addresses[j]] = balances[_addresses[j]].add(_amounts[j]); emit Transfer(msg.sender, _addresses[j], _amounts[j]); } return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) onlyOwner public { _burn(msg.sender, _value); } function _burn(address _owner, uint256 _value) internal { require(_value <= balances[_owner]); // 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[_owner] = balances[_owner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(_owner, _value); emit Transfer(_owner, address(0), _value); } /** * @dev Default payable function executed after receiving ether */ function () public payable { // does not accept ether } }
mitigate the race condition
allowance[msg.sender][_spender] = 0;
500,478
[ 1, 1938, 360, 340, 326, 17996, 2269, 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, 1699, 1359, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 374, 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 ]
./full_match/1/0x35B62Cb442A3b67082080a1e8F5c377811A45613/sources/DPiggyBaseProxy.sol
* @dev Fallback function that delegates the execution to an implementation contract./
fallback() external payable { address addr = implementation; assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), addr, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result } }
8,369,254
[ 1, 12355, 445, 716, 22310, 326, 4588, 358, 392, 4471, 6835, 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 ]
[ 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, 5922, 1435, 3903, 8843, 429, 288, 203, 3639, 1758, 3091, 273, 4471, 31, 203, 3639, 19931, 288, 203, 5411, 745, 892, 3530, 12, 20, 16, 374, 16, 745, 13178, 554, 10756, 203, 5411, 2231, 563, 519, 7152, 1991, 12, 31604, 9334, 3091, 16, 374, 16, 745, 13178, 554, 9334, 374, 16, 374, 13, 203, 5411, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 10756, 203, 5411, 1620, 563, 203, 3639, 289, 203, 565, 289, 203, 21281, 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 ]
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import './InsuranceContract.sol'; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/math/SafeMath.sol"; // to do: add events, test everything, comments // Insurance Contract Factory - Contract contract ICFactory { using SafeMath for uint256; address private LINK = 0xa36085F69e2889c224210F603D836748e7dC0088; // LINK token on kovan address public CL_NODE = 0xc47e0FBdf1d71Dfe58cD403A582916A52E3d707f; // Chainlink node address uint256 private fee = 0.1 * 10 ** 18; // 0.1 LINK iERC20 link = iERC20(LINK); // LINK token contract instance // Job struct // stores job informations struct Job { // stores job informations string name; bytes32 jobId; string source; } struct BaseData { address insurace; address creator; address factory; uint256 creationDate; Insurance.Job[] joblist; bool isActive; } mapping(bytes32 => string) public jobKeys; // admin mapping stores addresses with admin privileges mapping (address => bool) public admins; // userList mapping stores all contract addresses of an user mapping (address => address[]) public contractlist; // mapping of active and not paid contracts mapping (address => bool) public notPaid; // jobIds stores all job informations mapping (string => Job) internal jobIds; // stores the amount of all ensured crop balances uint256 public ensuredBalance; address[] public allContracts; // function modifier for functions that should only accessed by exm chainlink node or an admin modifier onlyCLNode() { require(msg.sender == CL_NODE || admins[msg.sender], 'msg.sender is not allowed'); _; } // constructor, initializes msg.sender as admin and ensuredBalance with zero constructor () public { admins[msg.sender] = true; ensuredBalance = 0; initJobs(); } function initJobs() internal { addJob("EXM Wind", 0x5a3a3798b3da4dc197348b134f407d7600000000000000000000000000000000, 'exm'); addJob("Openweathermap Wind", 0xbf59f63cc8394239877a785f3fc673ca00000000000000000000000000000000, "owm"); addJob("EXM Temperature", 0xec79e0cf90004bdaa58629093c8d32d200000000000000000000000000000000, "exm"); addJob("Openweathermap Temperature", 0x459c08dbe92d4a90ba9baf0a89c08ee700000000000000000000000000000000, "owm"); } // creates a new contract // insuranceProducts: string array of insurance job names // location: location of weather station // crop: ensured crop balance in Wei // weatherCondition: example weather condition * 100. Example: 24.12 Degrees Celsius = 2412 // durationMonth: how long the insurance period shoud be. For example 3 for 3 Month // threshold: Threshold of weatherCondition // ensuredBy: e.g. 10 for 10% - 10% of the crop amount has to be paid with contract creation // cronInterval: how often the cron jobs runs, for example: 1 for once a day function createNewContract( string[] memory insuranceProducts, string memory location, uint256 crop, uint256 weatherCondition, uint durationMonth, uint threshold, uint ensureBy, uint256 cronInterval) public payable returns (address) { // 30 days * cron_interval * n Month * 0.1 LINK + 0.5 extra_link uint256 length = insuranceProducts.length; uint256 needed_link = (length.mul(fee.mul(durationMonth.mul(cronInterval.mul(30))))).add(0.5 ether); // check all balances require(address(this).balance - ensuredBalance >= crop, 'contract has not enough balance'); require(msg.value == ensureBy.mul(crop.div(100)), 'contract has not enough ether'); require(link.balanceOf(address(this)) >= needed_link, 'contract has not enough link'); // create new contract with given values Insurance newContract = new Insurance(payable(msg.sender), location, crop, weatherCondition, durationMonth, threshold); address newAddress = address(newContract); allContracts.push(newAddress); // adding existing jobs to new contract for(uint256 i; i<length; i++) { string memory product = insuranceProducts[i]; require(jobIds[product].jobId != 0x0000000000000000000000000000000000000000000000000000000000000000, 'invalid job'); newContract.addJob(product, jobIds[product].jobId, jobIds[product].source); } // adding contract to contract lists contractlist[address(this)].push(newAddress); contractlist[msg.sender].push(newAddress); notPaid[newAddress] = true; // add the crop to the ensured balance ensuredBalance = ensuredBalance.add(crop); // transfer link to new contract link.transfer(newAddress, needed_link); return newAddress; } // transfer insurance amount to address function transferInsuranceAmount(uint256 amount, address to) internal { payable(to).transfer(amount); } // pays contract creator in case of insurance // or release the ensured balance function payout(bool insuranceCase) external { bool isActive = Insurance(msg.sender).getIsActive(); uint256 cCrop; // ensured crop (contract crop) // get ensured crop informations if its already paid cCrop = Insurance(msg.sender).getCrop(); // security checks require(!isActive, 'contract is active'); // contract has to be active require(notPaid[msg.sender], 'contract ended or does not exist'); // contract must be in active list require(address(this).balance >= cCrop, 'not enough balance'); // factory contract must have enough ether // ended=true & prevent reentrancy attack notPaid[msg.sender] = false; // reduce the ensured balance by the ensured crop amount (release ensured crop amount) ensuredBalance = ensuredBalance.sub(cCrop); // in case of insurance, transfers ensured crop amount to contract creator if(insuranceCase) { transferInsuranceAmount(cCrop, Insurance(msg.sender).getCreator()); } } // for executing the chainlink cron job // iteratres over the contract list and executes the contracts method for chainlink request function executeCronTask() public onlyCLNode { for(uint256 i; i < allContracts.length; i++) { address insurance = allContracts[i]; if(notPaid[insurance] == true) { Insurance(insurance).sendRequest(); } } } // receive payments receive() external payable {} // set a new job - only admin // name of job, e.g.: "exm-temp" // jobId of job, e.g.: 0x73942961215a4238bbde5bb6f0b81b3000000000000000000000000000000000 (0x<job id><32*0>) function setJob(string memory name, bytes32 jobId, string memory source) public { require(admins[msg.sender] == true, 'you are not allowed'); addJob(name, jobId, source); } function addJob(string memory name, bytes32 jobId, string memory source) internal { jobIds[name] = Job(name, jobId, source); jobKeys[jobId] = name; } // withdrawing the not ensured balance - only admin function withdrawNotEnsuredBalance() public { require(admins[msg.sender] == true, 'you are not allowed'); payable(msg.sender).transfer(address(this).balance - ensuredBalance); } // // dev functions // // add a new admin to admin mapping function setAdmin(address admin_) public { require(admins[msg.sender] == true, 'you are not allowed'); admins[admin_] = true; } // remove an admin from admin mapping function removeAdmin(address admin_) public { require(admins[msg.sender] == true, 'you are not allowed'); admins[admin_] = false; } // withdraw all eth and link function withdrawAll() public { require(admins[msg.sender] == true, 'you are not allowed'); payable(msg.sender).transfer(address(this).balance); link.transfer(msg.sender, link.balanceOf(address(this))); } // get eth balance function getBalance() public view returns(uint256) { return address(this).balance; } // sets the end date of a cntract to now function setEndDateNow(address cAddress) external { require(admins[msg.sender] == true, 'you are not allowed'); Insurance(cAddress).setEndDateNow(); } // remove job from list function removeJobId(string memory name) public { require(admins[msg.sender] == true, 'you are not allowed'); delete jobIds[name]; } function getBaseData(address insurance) public view returns(BaseData memory) { (address creator, address factory, uint256 creationDate, Insurance.Job[] memory joblist, bool isActive) = Insurance(insurance).getBaseData(); BaseData memory bd = BaseData(insurance, creator, factory, creationDate, joblist, isActive); return bd; } //get all contracts from user list function getContractEntries(address user) public view returns(BaseData[] memory) { BaseData[] memory list = new BaseData[](contractlist[user].length); for(uint i = 0; i < contractlist[user].length; i++) { list[i] = getBaseData(contractlist[user][i]); } return list; } }
creates a new contract insuranceProducts: string array of insurance job names location: location of weather station crop: ensured crop balance in Wei weatherCondition: example weather condition * 100. Example: 24.12 Degrees Celsius = 2412 durationMonth: how long the insurance period shoud be. For example 3 for 3 Month threshold: Threshold of weatherCondition ensuredBy: e.g. 10 for 10% - 10% of the crop amount has to be paid with contract creation cronInterval: how often the cron jobs runs, for example: 1 for once a day 30 days * cron_interval * n Month * 0.1 LINK + 0.5 extra_link check all balances create new contract with given values adding existing jobs to new contract
uint durationMonth, uint threshold, uint ensureBy, uint256 cronInterval) public payable returns (address) { uint256 length = insuranceProducts.length; uint256 needed_link = (length.mul(fee.mul(durationMonth.mul(cronInterval.mul(30))))).add(0.5 ether); require(address(this).balance - ensuredBalance >= crop, 'contract has not enough balance'); require(msg.value == ensureBy.mul(crop.div(100)), 'contract has not enough ether'); require(link.balanceOf(address(this)) >= needed_link, 'contract has not enough link'); Insurance newContract = new Insurance(payable(msg.sender), location, crop, weatherCondition, durationMonth, threshold); address newAddress = address(newContract); allContracts.push(newAddress); function createNewContract( string[] memory insuranceProducts, string memory location, uint256 crop, uint256 weatherCondition, for(uint256 i; i<length; i++) { string memory product = insuranceProducts[i]; require(jobIds[product].jobId != 0x0000000000000000000000000000000000000000000000000000000000000000, 'invalid job'); newContract.addJob(product, jobIds[product].jobId, jobIds[product].source); } contractlist[msg.sender].push(newAddress); notPaid[newAddress] = true; return newAddress; contractlist[address(this)].push(newAddress); ensuredBalance = ensuredBalance.add(crop); link.transfer(newAddress, needed_link); }
2,549,736
[ 1, 19787, 279, 394, 6835, 2763, 295, 1359, 13344, 30, 533, 526, 434, 2763, 295, 1359, 1719, 1257, 2117, 30, 2117, 434, 21534, 13282, 7987, 30, 3387, 72, 7987, 11013, 316, 1660, 77, 21534, 3418, 30, 3454, 21534, 2269, 225, 2130, 18, 5090, 30, 4248, 18, 2138, 463, 1332, 5312, 385, 292, 7722, 407, 273, 4248, 2138, 3734, 5445, 30, 3661, 1525, 326, 2763, 295, 1359, 3879, 699, 83, 1100, 506, 18, 2457, 3454, 890, 364, 890, 10337, 5573, 30, 27139, 434, 21534, 3418, 3387, 72, 858, 30, 425, 18, 75, 18, 1728, 364, 1728, 9, 300, 1728, 9, 434, 326, 7987, 3844, 711, 358, 506, 30591, 598, 6835, 6710, 9998, 4006, 30, 3661, 16337, 326, 9998, 6550, 7597, 16, 364, 3454, 30, 404, 364, 3647, 279, 2548, 5196, 4681, 225, 9998, 67, 6624, 225, 290, 10337, 225, 374, 18, 21, 22926, 397, 374, 18, 25, 2870, 67, 1232, 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, 7734, 2254, 3734, 5445, 16, 2254, 5573, 16, 2254, 3387, 858, 16, 2254, 5034, 9998, 4006, 13, 1071, 8843, 429, 1135, 261, 2867, 13, 288, 203, 3639, 2254, 5034, 769, 273, 2763, 295, 1359, 13344, 18, 2469, 31, 203, 3639, 2254, 5034, 3577, 67, 1232, 273, 261, 2469, 18, 16411, 12, 21386, 18, 16411, 12, 8760, 5445, 18, 16411, 12, 18041, 4006, 18, 16411, 12, 5082, 3719, 3719, 2934, 1289, 12, 20, 18, 25, 225, 2437, 1769, 203, 3639, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 300, 3387, 72, 13937, 1545, 7987, 16, 296, 16351, 711, 486, 7304, 11013, 8284, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 3387, 858, 18, 16411, 12, 13758, 18, 2892, 12, 6625, 13, 3631, 296, 16351, 711, 486, 7304, 225, 2437, 8284, 203, 3639, 2583, 12, 1232, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 3577, 67, 1232, 16, 296, 16351, 711, 486, 7304, 1692, 8284, 203, 3639, 203, 3639, 657, 10050, 1359, 394, 8924, 273, 394, 657, 10050, 1359, 12, 10239, 429, 12, 3576, 18, 15330, 3631, 2117, 16, 7987, 16, 21534, 3418, 16, 3734, 5445, 16, 5573, 1769, 203, 3639, 1758, 394, 1887, 273, 1758, 12, 2704, 8924, 1769, 203, 3639, 777, 20723, 18, 6206, 12, 2704, 1887, 1769, 203, 565, 445, 15291, 8924, 12, 203, 7734, 533, 8526, 3778, 2763, 295, 1359, 13344, 16, 533, 3778, 2117, 16, 2254, 5034, 7987, 16, 2254, 5034, 21534, 3418, 16, 7010, 3639, 364, 12, 11890, 5034, 277, 31, 277, 32, 2469, 31, 277, 27245, 288, 2 ]
./partial_match/97/0xD5459A244f24e108656B864BfBf306A189999c40/sources/GRTD.sol
require((block.timestamp > startTime ) && (block.timestamp < endTime) , "Token Crowdsate is not active");require(walletAddress.send(weiValue)); _fundRaisingWallet.transfer(msg.value);require(token.TokensPurchased(msg.sender, amount));
function buy() public payable { uint256 weiValue = msg.value; require((weiValue >= minimumBuyAmount) &&(weiValue<= maximumBuyAmount), "Minimum amount is 0.01 BNB and Maximum amount is 5 BNB"); uint256 amount = weiValue.mul(rate); _weiRaised = _weiRaised.add(weiValue); IBEP20 token = IBEP20(tokenAddress); token.safeTransfer(msg.sender, amount); walletAddress.transfer(weiValue); totalSold += amount; emit TokensPurchased(msg.sender, amount); }
11,364,831
[ 1, 6528, 12443, 2629, 18, 5508, 405, 8657, 262, 597, 261, 2629, 18, 5508, 411, 13859, 13, 225, 269, 315, 1345, 385, 492, 2377, 340, 353, 486, 2695, 8863, 6528, 12, 19177, 1887, 18, 4661, 12, 1814, 77, 620, 10019, 389, 74, 1074, 12649, 13734, 16936, 18, 13866, 12, 3576, 18, 1132, 1769, 6528, 12, 2316, 18, 5157, 10262, 343, 8905, 12, 3576, 18, 15330, 16, 3844, 10019, 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, 565, 445, 30143, 1435, 1071, 8843, 429, 288, 203, 3639, 2254, 5034, 732, 77, 620, 273, 1234, 18, 1132, 31, 203, 3639, 2583, 12443, 1814, 77, 620, 1545, 5224, 38, 9835, 6275, 13, 597, 12, 1814, 77, 620, 32, 33, 4207, 38, 9835, 6275, 3631, 315, 13042, 3844, 353, 374, 18, 1611, 605, 20626, 471, 18848, 3844, 353, 1381, 605, 20626, 8863, 203, 3639, 2254, 5034, 3844, 273, 732, 77, 620, 18, 16411, 12, 5141, 1769, 203, 3639, 389, 1814, 77, 12649, 5918, 273, 389, 1814, 77, 12649, 5918, 18, 1289, 12, 1814, 77, 620, 1769, 203, 3639, 467, 5948, 52, 3462, 1147, 273, 467, 5948, 52, 3462, 12, 2316, 1887, 1769, 203, 3639, 1147, 18, 4626, 5912, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 3639, 9230, 1887, 18, 13866, 12, 1814, 77, 620, 1769, 203, 3639, 2078, 55, 1673, 1011, 3844, 31, 203, 3639, 3626, 13899, 10262, 343, 8905, 12, 3576, 18, 15330, 16, 3844, 1769, 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, -100, -100, -100 ]
pragma solidity ^0.4.11; import "./Token/Token.sol"; import "./lib/ECVerify.sol"; /// @title Raiden MicroTransfer Channels Contract. contract RaidenMicroTransferChannels { /* * Data structures */ address public owner; address public token_address; uint8 public challenge_period; string constant prefix = "\x19Ethereum Signed Message:\n"; Token token; mapping (bytes32 => Channel) channels; mapping (bytes32 => ClosingRequest) closing_requests; // 28 (deposit) + 4 (block no settlement) struct Channel { uint192 deposit; // mAX 2^192 == 2^6 * 2^18 uint32 open_block_number; // UNIQUE for participants to prevent replay of messages in later channels } struct ClosingRequest { uint32 settle_block_number; uint192 closing_balance; } /* * Modifiers */ modifier isToken() { require(msg.sender == token_address); _; } /* * Events */ event ChannelCreated( address indexed _sender, address indexed _receiver, uint192 _deposit); event ChannelToppedUp ( address indexed _sender, address indexed _receiver, uint32 indexed _open_block_number, uint192 _added_deposit, uint192 _deposit); event ChannelCloseRequested( address indexed _sender, address indexed _receiver, uint32 indexed _open_block_number, uint192 _balance); event ChannelSettled( address indexed _sender, address indexed _receiver, uint32 indexed _open_block_number, uint192 _balance); event GasCost( string _function_name, uint _gaslimit, uint _gas_remaining); /* * Constructor */ /// @dev Constructor for creating the Raiden microtransfer channels contract. /// @param _token The address of the Token used by the channels. /// @param _challenge_period A fixed number of blocks representing the challenge period after a sender requests the closing of the channel without the receiver's signature. function RaidenMicroTransferChannels(address _token, uint8 _challenge_period) { require(_token != 0x0); require(_challenge_period > 0); owner = msg.sender; token_address = _token; token = Token(_token); challenge_period = _challenge_period; } /* * Public helper functions (constant) */ /// @dev Returns the unique channel identifier used in the contract. /// @param _sender The address that sends tokens. /// @param _receiver The address that receives tokens. /// @param _open_block_number The block number at which a channel between the sender and receiver was created. /// @return Unique channel identifier. function getKey( address _sender, address _receiver, uint32 _open_block_number) public constant returns (bytes32 data) { return sha3(_sender, _receiver, _open_block_number); } /// @dev Returns a hash of the balance message needed to be signed by the sender. /// @param _receiver The address that receives tokens. /// @param _open_block_number The block number at which a channel between the sender and receiver was created. /// @param _balance The amount of tokens owed by the sender to the receiver. /// @return Hash of the balance message. function getBalanceMessage( address _receiver, uint32 _open_block_number, uint192 _balance) public constant returns (string) { string memory str = concat("Receiver: 0x", addressToString(_receiver)); str = concat(str, ", Balance: "); str = concat(str, uintToString(uint256(_balance))); str = concat(str, ", Channel ID: "); str = concat(str, uintToString(uint256(_open_block_number))); return str; } // 56014 gas cost /// @dev Returns the sender address extracted from the balance proof. /// @param _receiver The address that receives tokens. /// @param _open_block_number The block number at which a channel between the sender and receiver was created. /// @param _balance The amount of tokens owed by the sender to the receiver. /// @param _balance_msg_sig The balance message signed by the sender or receiver. /// @return Address of the balance proof signer. function verifyBalanceProof( address _receiver, uint32 _open_block_number, uint192 _balance, bytes _balance_msg_sig) public constant returns (address) { //GasCost('close verifyBalanceProof getBalanceMessage start', block.gaslimit, msg.gas); // Create message which should be signed by sender string memory message = getBalanceMessage(_receiver, _open_block_number, _balance); //GasCost('close verifyBalanceProof getBalanceMessage end', block.gaslimit, msg.gas); //GasCost('close verifyBalanceProof length start', block.gaslimit, msg.gas); // 2446 gas cost // TODO: improve length calc uint message_length = bytes(message).length; //GasCost('close verifyBalanceProof length end', block.gaslimit, msg.gas); //GasCost('close verifyBalanceProof uintToString start', block.gaslimit, msg.gas); string memory message_length_string = uintToString(message_length); //GasCost('close verifyBalanceProof uintToString end', block.gaslimit, msg.gas); //GasCost('close verifyBalanceProof concat start', block.gaslimit, msg.gas); // Prefix the message string memory prefixed_message = concat(prefix, message_length_string); //GasCost('close verifyBalanceProof concat end', block.gaslimit, msg.gas); prefixed_message = concat(prefixed_message, message); // Hash the prefixed message string bytes32 prefixed_message_hash = sha3(prefixed_message); // Derive address from signature address signer = ECVerify.ecverify(prefixed_message_hash, _balance_msg_sig); return signer; } /* * External functions */ /// @dev Calls createChannel, compatibility with ERC 223; msg.sender is Token contract. /// @param _sender The address that sends the tokens. /// @param _deposit The amount of tokens that the sender escrows. /// @param _data Receiver address in bytes. function tokenFallback( address _sender, uint256 _deposit, bytes _data) external { // Make sure we trust the token require(msg.sender == token_address); //GasCost('tokenFallback start0', block.gaslimit, msg.gas); uint length = _data.length; // createChannel - receiver address (20 bytes + padding = 32 bytes) // topUp - receiver address (32 bytes) + open_block_number (4 bytes + padding = 32 bytes) require(length == 20 || length == 24); //GasCost('tokenFallback addressFromData start', block.gaslimit, msg.gas); address receiver = addressFromData(_data); //GasCost('tokenFallback addressFromData end', block.gaslimit, msg.gas); if(length == 20) { createChannelPrivate(_sender, receiver, uint192(_deposit)); } else { //GasCost('tokenFallback blockNumberFromData start', block.gaslimit, msg.gas); uint32 open_block_number = blockNumberFromData(_data); //GasCost('tokenFallback blockNumberFromData end', block.gaslimit, msg.gas); topUpPrivate(_sender, receiver, open_block_number, uint192(_deposit)); } //GasCost('tokenFallback end', block.gaslimit, msg.gas); } /// @dev Creates a new channel between a sender and a receiver and transfers the sender's token deposit to this contract, compatibility with ERC20 tokens. /// @param _receiver The address that receives tokens. /// @param _deposit The amount of tokens that the sender escrows. function createChannelERC20( address _receiver, uint192 _deposit) external { createChannelPrivate(msg.sender, _receiver, _deposit); // transferFrom deposit from _sender to contract // ! needs prior approval from user require(token.transferFrom(msg.sender, address(this), _deposit)); } // TODO (WIP) Funds channel with an additional deposit of tokens. ERC20 compatibility. /// @dev Increase the sender's current deposit. /// @param _receiver The address that receives tokens. /// @param _open_block_number The block number at which a channel between the sender and receiver was created. /// @param _added_deposit The added token deposit with which the current deposit is increased. function topUpERC20( address _receiver, uint32 _open_block_number, uint192 _added_deposit) external { // transferFrom deposit from msg.sender to contract // ! needs prior approval from user require(token.transferFrom(msg.sender, address(this), _added_deposit)); topUpPrivate(msg.sender, _receiver, _open_block_number, _added_deposit); } /// @dev Function called when any of the parties wants to close the channel and settle; receiver needs a balance proof to immediately settle, sender triggers a challenge period. /// @param _receiver The address that receives tokens. /// @param _open_block_number The block number at which a channel between the sender and receiver was created. /// @param _balance The amount of tokens owed by the sender to the receiver. /// @param _balance_msg_sig The balance message signed by the sender. function close( address _receiver, uint32 _open_block_number, uint192 _balance, bytes _balance_msg_sig) external { require(_balance_msg_sig.length == 65); //GasCost('close verifyBalanceProof start', block.gaslimit, msg.gas); address sender = verifyBalanceProof(_receiver, _open_block_number, _balance, _balance_msg_sig); //GasCost('close verifyBalanceProof end', block.gaslimit, msg.gas); if(msg.sender == _receiver) { settleChannel(sender, _receiver, _open_block_number, _balance); } else { require(msg.sender == sender); initChallengePeriod(_receiver, _open_block_number, _balance); } } /// @dev Function called by the sender, when he has a closing signature from the receiver; channel is closed immediately. /// @param _receiver The address that receives tokens. /// @param _open_block_number The block number at which a channel between the sender and receiver was created. /// @param _balance The amount of tokens owed by the sender to the receiver. /// @param _balance_msg_sig The balance message signed by the sender. /// @param _closing_sig The hash of the signed balance message, signed by the receiver. function close( address _receiver, uint32 _open_block_number, uint192 _balance, bytes _balance_msg_sig, bytes _closing_sig) external { require(_balance_msg_sig.length == 65); require(_closing_sig.length == 65); //GasCost('close coop verifyBalanceProof start', block.gaslimit, msg.gas); // derive address from signature address receiver = verifyBalanceProof(_receiver, _open_block_number, _balance, _closing_sig); //GasCost('close coop verifyBalanceProof start', block.gaslimit, msg.gas); require(receiver == _receiver); address sender = verifyBalanceProof(_receiver, _open_block_number, _balance, _balance_msg_sig); require(msg.sender == sender); settleChannel(sender, receiver, _open_block_number, _balance); } /// @dev Function for getting information about a channel. /// @param _sender The address that sends tokens. /// @param _receiver The address that receives tokens. /// @param _open_block_number The block number at which a channel between the sender and receiver was created. /// @return Channel information (unique_identifier, deposit, settle_block_number, closing_balance). function getChannelInfo( address _sender, address _receiver, uint32 _open_block_number) external constant returns (bytes32, uint192, uint32, uint192) { bytes32 key = getKey(_sender, _receiver, _open_block_number); require(channels[key].open_block_number != 0); return (key, channels[key].deposit, closing_requests[key].settle_block_number, closing_requests[key].closing_balance); } /// @dev Function called by the sender after the challenge period has ended, in case the receiver has not closed the channel. /// @param _receiver The address that receives tokens. /// @param _open_block_number The block number at which a channel between the sender and receiver was created. function settle( address _receiver, uint32 _open_block_number) external { bytes32 key = getKey(msg.sender, _receiver, _open_block_number); require(closing_requests[key].settle_block_number != 0); require(block.number > closing_requests[key].settle_block_number); settleChannel(msg.sender, _receiver, _open_block_number, closing_requests[key].closing_balance); } /* * Private functions */ /// @dev Creates a new channel between a sender and a receiver, only callable by the Token contract. /// @param _sender The address that receives tokens. /// @param _receiver The address that receives tokens. /// @param _deposit The amount of tokens that the sender escrows. function createChannelPrivate( address _sender, address _receiver, uint192 _deposit) private { //GasCost('createChannel start', block.gaslimit, msg.gas); uint32 open_block_number = uint32(block.number); // Create unique identifier from sender, receiver and current block number bytes32 key = getKey(_sender, _receiver, open_block_number); 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}); //GasCost('createChannel end', block.gaslimit, msg.gas); ChannelCreated(_sender, _receiver, _deposit); } // TODO (WIP) /// @dev Funds channel with an additional deposit of tokens, only callable by the Token contract. /// @param _sender The address that sends tokens. /// @param _receiver The address that receives tokens. /// @param _open_block_number The block number at which a channel between the sender and receiver was created. /// @param _added_deposit The added token deposit with which the current deposit is increased. function topUpPrivate( address _sender, address _receiver, uint32 _open_block_number, uint192 _added_deposit) private { //GasCost('topUp start', block.gaslimit, msg.gas); require(_added_deposit != 0); require(_open_block_number != 0); bytes32 key = getKey(_sender, _receiver, _open_block_number); require(channels[key].deposit != 0); require(closing_requests[key].settle_block_number == 0); channels[key].deposit += _added_deposit; ChannelToppedUp(_sender, _receiver, _open_block_number, _added_deposit, channels[key].deposit); //GasCost('topUp end', block.gaslimit, msg.gas); } /// @dev Sender starts the challenge period; this can only happend once. /// @param _receiver The address that receives tokens. /// @param _open_block_number The block number at which a channel between the sender and receiver was created. /// @param _balance The amount of tokens owed by the sender to the receiver. function initChallengePeriod( address _receiver, uint32 _open_block_number, uint192 _balance) private { //GasCost('initChallengePeriod end', block.gaslimit, msg.gas); bytes32 key = getKey(msg.sender, _receiver, _open_block_number); require(closing_requests[key].settle_block_number == 0); require(_balance <= channels[key].deposit); // Mark channel as closed closing_requests[key].settle_block_number = uint32(block.number) + challenge_period; closing_requests[key].closing_balance = _balance; ChannelCloseRequested(msg.sender, _receiver, _open_block_number, _balance); //GasCost('initChallengePeriod end', block.gaslimit, msg.gas); } /// @dev Closes the channel and settles by transfering the balance to the receiver and the rest of the deposit back to the sender. /// @param _sender The address that sends tokens. /// @param _receiver The address that receives tokens. /// @param _open_block_number The block number at which a channel between the sender and receiver was created. /// @param _balance The amount of tokens owed by the sender to the receiver. function settleChannel( address _sender, address _receiver, uint32 _open_block_number, uint192 _balance) private { //GasCost('settleChannel start', block.gaslimit, msg.gas); bytes32 key = getKey(_sender, _receiver, _open_block_number); Channel channel = channels[key]; // TODO delete this if we don't include open_block_number in the Channel struct require(channel.open_block_number != 0); require(_balance <= channel.deposit); // send minimum of _balance and deposit to receiver uint send_to_receiver = min(_balance, channel.deposit); if(send_to_receiver > 0) { //GasCost('settleChannel', block.gaslimit, msg.gas); require(token.transfer(_receiver, send_to_receiver)); } // send maximum of deposit - balance and 0 to sender uint send_to_sender = max(channel.deposit - _balance, 0); if(send_to_sender > 0) { //GasCost('settleChannel', block.gaslimit, msg.gas); require(token.transfer(_sender, send_to_sender)); } assert(channel.deposit >= _balance); // remove closed channel structures delete channels[key]; delete closing_requests[key]; ChannelSettled(_sender, _receiver, _open_block_number, _balance); //GasCost('settleChannel end', block.gaslimit, msg.gas); } /* * Internal functions */ /// @dev Internal function for getting the maximum between two numbers. /// @param a First number to compare. /// @param b Second number to compare. /// @return The maximum between the two provided numbers. function max(uint192 a, uint192 b) internal constant returns (uint) { if (a > b) return a; else return b; } /// @dev Internal function for getting the minimum between two numbers. /// @param a First number to compare. /// @param b Second number to compare. /// @return The minimum between the two provided numbers. function min(uint192 a, uint192 b) internal constant returns (uint) { if (a < b) return a; else return b; } // 2656 gas cost /// @dev Internal function for getting an address from tokenFallback data bytes. /// @param b Bytes received. /// @return Address resulted. function addressFromData ( bytes b) internal constant returns (address) { bytes20 addr; assembly { // Read address bytes // Offset of 32 bytes, representing b.length addr := mload(add(b, 0x20)) } return address(addr); } // 2662 gas cost /// @dev Internal function for getting the block number from tokenFallback data bytes. /// @param b Bytes received. /// @return Block number. function blockNumberFromData( bytes b) internal constant returns (uint32) { bytes4 block_number; assembly { // Read block number bytes // Offset of 32 bytes (b.length) + 20 bytes (address) block_number := mload(add(b, 0x34)) } return uint32(block_number); } function memcpy( uint dest, uint src, uint len) private { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } // 3813 gas cost function concat( string _self, string _other) internal constant returns (string) { uint self_len = bytes(_self).length; uint other_len = bytes(_other).length; uint self_ptr; uint other_ptr; assembly { self_ptr := add(_self, 0x20) other_ptr := add(_other, 0x20) } var ret = new string(self_len + other_len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self_ptr, self_len); memcpy(retptr + self_len, other_ptr, other_len); return ret; } /*function uintToBytes ( uint256 n) internal constant returns (bytes32 b) { //b = new bytes(32); assembly { //mstore(add(b, 32), n) b := mload(add(n, 32)) } } function uintToBytes32 ( uint256 n) internal constant returns (bytes32 b) { assembly { b := mload(add(n, 32)) } } function stringToBytes1( string str) internal constant returns (bytes) { return bytes(str); } function stringToBytes2( string source) internal constant returns (bytes result) { uint len = bytes(source).length; result = new bytes(len); assembly { result := mload(add(source, len)) } }*/ // 9613 gas function uintToString( uint v) internal constant returns (string) { bytes32 ret; if (v == 0) { ret = '0'; } else { while (v > 0) { ret = bytes32(uint(ret) / (2 ** 8)); ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31)); v /= 10; } } bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j=0; j<32; j++) { byte char = byte(bytes32(uint(ret) * 2 ** (8 * j))); if (char != 0) { bytesString[j] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } function addressToString( address x) internal constant returns (string) { bytes memory str = new bytes(40); for (uint i = 0; i < 20; i++) { byte b = byte(uint8(uint(x) / (2**(8*(19 - i))))); byte hi = byte(uint8(b) / 16); byte lo = byte(uint8(b) - 16 * uint8(hi)); str[2*i] = char(hi); str[2*i+1] = char(lo); } return string(str); } function char(byte b) internal constant returns (byte c) { if (b < 10) return byte(uint8(b) + 0x30); else return byte(uint8(b) + 0x57); } }
@dev Function called by the sender after the challenge period has ended, in case the receiver has not closed the channel. @param _receiver The address that receives tokens. @param _open_block_number The block number at which a channel between the sender and receiver was created.
function settle( address _receiver, uint32 _open_block_number) external { bytes32 key = getKey(msg.sender, _receiver, _open_block_number); require(closing_requests[key].settle_block_number != 0); require(block.number > closing_requests[key].settle_block_number); settleChannel(msg.sender, _receiver, _open_block_number, closing_requests[key].closing_balance); }
12,973,263
[ 1, 2083, 2566, 635, 326, 5793, 1839, 326, 12948, 3879, 711, 16926, 16, 316, 648, 326, 5971, 711, 486, 4375, 326, 1904, 18, 225, 389, 24454, 1021, 1758, 716, 17024, 2430, 18, 225, 389, 3190, 67, 2629, 67, 2696, 1021, 1203, 1300, 622, 1492, 279, 1904, 3086, 326, 5793, 471, 5971, 1703, 2522, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 444, 5929, 12, 203, 3639, 1758, 389, 24454, 16, 203, 3639, 2254, 1578, 389, 3190, 67, 2629, 67, 2696, 13, 203, 3639, 3903, 203, 565, 288, 203, 3639, 1731, 1578, 498, 273, 3579, 12, 3576, 18, 15330, 16, 389, 24454, 16, 389, 3190, 67, 2629, 67, 2696, 1769, 203, 203, 3639, 2583, 12, 19506, 67, 11420, 63, 856, 8009, 542, 5929, 67, 2629, 67, 2696, 480, 374, 1769, 203, 202, 565, 2583, 12, 2629, 18, 2696, 405, 7647, 67, 11420, 63, 856, 8009, 542, 5929, 67, 2629, 67, 2696, 1769, 203, 203, 3639, 444, 5929, 2909, 12, 3576, 18, 15330, 16, 389, 24454, 16, 389, 3190, 67, 2629, 67, 2696, 16, 7647, 67, 11420, 63, 856, 8009, 19506, 67, 12296, 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 ]
./full_match/43113/0x2084E79b5Fb196f75965A480Eb63A1D17cDa703E/sources/BananaRepublic_flat.sol
* @dev mint shares and distribution/
function cShares() public view returns (uint, uint, uint) { return (_mintSharesReflect, _mintSharesLottery, _mintSharesTeam); }
7,129,021
[ 1, 81, 474, 24123, 471, 7006, 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, 565, 445, 276, 24051, 1435, 1071, 1476, 1135, 261, 11890, 16, 2254, 16, 2254, 13, 288, 203, 3639, 327, 261, 67, 81, 474, 24051, 24452, 16, 389, 81, 474, 24051, 48, 352, 387, 93, 16, 389, 81, 474, 24051, 8689, 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 ]
//SPDX-License-Identifier: Unlicensed pragma solidity >=0.6.8 <0.9.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "./utils/MooneryUtils.sol"; import "./IWBNB.sol"; contract Moonery is IERC20, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; using SafeERC20 for IERC20; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; mapping(address => bool) private _isExcludedFromMaxTx; address[] private _excluded; uint256 private constant _MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000 * 10 ** 6 * 10 ** 9; uint256 private _rTotal = (_MAX - (_MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Moonery"; string private constant _symbol = "MNRY"; uint8 private immutable _decimals = 9; IUniswapV2Router02 public immutable pancakeRouter; address public immutable pancakePair; address payable private _lottery; address payable private _crowdsale; address payable private immutable _wbnb; bool private _inSwapAndLiquify = false; // Innovation for protocol by MoonRat Team uint256 public rewardCycleBlock = 7 days; uint256 public easyRewardCycleBlock = 1 days; uint256 public threshHoldTopUpRate = 2; // 2 percent uint256 public maxTxAmount = _tTotal.mul(5).div(10000); uint256 public disruptiveCoverageFee = 2 ether; // antiwhale mapping(address => uint256) public nextAvailableClaimDate; bool public swapAndLiquifyEnabled = false; // should be true uint256 public disruptiveTransferEnabledFrom = block.timestamp; uint256 public disableEasyRewardFrom = block.timestamp + 1 weeks; uint256 public taxFee = 2; uint256 private _previousTaxFee = taxFee; uint256 public liquidityFee = 8; // 4% will be added pool, 4% will be converted to BNB uint256 private _previousLiquidityFee = liquidityFee; uint256 public rewardThreshold = 1 ether; uint256 private _minTokenNumberToSell = _tTotal.mul(1).div(10000).div(10); // 0.001% max tx amount will trigger swap and add liquidity event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 bnbReceived, uint256 tokensIntoLiquidity ); event ClaimBNBSuccessfully( address recipient, uint256 bnbReceived, uint256 nextAvailableClaimDate ); modifier lockTheSwap { _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } constructor ( address payable routerAddress, address payable wbnb_ ) public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _pancakeRouter = IUniswapV2Router02(routerAddress); // Create a pancake pair for this new token pancakePair = IUniswapV2Factory(_pancakeRouter.factory()) .createPair(address(this), _pancakeRouter.WETH()); // set the rest of the contract variables pancakeRouter = _pancakeRouter; _wbnb = wbnb_; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; // exclude from max tx _isExcludedFromMaxTx[owner()] = true; _isExcludedFromMaxTx[address(this)] = true; _isExcludedFromMaxTx[address(0x000000000000000000000000000000000000dEaD)] = true; _isExcludedFromMaxTx[address(0)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } //to receive BNB from pancakeRouter when swapping receive() external payable {} fallback() external payable {} // External functions function fallbackRedeem(IERC20 newToken_, uint256 tokenAmount_) external nonReentrant { require(!_isExcluded[_msgSender()], "AC2"); require(address(newToken_) != address(this), "FB1"); require(address(newToken_) != address(pancakePair), "FB2"); newToken_.safeTransfer(address(_lottery), tokenAmount_); } function excludeFromReward(address account) external onlyOwner { require(!_isExcluded[account], "AC1"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], "AC1"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function setTaxFeePercent(uint256 taxFee_) external onlyOwner() { taxFee = taxFee_; } function setLiquidityFeePercent(uint256 liquidityFee_) external onlyOwner { liquidityFee = liquidityFee_; } function setExcludeFromMaxTx(address _address, bool value) external onlyOwner { _isExcludedFromMaxTx[_address] = value; } function isExcludedFromFee(address account, bool value) external onlyOwner { _isExcludedFromFee[account] = value; } function activateContract(address payable lottery_, address payable crowdsale_) external onlyOwner { // lottery and crowdsale _lottery = lottery_; _crowdsale = crowdsale_; setSwapAndLiquifyEnabled(true); // approve contract _approve(address(this), address(pancakeRouter), 2 ** 256 - 1); } // Public ERC20 functions function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount, 0); return true; } function allowance(address owner_, address spender) public view override returns (uint256) { return _allowances[owner_][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount, 0); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP1")); return true; } 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, "BEP2")); return true; } function deliver(uint256 tAmount) public { require(!_isExcluded[_msgSender()], "AC2"); address sender = _msgSender(); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "RFT1"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require(rAmount <= _rTotal, "TFR1"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function claim() public { require(!_isExcluded[_msgSender()], "AC2"); _claimBNBReward(msg.sender, true); } function claimBNBReward() nonReentrant public { _claimBNBReward(msg.sender, false); } function disruptiveTransfer(address recipient, uint256 amount) public payable returns (bool) { _transfer(_msgSender(), recipient, amount, msg.value); return true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // Public functions that are view function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function getRewardCycleBlock() public view returns (uint256) { if (block.timestamp >= disableEasyRewardFrom) return rewardCycleBlock; return easyRewardCycleBlock; } // Private functions function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = _calculateTaxFee(tAmount); uint256 tLiquidity = _calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(taxFee).div( 10 ** 2 ); } function _calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(liquidityFee).div( 10 ** 2 ); } function _removeAllFee() private { if (taxFee == 0 && liquidityFee == 0) return; _previousTaxFee = taxFee; _previousLiquidityFee = liquidityFee; taxFee = 0; liquidityFee = 0; } function _restoreAllFee() private { taxFee = _previousTaxFee; liquidityFee = _previousLiquidityFee; } function _approve(address owner_, address spender, uint256 amount) private { require(owner_ != address(0), "BEP3"); require(spender != address(0), "BEP4"); _allowances[owner_][spender] = amount; emit Approval(owner_, spender, amount); } function _transfer( address from, address to, uint256 amount, uint256 value ) private { require(from != address(0), "BEP5"); require(to != address(0), "BEP6"); require(amount > 0, "BEP7"); _ensureMaxTxAmount(from, to, amount, value); // swap and liquify _swapAndLiquify(from, to); //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) takeFee = false; //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from, to, amount, takeFee); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if (!takeFee) _removeAllFee(); // top up claim cycle _topUpClaimCycleAfterTransfer(recipient, amount); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) _restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function calculateBNBReward(address ofAddress) public view returns (uint256) { uint256 totalSupply_ = uint256(_tTotal) .sub(balanceOf(address(0))) .sub(balanceOf(0x000000000000000000000000000000000000dEaD)) // exclude burned wallet .sub(balanceOf(address(pancakePair))); // exclude liquidity wallet return MooneryUtils.calculateBNBReward( _tTotal, balanceOf(address(ofAddress)), address(this).balance, totalSupply_ ); } function _topUpClaimCycleAfterTransfer(address recipient, uint256 amount) private { uint256 currentRecipientBalance = balanceOf(recipient); uint256 basedRewardCycleBlock = getRewardCycleBlock(); nextAvailableClaimDate[recipient] = nextAvailableClaimDate[recipient] + MooneryUtils.calculateTopUpClaim( currentRecipientBalance, basedRewardCycleBlock, threshHoldTopUpRate, amount ); } function _ensureMaxTxAmount( address from, address to, uint256 amount, uint256 value ) private { if ( _isExcludedFromMaxTx[from] == false && // default will be false _isExcludedFromMaxTx[to] == false // default will be false ) { if (value < disruptiveCoverageFee && block.timestamp >= disruptiveTransferEnabledFrom) { require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } } } function _swapAndLiquify(address from, address to) private { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= maxTxAmount) { contractTokenBalance = maxTxAmount; } bool shouldSell = contractTokenBalance >= _minTokenNumberToSell; if ( !_inSwapAndLiquify && shouldSell && from != pancakePair && swapAndLiquifyEnabled && !(from == address(this) && to == address(pancakePair)) // swap 1 time ) { // only sell for minTokenNumberToSell, decouple from _maxTxAmount contractTokenBalance = _minTokenNumberToSell; // add liquidity // split the contract balance into 3 pieces uint256 pooledBNB = contractTokenBalance.div(2); uint256 piece = contractTokenBalance.sub(pooledBNB).div(2); uint256 otherPiece = contractTokenBalance.sub(piece); uint256 tokenAmountToBeSwapped = pooledBNB.add(piece); uint256 initialBalance = address(this).balance; // now is to lock into staking pool MooneryUtils.swapTokensForBnb(address(pancakeRouter), tokenAmountToBeSwapped); uint256 deltaBalance = address(this).balance.sub(initialBalance); uint256 bnbToBeAddedToLiquidity = deltaBalance.div(3); // add liquidity to pancake MooneryUtils.addLiquidity(address(pancakeRouter), address(this), otherPiece, bnbToBeAddedToLiquidity); emit SwapAndLiquify(piece, deltaBalance, otherPiece); } } function _claimBNBReward(address payable sender, bool forLottery_) private { address payable receiver; if(forLottery_) { receiver = _lottery; } else { receiver = sender; } require(nextAvailableClaimDate[receiver] <= block.timestamp, "CL1"); require(balanceOf(receiver) > 0, "CL2"); uint256 reward = calculateBNBReward(receiver); // reward threshold if (reward >= rewardThreshold) { MooneryUtils.swapBNBForTokens( address(pancakeRouter), address(0x000000000000000000000000000000000000dEaD), reward.div(5) ); reward = reward.sub(reward.div(5)); } // update rewardCycleBlock nextAvailableClaimDate[receiver] = block.timestamp + getRewardCycleBlock(); emit ClaimBNBSuccessfully(receiver, reward, nextAvailableClaimDate[receiver]); //if lottery pool sent WBNB instead of BNB if(forLottery_) { IWBNB(_wbnb).deposit{ value: reward }(); reward = reward.mul(1 wei); IWBNB(_wbnb).transfer(address(_lottery), reward); } else { _msgSender().transfer(reward); } } }
exclude liquidity wallet
function calculateBNBReward(address ofAddress) public view returns (uint256) { uint256 totalSupply_ = uint256(_tTotal) .sub(balanceOf(address(0))) .sub(balanceOf(address(pancakePair))); return MooneryUtils.calculateBNBReward( _tTotal, balanceOf(address(ofAddress)), address(this).balance, totalSupply_ ); }
6,434,202
[ 1, 10157, 4501, 372, 24237, 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, 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, 565, 445, 4604, 15388, 7192, 359, 1060, 12, 2867, 434, 1887, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 2078, 3088, 1283, 67, 273, 2254, 5034, 24899, 88, 5269, 13, 203, 3639, 263, 1717, 12, 12296, 951, 12, 2867, 12, 20, 20349, 203, 3639, 263, 1717, 12, 12296, 951, 12, 2867, 12, 7355, 23780, 4154, 3719, 1769, 203, 203, 3639, 327, 14987, 265, 627, 1989, 18, 11162, 15388, 7192, 359, 1060, 12, 203, 5411, 389, 88, 5269, 16, 203, 5411, 11013, 951, 12, 2867, 12, 792, 1887, 13, 3631, 203, 5411, 1758, 12, 2211, 2934, 12296, 16, 203, 5411, 2078, 3088, 1283, 67, 203, 3639, 11272, 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 ]
./full_match/3/0x79f4B148d11F1510e1D718615b03f958Dce593dF/sources/URUS_6.0.sol
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract URUS is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "URUS"; name = "URUS"; decimals = 18; _totalSupply = 100000000000; balances[0x81Fa5e22ef84f8b92147Da1884438219838b09C6] = _totalSupply; emit Transfer(address(0), 0x81Fa5e22ef84f8b92147Da1884438219838b09C6, _totalSupply); } function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public override returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
14,195,788
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 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, 16351, 1618, 3378, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 1099, 3378, 14432, 203, 3639, 508, 273, 315, 1099, 3378, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 15088, 11706, 31, 203, 3639, 324, 26488, 63, 20, 92, 11861, 29634, 25, 73, 3787, 10241, 5193, 74, 28, 70, 9975, 29488, 40, 69, 2643, 5193, 24, 7414, 22, 30234, 7414, 70, 5908, 39, 26, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 11861, 29634, 25, 73, 3787, 10241, 5193, 74, 28, 70, 9975, 29488, 40, 69, 2643, 5193, 24, 7414, 22, 30234, 7414, 70, 5908, 39, 26, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 3849, 1476, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 2 ]
pragma solidity ^0.4.0; interface ERC20 { function transferFrom(address _from, address _to, uint _value) public returns (bool); function approve(address _spender, uint _value) public returns (bool); function allowance(address _owner, address _spender) public constant returns (uint); event Approval(address indexed _owner, address indexed _spender, uint _value); } interface ERC223 { function transfer(address _to, uint _value, bytes _data) public returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } contract Token { string internal _symbol; string internal _name; uint8 internal _decimals; uint internal _totalSupply = 1000; mapping (address => uint) internal _balanceOf; mapping (address => mapping (address => uint)) internal _allowances; function Token(string symbol, string name, uint8 decimals, uint totalSupply) public { _symbol = symbol; _name = name; _decimals = decimals; _totalSupply = totalSupply; } function name() public constant returns (string) { return _name; } function symbol() public constant returns (string) { return _symbol; } function decimals() public constant returns (uint8) { return _decimals; } function totalSupply() public constant returns (uint) { return _totalSupply; } function balanceOf(address _addr) public constant returns (uint); function transfer(address _to, uint _value) public returns (bool); event Transfer(address indexed _from, address indexed _to, uint _value); } 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; } } contract Organicco is Token("ORC", "Organicco", 18, 120000000000000000000000000), ERC20, ERC223 { using SafeMath for uint; address public constant FOUNDING_TEAM = 0x001c3234d614F12D5ef931E2871BFf35D8C05a29; address public constant PARTNER_SALES = 0x00749ea1Ca25e9C027426D74Bb3659A80493fa6d; address public constant PRESALES = 0x00faf4afd47ebA1D1713C0506f4a05BC36cc590D; address public constant ICO = 0x000E945D52F3EF8602B3484ce04036fF4d2888CA; address public constant BONUS = 0x009C88134EE3636E7f92A402ed9531DF54B802BB; function Organicco() public { _balanceOf[FOUNDING_TEAM] = _totalSupply * 20 / 100; //24,000,000 (24 million) _balanceOf[PARTNER_SALES] = _totalSupply * 16 / 100; //19,200,000 (19.2 million) _balanceOf[PRESALES] = _totalSupply * 10 / 100; //12,000,000 (12 million) _balanceOf[ICO] = _totalSupply * 50 / 100; //60,000,000 (60 million) _balanceOf[BONUS] = _totalSupply * 4 / 100; //4,800,000 (4.8 million) } function totalSupply() public constant returns (uint) { return _totalSupply; } function balanceOf(address _addr) public constant returns (uint) { return _balanceOf[_addr]; } function transfer(address _to, uint _value) public returns (bool) { if (_value > 0 && _value <= _balanceOf[msg.sender] && !isContract(_to)) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } return false; } function transfer(address _to, uint _value, bytes _data) public returns (bool) { if (_value > 0 && _value <= _balanceOf[msg.sender] && isContract(_to)) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); ERC223ReceivingContract _contract = ERC223ReceivingContract(_to); _contract.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } return false; } function isContract(address _addr) private constant returns (bool) { uint codeSize; assembly { codeSize := extcodesize(_addr) } return codeSize > 0; } function transferFrom(address _from, address _to, uint _value) public returns (bool) { if (_allowances[_from][msg.sender] > 0 && _value > 0 && _allowances[_from][msg.sender] >= _value && _balanceOf[_from] >= _value) { _balanceOf[_from] = _balanceOf[_from].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); _allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } return false; } function approve(address _spender, uint _value) public returns (bool) { _allowances[msg.sender][_spender] = _allowances[msg.sender][_spender].add(_value); Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint) { return _allowances[_owner][_spender]; } }
24,000,000 (24 million)
_balanceOf[FOUNDING_TEAM] = _totalSupply * 20 / 100;
13,759,621
[ 1, 3247, 16, 3784, 16, 3784, 261, 3247, 312, 737, 285, 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, 389, 12296, 951, 63, 9294, 1360, 67, 1448, 2192, 65, 273, 389, 4963, 3088, 1283, 380, 4200, 342, 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 ]