file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
/** *Submitted for verification at Etherscan.io on 2022-03-01 */ pragma solidity ^0.8.4; /** BETERO TOKEN */ interface IERC20 { /** * @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 Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* * @dev 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) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () {address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Betero is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 private _decimals; string private _symbol; string private _name; constructor() public{ _name = "Betero"; _symbol = "BTE"; _decimals = 18; _totalSupply = 25 * 10**8 * 10**18; //100m tokens _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the erc token owner. */ function getOwner() external view returns (address) {return owner();} /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) {return _decimals;} /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol;} /** * @dev Returns the token name. */ function name() external view returns (string memory) {return _name; } /** * @dev See {ERC20-totalSupply}. */ function totalSupply() external view returns (uint256) {return _totalSupply; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {ERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {ERC20-allowance}. */ function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ERC20-approve}. * * Requirements: * * 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. * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {ERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) 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 {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) external 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) external virtual { uint256 decreasedAllowance = _allowances[account][_msgSender()].sub( amount, 'ERC20: burn amount exceeds allowance' ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { 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 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 Returns the erc token owner./
function getOwner() external view returns (address) {return owner();}
2,328,334
[ 1, 1356, 326, 6445, 71, 1147, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 13782, 1435, 3903, 1476, 1135, 261, 2867, 13, 288, 2463, 3410, 5621, 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, -100, -100, -100, -100 ]
pragma solidity >=0.5.0 <0.7.0; contract ERC20 { function transfer(address recipient, uint256 amount) public returns (bool); function transferFrom(address sender, address recipient, uint256 amount) public returns (bool); } contract EthBondManager { event DepositMade(address indexed account, address indexed token, uint256 indexed amount); event WithdrawalMade(address indexed account, address indexed token, uint256 indexed amount, address destination); event AllowProposal(address indexed account, address indexed proposal); event BondProcessed(address indexed account, address indexed proposal, address indexed token); struct Account { uint256 balance; // an account's total withdrawable balance (sum of deposits since last withdrawal) uint256 unlockBlock; // block number after which the balance can be withdrawn } mapping(bytes32 => Account) public accounts; mapping(bytes32 => bool) public approvals; // used to check if an account has approved its participation in a proposal function getAddressAddressKey(address addr1, address addr2) public pure returns (bytes32) { return sha256(abi.encodePacked(addr1, addr2)); } function deposit(address token, uint256 amount) public { assert(ERC20(token).transferFrom(msg.sender, address(this), amount)); bytes32 accountKey = getAddressAddressKey(msg.sender, token); uint256 balance = accounts[accountKey].balance; accounts[accountKey].balance += amount; assert(accounts[accountKey].balance > balance); // prevent overflow emit DepositMade(msg.sender, token, amount); } function withdraw(address token, address destination, uint256 amount) public { bytes32 accountKey = getAddressAddressKey(msg.sender, token); Account storage account = accounts[accountKey]; assert(block.number > account.unlockBlock); // account's amount must not be banded to any proposals assert(amount <= account.balance); // prevent underflow account.balance -= amount; // all or nothing ETH withdrawal (in wei), before transfer to prevent reentrancy account.unlockBlock = uint256(0); // this is moot, but at least frees up some state and reclaims some gas assert(ERC20(token).transfer(destination, amount)); emit WithdrawalMade(msg.sender, token, amount, destination); } function allow(address proposal) public { approvals[getAddressAddressKey(msg.sender, proposal)] = true; // calling account allows proposal to affect their account emit AllowProposal(msg.sender, proposal); } function processBond(address accountAddress, uint256 unlockBlock, address token) public { assert(approvals[getAddressAddressKey(accountAddress, msg.sender)]); // calling proposal can only deal with participating accounts bytes32 accountKey = getAddressAddressKey(accountAddress, token); Account storage account = accounts[accountKey]; // keep a copy to save on SLOAD as it will be reused later on if (account.unlockBlock < unlockBlock) { account.unlockBlock = unlockBlock; // bond the account's balance until voting for this proposal ends } emit BondProcessed(accountAddress, msg.sender, token); } }
this is moot, but at least frees up some state and reclaims some gas
account.unlockBlock = uint256(0);
941,248
[ 1, 2211, 353, 312, 1632, 16, 1496, 622, 4520, 284, 5312, 731, 2690, 919, 471, 283, 28979, 2690, 16189, 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, 2236, 18, 26226, 1768, 273, 2254, 5034, 12, 20, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.11; library OutputId { /** * @notice Computes the output ID for a deposit tx * @dev Deposit tx bytes might not be unique because all inputs are empty * Two deposits with the same output value would result in the same tx bytes * As a result, we need to hash with utxoPos to ensure uniqueness * @param _txBytes Transaction bytes * @param _outputIndex Output index of the output * @param _utxoPosValue (Optional) UTXO position of the deposit output */ function computeDepositOutputId(bytes memory _txBytes, uint256 _outputIndex, uint256 _utxoPosValue) internal pure returns(bytes32) { return keccak256(abi.encodePacked(_txBytes, _outputIndex, _utxoPosValue)); } /** * @notice Computes the output ID for normal (non-deposit) tx * @dev Since txBytes for non-deposit tx is unique, directly hash the txBytes with outputIndex * @param _txBytes Transaction bytes * @param _outputIndex Output index of the output */ function computeNormalOutputId(bytes memory _txBytes, uint256 _outputIndex) internal pure returns(bytes32) { return keccak256(abi.encodePacked(_txBytes, _outputIndex)); } }
* @notice Computes the output ID for a deposit tx @dev Deposit tx bytes might not be unique because all inputs are empty Two deposits with the same output value would result in the same tx bytes As a result, we need to hash with utxoPos to ensure uniqueness @param _txBytes Transaction bytes @param _outputIndex Output index of the output @param _utxoPosValue (Optional) UTXO position of the deposit output/
{ return keccak256(abi.encodePacked(_txBytes, _outputIndex, _utxoPosValue)); }
15,828,642
[ 1, 10743, 326, 876, 1599, 364, 279, 443, 1724, 2229, 225, 4019, 538, 305, 2229, 1731, 4825, 486, 506, 3089, 2724, 777, 4540, 854, 1008, 1377, 16896, 443, 917, 1282, 598, 326, 1967, 876, 460, 4102, 563, 316, 326, 1967, 2229, 1731, 1377, 2970, 279, 563, 16, 732, 1608, 358, 1651, 598, 5218, 25272, 1616, 358, 3387, 31596, 225, 389, 978, 2160, 5947, 1731, 225, 389, 2844, 1016, 3633, 770, 434, 326, 876, 225, 389, 322, 25272, 1616, 620, 261, 6542, 13, 4732, 60, 51, 1754, 434, 326, 443, 1724, 876, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 288, 203, 3639, 327, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 978, 2160, 16, 389, 2844, 1016, 16, 389, 322, 25272, 1616, 620, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-only pragma solidity =0.7.6; pragma abicoder v2; // interface import {IController} from "../interfaces/IController.sol"; import {IWPowerPerp} from "../interfaces/IWPowerPerp.sol"; import {IOracle} from "../interfaces/IOracle.sol"; import {IWETH9} from "../interfaces/IWETH9.sol"; import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import {IController} from "../interfaces/IController.sol"; // contract import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {StrategyBase} from "./base/StrategyBase.sol"; import {StrategyFlashSwap} from "./base/StrategyFlashSwap.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; // lib import {Address} from "@openzeppelin/contracts/utils/Address.sol"; // StrategyMath licensed under AGPL-3.0-only import {StrategyMath} from "./base/StrategyMath.sol"; import {Power2Base} from "../libs/Power2Base.sol"; /** * @dev CrabStrategy contract * @notice Contract for Crab strategy * @author Opyn team */ contract CrabStrategy is StrategyBase, StrategyFlashSwap, ReentrancyGuard, Ownable { using StrategyMath for uint256; using Address for address payable; /// @dev the cap in ETH for the strategy, above which deposits will be rejected uint256 public strategyCap; /// @dev the TWAP_PERIOD used in the PowerPerp Controller contract uint32 public constant POWER_PERP_PERIOD = 420 seconds; /// @dev twap period to use for hedge calculations uint32 public hedgingTwapPeriod = 420 seconds; /// @dev enum to differentiate between uniswap swap callback function source enum FLASH_SOURCE { FLASH_DEPOSIT, FLASH_WITHDRAW, FLASH_HEDGE_SELL, FLASH_HEDGE_BUY } /// @dev ETH:WSqueeth uniswap pool address public immutable ethWSqueethPool; /// @dev strategy uniswap oracle address public immutable oracle; address public immutable ethQuoteCurrencyPool; address public immutable quoteCurrency; /// @dev strategy will only allow hedging if collateral to trade is at least a set percentage of the total strategy collateral uint256 public deltaHedgeThreshold = 1e15; /// @dev time difference to trigger a hedge (seconds) uint256 public hedgeTimeThreshold; /// @dev price movement to trigger a hedge (0.1*1e18 = 10%) uint256 public hedgePriceThreshold; /// @dev hedge auction duration (seconds) uint256 public auctionTime; /// @dev start auction price multiplier for hedge buy auction and reserve price for hedge sell auction (scaled 1e18) uint256 public minPriceMultiplier; /// @dev start auction price multiplier for hedge sell auction and reserve price for hedge buy auction (scaled 1e18) uint256 public maxPriceMultiplier; /// @dev timestamp when last hedge executed uint256 public timeAtLastHedge; /// @dev WSqueeth/Eth price when last hedge executed uint256 public priceAtLastHedge; /// @dev set to true when redeemShortShutdown has been called bool private hasRedeemedInShutdown; struct FlashDepositData { uint256 totalDeposit; } struct FlashWithdrawData { uint256 crabAmount; } struct FlashHedgeData { uint256 wSqueethAmount; uint256 ethProceeds; uint256 minWSqueeth; uint256 minEth; } event Deposit(address indexed depositor, uint256 wSqueethAmount, uint256 lpAmount); event Withdraw(address indexed withdrawer, uint256 crabAmount, uint256 wSqueethAmount, uint256 ethWithdrawn); event WithdrawShutdown(address indexed withdrawer, uint256 crabAmount, uint256 ethWithdrawn); event FlashDeposit(address indexed depositor, uint256 depositedAmount, uint256 tradedAmountOut); event FlashWithdraw(address indexed withdrawer, uint256 crabAmount, uint256 wSqueethAmount); event FlashDepositCallback(address indexed depositor, uint256 flashswapDebt, uint256 excess); event FlashWithdrawCallback(address indexed withdrawer, uint256 flashswapDebt, uint256 excess); event TimeHedgeOnUniswap( address indexed hedger, uint256 hedgeTimestamp, uint256 auctionTriggerTimestamp, uint256 minWSqueeth, uint256 minEth ); event PriceHedgeOnUniswap( address indexed hedger, uint256 hedgeTimestamp, uint256 auctionTriggerTimestamp, uint256 minWSqueeth, uint256 minEth ); event TimeHedge(address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionTriggerTimestamp); event PriceHedge(address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionTriggerTimestamp); event Hedge( address indexed hedger, bool auctionType, uint256 hedgerPrice, uint256 auctionPrice, uint256 wSqueethHedgeTargetAmount, uint256 ethHedgetargetAmount ); event HedgeOnUniswap( address indexed hedger, bool auctionType, uint256 auctionPrice, uint256 wSqueethHedgeTargetAmount, uint256 ethHedgetargetAmount ); event ExecuteSellAuction(address indexed buyer, uint256 wSqueethSold, uint256 ethBought, bool isHedgingOnUniswap); event ExecuteBuyAuction(address indexed seller, uint256 wSqueethBought, uint256 ethSold, bool isHedgingOnUniswap); event SetStrategyCap(uint256 newCapAmount); event SetDeltaHedgeThreshold(uint256 newDeltaHedgeThreshold); event SetHedgingTwapPeriod(uint32 newHedgingTwapPeriod); event SetHedgeTimeThreshold(uint256 newHedgeTimeThreshold); event SetHedgePriceThreshold(uint256 newHedgePriceThreshold); event SetAuctionTime(uint256 newAuctionTime); event SetMinPriceMultiplier(uint256 newMinPriceMultiplier); event SetMaxPriceMultiplier(uint256 newMaxPriceMultiplier); /** * @notice strategy constructor * @dev this will open a vault in the power token contract and store the vault ID * @param _wSqueethController power token controller address * @param _oracle oracle address * @param _weth weth address * @param _uniswapFactory uniswap factory address * @param _ethWSqueethPool eth:wSqueeth uniswap pool address * @param _hedgeTimeThreshold hedge time threshold (seconds) * @param _hedgePriceThreshold hedge price threshold (0.1*1e18 = 10%) * @param _auctionTime auction duration (seconds) * @param _minPriceMultiplier minimum auction price multiplier (0.9*1e18 = min auction price is 90% of twap) * @param _maxPriceMultiplier maximum auction price multiplier (1.1*1e18 = max auction price is 110% of twap) */ constructor( address _wSqueethController, address _oracle, address _weth, address _uniswapFactory, address _ethWSqueethPool, uint256 _hedgeTimeThreshold, uint256 _hedgePriceThreshold, uint256 _auctionTime, uint256 _minPriceMultiplier, uint256 _maxPriceMultiplier ) StrategyBase(_wSqueethController, _weth, "Crab Strategy", "Crab") StrategyFlashSwap(_uniswapFactory) { require(_oracle != address(0), "invalid oracle address"); require(_ethWSqueethPool != address(0), "invalid ETH:WSqueeth address"); require(_hedgeTimeThreshold > 0, "invalid hedge time threshold"); require(_hedgePriceThreshold > 0, "invalid hedge price threshold"); require(_auctionTime > 0, "invalid auction time"); require(_minPriceMultiplier < 1e18, "min price multiplier too high"); require(_minPriceMultiplier > 0, "invalid min price multiplier"); require(_maxPriceMultiplier > 1e18, "max price multiplier too low"); oracle = _oracle; ethWSqueethPool = _ethWSqueethPool; hedgeTimeThreshold = _hedgeTimeThreshold; hedgePriceThreshold = _hedgePriceThreshold; auctionTime = _auctionTime; minPriceMultiplier = _minPriceMultiplier; maxPriceMultiplier = _maxPriceMultiplier; ethQuoteCurrencyPool = IController(_wSqueethController).ethQuoteCurrencyPool(); quoteCurrency = IController(_wSqueethController).quoteCurrency(); } /** * @notice receive function to allow ETH transfer to this contract */ receive() external payable { require(msg.sender == weth || msg.sender == address(powerTokenController), "Cannot receive eth"); } /** * @notice owner can set the strategy cap in ETH collateral terms * @dev deposits are rejected if it would put the strategy above the cap amount * @dev strategy collateral can be above the cap amount due to hedging activities * @param _capAmount the maximum strategy collateral in ETH, checked on deposits */ function setStrategyCap(uint256 _capAmount) external onlyOwner { strategyCap = _capAmount; emit SetStrategyCap(_capAmount); } /** * @notice called to redeem the net value of a vault post shutdown * @dev needs to be called 1 time before users can exit the strategy using withdrawShutdown */ function redeemShortShutdown() external { hasRedeemedInShutdown = true; powerTokenController.redeemShort(vaultId); } /** * @notice flash deposit into strategy, providing ETH, selling wSqueeth and receiving strategy tokens * @dev this function will execute a flash swap where it receives ETH, deposits and mints using flash swap proceeds and msg.value, and then repays the flash swap with wSqueeth * @dev _ethToDeposit must be less than msg.value plus the proceeds from the flash swap * @dev the difference between _ethToDeposit and msg.value provides the minimum that a user can receive for their sold wSqueeth * @param _ethToDeposit total ETH that will be deposited in to the strategy which is a combination of msg.value and flash swap proceeds */ function flashDeposit(uint256 _ethToDeposit) external payable nonReentrant { (uint256 cachedStrategyDebt, uint256 cachedStrategyCollateral) = _syncStrategyState(); _checkStrategyCap(_ethToDeposit, cachedStrategyCollateral); (uint256 wSqueethToMint, ) = _calcWsqueethToMintAndFee( _ethToDeposit, cachedStrategyDebt, cachedStrategyCollateral ); if (cachedStrategyDebt == 0 && cachedStrategyCollateral == 0) { // store hedge data as strategy is delta neutral at this point // only execute this upon first deposit uint256 wSqueethEthPrice = IOracle(oracle).getTwap( ethWSqueethPool, wPowerPerp, weth, hedgingTwapPeriod, true ); timeAtLastHedge = block.timestamp; priceAtLastHedge = wSqueethEthPrice; } _exactInFlashSwap( wPowerPerp, weth, IUniswapV3Pool(ethWSqueethPool).fee(), wSqueethToMint, _ethToDeposit.sub(msg.value), uint8(FLASH_SOURCE.FLASH_DEPOSIT), abi.encodePacked(_ethToDeposit) ); emit FlashDeposit(msg.sender, _ethToDeposit, wSqueethToMint); } /** * @notice flash withdraw from strategy, providing strategy tokens, buying wSqueeth, burning and receiving ETH * @dev this function will execute a flash swap where it receives wSqueeth, burns, withdraws ETH and then repays the flash swap with ETH * @param _crabAmount strategy token amount to burn * @param _maxEthToPay maximum ETH to pay to buy back the owed wSqueeth debt */ function flashWithdraw(uint256 _crabAmount, uint256 _maxEthToPay) external nonReentrant { uint256 exactWSqueethNeeded = _getDebtFromStrategyAmount(_crabAmount); _exactOutFlashSwap( weth, wPowerPerp, IUniswapV3Pool(ethWSqueethPool).fee(), exactWSqueethNeeded, _maxEthToPay, uint8(FLASH_SOURCE.FLASH_WITHDRAW), abi.encodePacked(_crabAmount) ); emit FlashWithdraw(msg.sender, _crabAmount, exactWSqueethNeeded); } /** * @notice deposit ETH into strategy * @dev provide ETH, return wSqueeth and strategy token */ function deposit() external payable nonReentrant { uint256 amount = msg.value; (uint256 wSqueethToMint, uint256 depositorCrabAmount) = _deposit(msg.sender, amount, false); emit Deposit(msg.sender, wSqueethToMint, depositorCrabAmount); } /** * @notice withdraw WETH from strategy * @dev provide strategy tokens and wSqueeth, returns eth * @param _crabAmount amount of strategy token to burn */ function withdraw(uint256 _crabAmount) external nonReentrant { uint256 wSqueethAmount = _getDebtFromStrategyAmount(_crabAmount); uint256 ethToWithdraw = _withdraw(msg.sender, _crabAmount, wSqueethAmount, false); // send back ETH collateral payable(msg.sender).sendValue(ethToWithdraw); emit Withdraw(msg.sender, _crabAmount, wSqueethAmount, ethToWithdraw); } /** * @notice called to exit a vault if the Squeeth Power Perp contracts are shutdown * @param _crabAmount amount of strategy token to burn */ function withdrawShutdown(uint256 _crabAmount) external nonReentrant { require(powerTokenController.isShutDown(), "Squeeth contracts not shut down"); require(hasRedeemedInShutdown, "Crab must redeemShortShutdown"); uint256 strategyShare = _calcCrabRatio(_crabAmount, totalSupply()); uint256 ethToWithdraw = _calcEthToWithdraw(strategyShare, address(this).balance); _burn(msg.sender, _crabAmount); payable(msg.sender).sendValue(ethToWithdraw); emit WithdrawShutdown(msg.sender, _crabAmount, ethToWithdraw); } /** * @notice hedge startegy based on time threshold with uniswap arbing * @dev this function atomically hedges on uniswap and provides a bounty to the caller based on the difference * @dev between uniswap execution price and the price of the hedging auction * @param _minWSqueeth minimum WSqueeth amount the caller willing to receive if hedge auction is selling WSqueeth * @param _minEth minimum ETH amount the caller is willing to receive if hedge auction is buying WSqueeth */ function timeHedgeOnUniswap(uint256 _minWSqueeth, uint256 _minEth) external { (bool isTimeHedgeAllowed, uint256 auctionTriggerTime) = _isTimeHedge(); require(isTimeHedgeAllowed, "Time hedging is not allowed"); _hedgeOnUniswap(auctionTriggerTime, _minWSqueeth, _minEth); emit TimeHedgeOnUniswap(msg.sender, block.timestamp, auctionTriggerTime, _minWSqueeth, _minEth); } /** * @notice hedge startegy based on price threshold with uniswap arbing * @dev this function atomically hedges on uniswap and provides a bounty to the caller based on the difference * @dev between uniswap execution price and the price of the hedging auction * @param _auctionTriggerTime the time when the price deviation threshold was exceeded and when the auction started * @param _minWSqueeth minimum WSqueeth amount the caller willing to receive if hedge auction is selling WSqueeth * @param _minEth minimum ETH amount the caller is willing to receive if hedge auction is buying WSqueeth */ function priceHedgeOnUniswap( uint256 _auctionTriggerTime, uint256 _minWSqueeth, uint256 _minEth ) external payable { require(_isPriceHedge(_auctionTriggerTime), "Price hedging not allowed"); _hedgeOnUniswap(_auctionTriggerTime, _minWSqueeth, _minEth); emit PriceHedgeOnUniswap(msg.sender, block.timestamp, _auctionTriggerTime, _minWSqueeth, _minEth); } /** * @notice strategy hedging based on time threshold * @dev need to attach msg.value if buying WSqueeth * @param _isStrategySellingWSqueeth sell or buy auction, true for sell auction * @param _limitPrice hedger limit auction price, should be the max price when auction is sell auction, min price when it is a buy auction */ function timeHedge(bool _isStrategySellingWSqueeth, uint256 _limitPrice) external payable nonReentrant { (bool isTimeHedgeAllowed, uint256 auctionTriggerTime) = _isTimeHedge(); require(isTimeHedgeAllowed, "Time hedging is not allowed"); _hedge(auctionTriggerTime, _isStrategySellingWSqueeth, _limitPrice); emit TimeHedge(msg.sender, _isStrategySellingWSqueeth, _limitPrice, auctionTriggerTime); } /** * @notice strategy hedging based on price threshold * @dev need to attach msg.value if buying WSqueeth * @param _auctionTriggerTime the time when the price deviation threshold was exceeded and when the auction started * @param _isStrategySellingWSqueeth specify the direction of the trade that you expect, this choice impacts the limit price chosen * @param _limitPrice the min or max price that you will trade at, depending on if buying or selling */ function priceHedge( uint256 _auctionTriggerTime, bool _isStrategySellingWSqueeth, uint256 _limitPrice ) external payable nonReentrant { require(_isPriceHedge(_auctionTriggerTime), "Price hedging not allowed"); _hedge(_auctionTriggerTime, _isStrategySellingWSqueeth, _limitPrice); emit PriceHedge(msg.sender, _isStrategySellingWSqueeth, _limitPrice, _auctionTriggerTime); } /** * @notice check if hedging based on price threshold is allowed * @param _auctionTriggerTime the time when the price deviation threshold was exceeded and when the auction started * @return true if hedging is allowed */ function checkPriceHedge(uint256 _auctionTriggerTime) external view returns (bool) { return _isPriceHedge(_auctionTriggerTime); } /** * @notice check if hedging based on time threshold is allowed * @return isTimeHedgeAllowed true if hedging is allowed * @return auctionTriggertime auction trigger timestamp */ function checkTimeHedge() external view returns (bool, uint256) { return _isTimeHedge(); } /** * @notice get wSqueeth debt amount associated with strategy token amount * @param _crabAmount strategy token amount * @return wSqueeth amount */ function getWsqueethFromCrabAmount(uint256 _crabAmount) external view returns (uint256) { return _getDebtFromStrategyAmount(_crabAmount); } /** * @notice owner can set the delta hedge threshold as a percent scaled by 1e18 of ETH collateral * @dev the strategy will not allow a hedge if the trade size is below this threshold * @param _deltaHedgeThreshold minimum hedge size in a percent of ETH collateral */ function setDeltaHedgeThreshold(uint256 _deltaHedgeThreshold) external onlyOwner { deltaHedgeThreshold = _deltaHedgeThreshold; emit SetDeltaHedgeThreshold(_deltaHedgeThreshold); } /** * @notice owner can set the twap period in seconds that is used for calculating twaps for hedging * @param _hedgingTwapPeriod the twap period, in seconds */ function setHedgingTwapPeriod(uint32 _hedgingTwapPeriod) external onlyOwner { require(_hedgingTwapPeriod >= 180, "twap period is too short"); hedgingTwapPeriod = _hedgingTwapPeriod; emit SetHedgingTwapPeriod(_hedgingTwapPeriod); } /** * @notice owner can set the hedge time threshold in seconds that determines how often the strategy can be hedged * @param _hedgeTimeThreshold the hedge time threshold, in seconds */ function setHedgeTimeThreshold(uint256 _hedgeTimeThreshold) external onlyOwner { require(_hedgeTimeThreshold > 0, "invalid hedge time threshold"); hedgeTimeThreshold = _hedgeTimeThreshold; emit SetHedgeTimeThreshold(_hedgeTimeThreshold); } /** * @notice owner can set the hedge time threshold in percent, scaled by 1e18 that determines the deviation in wPowerPerp price that can trigger a rebalance * @param _hedgePriceThreshold the hedge price threshold, in percent, scaled by 1e18 */ function setHedgePriceThreshold(uint256 _hedgePriceThreshold) external onlyOwner { require(_hedgePriceThreshold > 0, "invalid hedge price threshold"); hedgePriceThreshold = _hedgePriceThreshold; emit SetHedgePriceThreshold(_hedgePriceThreshold); } /** * @notice owner can set the auction time, in seconds, that a hedge auction runs for * @param _auctionTime the length of the hedge auction in seconds */ function setAuctionTime(uint256 _auctionTime) external onlyOwner { require(_auctionTime > 0, "invalid auction time"); auctionTime = _auctionTime; emit SetAuctionTime(_auctionTime); } /** * @notice owner can set the min price multiplier in a percentage scaled by 1e18 (9e17 is 90%) * @dev the min price multiplier is multiplied by the TWAP price to get the intial auction price * @param _minPriceMultiplier the min price multiplier, a percentage, scaled by 1e18 */ function setMinPriceMultiplier(uint256 _minPriceMultiplier) external onlyOwner { require(_minPriceMultiplier < 1e18, "min price multiplier too high"); minPriceMultiplier = _minPriceMultiplier; emit SetMinPriceMultiplier(_minPriceMultiplier); } /** * @notice owner can set the max price multiplier in a percentage scaled by 1e18 (11e18 is 110%) * @dev the max price multiplier is multiplied by the TWAP price to get the final auction price * @param _maxPriceMultiplier the max price multiplier, a percentage, scaled by 1e18 */ function setMaxPriceMultiplier(uint256 _maxPriceMultiplier) external onlyOwner { require(_maxPriceMultiplier > 1e18, "max price multiplier too low"); maxPriceMultiplier = _maxPriceMultiplier; emit SetMaxPriceMultiplier(_maxPriceMultiplier); } /** * @notice get current auction details * @param _auctionTriggerTime timestamp where auction started * @return if strategy is selling wSqueeth, wSqueeth amount to auction, ETH proceeds, auction price, if auction direction has switched */ function getAuctionDetails(uint256 _auctionTriggerTime) external view returns ( bool, uint256, uint256, uint256, bool ) { (uint256 strategyDebt, uint256 ethDelta) = _syncStrategyState(); uint256 currentWSqueethPrice = IOracle(oracle).getTwap( ethWSqueethPool, wPowerPerp, weth, hedgingTwapPeriod, true ); uint256 feeAdjustment = _calcFeeAdjustment(); (bool isSellingAuction, ) = _checkAuctionType(strategyDebt, ethDelta, currentWSqueethPrice, feeAdjustment); uint256 auctionWSqueethEthPrice = _getAuctionPrice(_auctionTriggerTime, currentWSqueethPrice, isSellingAuction); (bool isStillSellingAuction, uint256 wSqueethToAuction) = _checkAuctionType( strategyDebt, ethDelta, auctionWSqueethEthPrice, feeAdjustment ); bool isAuctionDirectionChanged = isSellingAuction != isStillSellingAuction; uint256 ethProceeds = wSqueethToAuction.wmul(auctionWSqueethEthPrice); return (isSellingAuction, wSqueethToAuction, ethProceeds, auctionWSqueethEthPrice, isAuctionDirectionChanged); } /** * @notice check if a user deposit puts the strategy above the cap * @dev reverts if a deposit amount puts strategy over the cap * @dev it is possible for the strategy to be over the cap from trading/hedging activities, but withdrawals are still allowed * @param _depositAmount the user deposit amount in ETH * @param _strategyCollateral the updated strategy collateral */ function _checkStrategyCap(uint256 _depositAmount, uint256 _strategyCollateral) internal view { require(_strategyCollateral.add(_depositAmount) <= strategyCap, "Deposit exceeds strategy cap"); } /** * @notice uniswap flash swap callback function * @dev this function will be called by flashswap callback function uniswapV3SwapCallback() * @param _caller address of original function caller * @param _amountToPay amount to pay back for flashswap * @param _callData arbitrary data attached to callback * @param _callSource identifier for which function triggered callback */ function _strategyFlash( address _caller, address, /*_tokenIn*/ address, /*_tokenOut*/ uint24, /*_fee*/ uint256 _amountToPay, bytes memory _callData, uint8 _callSource ) internal override { if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_DEPOSIT) { FlashDepositData memory data = abi.decode(_callData, (FlashDepositData)); // convert WETH to ETH as Uniswap uses WETH IWETH9(weth).withdraw(IWETH9(weth).balanceOf(address(this))); //use user msg.value and unwrapped WETH from uniswap flash swap proceeds to deposit into strategy //will revert if data.totalDeposit is > eth balance in contract _deposit(_caller, data.totalDeposit, true); //repay the flash swap IWPowerPerp(wPowerPerp).transfer(ethWSqueethPool, _amountToPay); emit FlashDepositCallback(_caller, _amountToPay, address(this).balance); //return excess eth to the user that was not needed for slippage if (address(this).balance > 0) { payable(_caller).sendValue(address(this).balance); } } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_WITHDRAW) { FlashWithdrawData memory data = abi.decode(_callData, (FlashWithdrawData)); //use flash swap wSqueeth proceeds to withdraw ETH along with user crabAmount uint256 ethToWithdraw = _withdraw( _caller, data.crabAmount, IWPowerPerp(wPowerPerp).balanceOf(address(this)), true ); //use some amount of withdrawn ETH to repay flash swap IWETH9(weth).deposit{value: _amountToPay}(); IWETH9(weth).transfer(ethWSqueethPool, _amountToPay); //excess ETH not used to repay flash swap is transferred to the user uint256 proceeds = ethToWithdraw.sub(_amountToPay); emit FlashWithdrawCallback(_caller, _amountToPay, proceeds); if (proceeds > 0) { payable(_caller).sendValue(proceeds); } } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_HEDGE_SELL) { //strategy is selling wSqueeth for ETH FlashHedgeData memory data = abi.decode(_callData, (FlashHedgeData)); // convert WETH to ETH as Uniswap uses WETH IWETH9(weth).withdraw(IWETH9(weth).balanceOf(address(this))); //mint wSqueeth to pay hedger and repay flash swap, deposit ETH _executeSellAuction(_caller, data.ethProceeds, data.wSqueethAmount, data.ethProceeds, true); //determine excess wSqueeth that the auction would have sold but is not needed to repay flash swap uint256 wSqueethProfit = data.wSqueethAmount.sub(_amountToPay); //minimum profit check for hedger require(wSqueethProfit >= data.minWSqueeth, "profit is less than min wSqueeth"); //repay flash swap and transfer profit to hedger IWPowerPerp(wPowerPerp).transfer(ethWSqueethPool, _amountToPay); IWPowerPerp(wPowerPerp).transfer(_caller, wSqueethProfit); } else if (FLASH_SOURCE(_callSource) == FLASH_SOURCE.FLASH_HEDGE_BUY) { //strategy is buying wSqueeth for ETH FlashHedgeData memory data = abi.decode(_callData, (FlashHedgeData)); //withdraw ETH to pay hedger and repay flash swap, burn wSqueeth _executeBuyAuction(_caller, data.wSqueethAmount, data.ethProceeds, true); //determine excess ETH that the auction would have paid but is not needed to repay flash swap uint256 ethProfit = data.ethProceeds.sub(_amountToPay); //minimum profit check for hedger require(ethProfit >= data.minEth, "profit is less than min ETH"); //repay flash swap and transfer profit to hedger IWETH9(weth).deposit{value: _amountToPay}(); IWETH9(weth).transfer(ethWSqueethPool, _amountToPay); payable(_caller).sendValue(ethProfit); } } /** * @notice deposit into strategy * @dev if _isFlashDeposit is true, keeps wSqueeth in contract, otherwise sends to user * @param _depositor depositor address * @param _amount amount of ETH collateral to deposit * @param _isFlashDeposit true if called by flashDeposit * @return wSqueethToMint minted amount of WSqueeth * @return depositorCrabAmount minted CRAB strategy token amount */ function _deposit( address _depositor, uint256 _amount, bool _isFlashDeposit ) internal returns (uint256, uint256) { (uint256 strategyDebt, uint256 strategyCollateral) = _syncStrategyState(); _checkStrategyCap(_amount, strategyCollateral); (uint256 wSqueethToMint, uint256 ethFee) = _calcWsqueethToMintAndFee(_amount, strategyDebt, strategyCollateral); uint256 depositorCrabAmount = _calcSharesToMint(_amount.sub(ethFee), strategyCollateral, totalSupply()); if (strategyDebt == 0 && strategyCollateral == 0) { // store hedge data as strategy is delta neutral at this point // only execute this upon first deposit uint256 wSqueethEthPrice = IOracle(oracle).getTwap( ethWSqueethPool, wPowerPerp, weth, hedgingTwapPeriod, true ); timeAtLastHedge = block.timestamp; priceAtLastHedge = wSqueethEthPrice; } // mint wSqueeth and send it to msg.sender _mintWPowerPerp(_depositor, wSqueethToMint, _amount, _isFlashDeposit); // mint LP to depositor _mintStrategyToken(_depositor, depositorCrabAmount); return (wSqueethToMint, depositorCrabAmount); } /** * @notice withdraw WETH from strategy * @dev if _isFlashDeposit is true, keeps wSqueeth in contract, otherwise sends to user * @param _crabAmount amount of strategy token to burn * @param _wSqueethAmount amount of wSqueeth to burn * @param _isFlashWithdraw flag if called by flashWithdraw * @return ETH amount to withdraw */ function _withdraw( address _from, uint256 _crabAmount, uint256 _wSqueethAmount, bool _isFlashWithdraw ) internal returns (uint256) { (, uint256 strategyCollateral) = _syncStrategyState(); uint256 strategyShare = _calcCrabRatio(_crabAmount, totalSupply()); uint256 ethToWithdraw = _calcEthToWithdraw(strategyShare, strategyCollateral); _burnWPowerPerp(_from, _wSqueethAmount, ethToWithdraw, _isFlashWithdraw); _burn(_from, _crabAmount); return ethToWithdraw; } /** * @notice hedging function to adjust collateral and debt to be eth delta neutral * @param _auctionTriggerTime timestamp where auction started * @param _isStrategySellingWSqueeth auction type, true for sell auction * @param _limitPrice hedger accepted auction price, should be the max price when auction is sell auction, min price when it is a buy auction */ function _hedge( uint256 _auctionTriggerTime, bool _isStrategySellingWSqueeth, uint256 _limitPrice ) internal { ( bool isSellingAuction, uint256 wSqueethToAuction, uint256 ethProceeds, uint256 auctionWSqueethEthPrice ) = _startAuction(_auctionTriggerTime); require(_isStrategySellingWSqueeth == isSellingAuction, "wrong auction type"); if (isSellingAuction) { // Receiving ETH and paying wSqueeth require(auctionWSqueethEthPrice <= _limitPrice, "Auction price > max price"); require(msg.value >= ethProceeds, "Low ETH amount received"); _executeSellAuction(msg.sender, msg.value, wSqueethToAuction, ethProceeds, false); } else { require(msg.value == 0, "ETH attached for buy auction"); // Receiving wSqueeth and paying ETH require(auctionWSqueethEthPrice >= _limitPrice, "Auction price < min price"); _executeBuyAuction(msg.sender, wSqueethToAuction, ethProceeds, false); } emit Hedge( msg.sender, _isStrategySellingWSqueeth, _limitPrice, auctionWSqueethEthPrice, wSqueethToAuction, ethProceeds ); } /** * @notice execute arb between auction price and uniswap price * @param _auctionTriggerTime auction starting time * @param _minWSqueeth minimum WSqueeth amount the caller willing to receive if hedge auction is selling WSqueeth * @param _minEth minimum ETH amount the caller is willing to receive if hedge auction is buying WSqueeth */ function _hedgeOnUniswap( uint256 _auctionTriggerTime, uint256 _minWSqueeth, uint256 _minEth ) internal { ( bool isSellingAuction, uint256 wSqueethToAuction, uint256 ethProceeds, uint256 auctionWSqueethEthPrice ) = _startAuction(_auctionTriggerTime); if (isSellingAuction) { _exactOutFlashSwap( wPowerPerp, weth, IUniswapV3Pool(ethWSqueethPool).fee(), ethProceeds, wSqueethToAuction, uint8(FLASH_SOURCE.FLASH_HEDGE_SELL), abi.encodePacked(wSqueethToAuction, ethProceeds, _minWSqueeth, _minEth) ); } else { _exactOutFlashSwap( weth, wPowerPerp, IUniswapV3Pool(ethWSqueethPool).fee(), wSqueethToAuction, ethProceeds, uint8(FLASH_SOURCE.FLASH_HEDGE_BUY), abi.encodePacked(wSqueethToAuction, ethProceeds, _minWSqueeth, _minEth) ); } emit HedgeOnUniswap(msg.sender, isSellingAuction, auctionWSqueethEthPrice, wSqueethToAuction, ethProceeds); } /** * @notice execute sell auction based on the parameters calculated * @dev if _isHedgingOnUniswap, wSqueeth minted is kept to repay flashswap, otherwise sent to seller * @param _buyer buyer address * @param _buyerAmount buyer ETH amount sent * @param _wSqueethToSell wSqueeth amount to sell * @param _ethToBuy ETH amount to buy * @param _isHedgingOnUniswap true if arbing with uniswap price */ function _executeSellAuction( address _buyer, uint256 _buyerAmount, uint256 _wSqueethToSell, uint256 _ethToBuy, bool _isHedgingOnUniswap ) internal { if (_isHedgingOnUniswap) { _mintWPowerPerp(_buyer, _wSqueethToSell, _ethToBuy, true); } else { _mintWPowerPerp(_buyer, _wSqueethToSell, _ethToBuy, false); uint256 remainingEth = _buyerAmount.sub(_ethToBuy); if (remainingEth > 0) { payable(_buyer).sendValue(remainingEth); } } emit ExecuteSellAuction(_buyer, _wSqueethToSell, _ethToBuy, _isHedgingOnUniswap); } /** * @notice execute buy auction based on the parameters calculated * @dev if _isHedgingOnUniswap, ETH proceeds are not sent to seller * @param _seller seller address * @param _wSqueethToBuy wSqueeth amount to buy * @param _ethToSell ETH amount to sell * @param _isHedgingOnUniswap true if arbing with uniswap price */ function _executeBuyAuction( address _seller, uint256 _wSqueethToBuy, uint256 _ethToSell, bool _isHedgingOnUniswap ) internal { _burnWPowerPerp(_seller, _wSqueethToBuy, _ethToSell, _isHedgingOnUniswap); if (!_isHedgingOnUniswap) { payable(_seller).sendValue(_ethToSell); } emit ExecuteBuyAuction(_seller, _wSqueethToBuy, _ethToSell, _isHedgingOnUniswap); } /** * @notice determine auction direction, price, and ensure auction hasn't switched directions * @param _auctionTriggerTime auction starting time * @return auction type * @return WSqueeth amount to sell or buy * @return ETH to sell/buy * @return auction WSqueeth/ETH price */ function _startAuction(uint256 _auctionTriggerTime) internal returns ( bool, uint256, uint256, uint256 ) { (uint256 strategyDebt, uint256 ethDelta) = _syncStrategyState(); uint256 currentWSqueethPrice = IOracle(oracle).getTwap( ethWSqueethPool, wPowerPerp, weth, hedgingTwapPeriod, true ); uint256 feeAdjustment = _calcFeeAdjustment(); (bool isSellingAuction, ) = _checkAuctionType(strategyDebt, ethDelta, currentWSqueethPrice, feeAdjustment); uint256 auctionWSqueethEthPrice = _getAuctionPrice(_auctionTriggerTime, currentWSqueethPrice, isSellingAuction); (bool isStillSellingAuction, uint256 wSqueethToAuction) = _checkAuctionType( strategyDebt, ethDelta, auctionWSqueethEthPrice, feeAdjustment ); require(isSellingAuction == isStillSellingAuction, "auction direction changed"); uint256 ethProceeds = wSqueethToAuction.wmul(auctionWSqueethEthPrice); timeAtLastHedge = block.timestamp; priceAtLastHedge = currentWSqueethPrice; return (isSellingAuction, wSqueethToAuction, ethProceeds, auctionWSqueethEthPrice); } /** * @notice sync strategy debt and collateral amount from vault * @return synced debt amount * @return synced collateral amount */ function _syncStrategyState() internal view returns (uint256, uint256) { (, , uint256 syncedStrategyCollateral, uint256 syncedStrategyDebt) = _getVaultDetails(); return (syncedStrategyDebt, syncedStrategyCollateral); } /** * @notice calculate the fee adjustment factor, which is the amount of ETH owed per 1 wSqueeth minted * @dev the fee is a based off the index value of squeeth and uses a twap scaled down by the PowerPerp's INDEX_SCALE * @return the fee adjustment factor */ function _calcFeeAdjustment() internal view returns (uint256) { uint256 wSqueethEthPrice = Power2Base._getTwap( oracle, ethWSqueethPool, wPowerPerp, weth, POWER_PERP_PERIOD, false ); uint256 feeRate = IController(powerTokenController).feeRate(); return wSqueethEthPrice.mul(feeRate).div(10000); } /** * @notice calculate amount of wSqueeth to mint and fee paid from deposited amount * @param _depositedAmount amount of deposited WETH * @param _strategyDebtAmount amount of strategy debt * @param _strategyCollateralAmount collateral amount in strategy * @return amount of minted wSqueeth and ETH fee paid on minted squeeth */ function _calcWsqueethToMintAndFee( uint256 _depositedAmount, uint256 _strategyDebtAmount, uint256 _strategyCollateralAmount ) internal view returns (uint256, uint256) { uint256 wSqueethToMint; uint256 feeAdjustment = _calcFeeAdjustment(); if (_strategyDebtAmount == 0 && _strategyCollateralAmount == 0) { require(totalSupply() == 0, "Crab contracts shut down"); uint256 wSqueethEthPrice = IOracle(oracle).getTwap( ethWSqueethPool, wPowerPerp, weth, hedgingTwapPeriod, true ); uint256 squeethDelta = wSqueethEthPrice.wmul(2e18); wSqueethToMint = _depositedAmount.wdiv(squeethDelta.add(feeAdjustment)); } else { wSqueethToMint = _depositedAmount.wmul(_strategyDebtAmount).wdiv( _strategyCollateralAmount.add(_strategyDebtAmount.wmul(feeAdjustment)) ); } uint256 fee = wSqueethToMint.wmul(feeAdjustment); return (wSqueethToMint, fee); } /** * @notice check if hedging based on time threshold is allowed * @return true if time hedging is allowed * @return auction trigger timestamp */ function _isTimeHedge() internal view returns (bool, uint256) { uint256 auctionTriggerTime = timeAtLastHedge.add(hedgeTimeThreshold); return (block.timestamp >= auctionTriggerTime, auctionTriggerTime); } /** * @notice check if hedging based on price threshold is allowed * @param _auctionTriggerTime timestamp where auction started * @return true if hedging is allowed */ function _isPriceHedge(uint256 _auctionTriggerTime) internal view returns (bool) { if (_auctionTriggerTime < timeAtLastHedge) return false; uint32 secondsToPriceHedgeTrigger = uint32(block.timestamp.sub(_auctionTriggerTime)); uint256 wSqueethEthPriceAtTriggerTime = IOracle(oracle).getHistoricalTwap( ethWSqueethPool, wPowerPerp, weth, secondsToPriceHedgeTrigger + hedgingTwapPeriod, secondsToPriceHedgeTrigger ); uint256 cachedRatio = wSqueethEthPriceAtTriggerTime.wdiv(priceAtLastHedge); uint256 priceThreshold = cachedRatio > 1e18 ? (cachedRatio).sub(1e18) : uint256(1e18).sub(cachedRatio); return priceThreshold >= hedgePriceThreshold; } /** * @notice calculate auction price based on auction direction, start time and wSqueeth price * @param _auctionTriggerTime timestamp where auction started * @param _wSqueethEthPrice WSqueeth/ETH price * @param _isSellingAuction auction type (true for selling, false for buying auction) * @return auction price */ function _getAuctionPrice( uint256 _auctionTriggerTime, uint256 _wSqueethEthPrice, bool _isSellingAuction ) internal view returns (uint256) { uint256 auctionCompletionRatio = block.timestamp.sub(_auctionTriggerTime) >= auctionTime ? 1e18 : (block.timestamp.sub(_auctionTriggerTime)).wdiv(auctionTime); uint256 priceMultiplier; if (_isSellingAuction) { priceMultiplier = maxPriceMultiplier.sub( auctionCompletionRatio.wmul(maxPriceMultiplier.sub(minPriceMultiplier)) ); } else { priceMultiplier = minPriceMultiplier.add( auctionCompletionRatio.wmul(maxPriceMultiplier.sub(minPriceMultiplier)) ); } return _wSqueethEthPrice.wmul(priceMultiplier); } /** * @notice check the direction of auction and the target amount of wSqueeth to hedge * @param _debt strategy debt * @param _ethDelta ETH delta (amount of ETH in strategy) * @param _wSqueethEthPrice WSqueeth/ETH price * @param _feeAdjustment the fee adjustment, the amount of ETH owed per wSqueeth minted * @return auction type(sell or buy) and auction initial target hedge in wSqueeth */ function _checkAuctionType( uint256 _debt, uint256 _ethDelta, uint256 _wSqueethEthPrice, uint256 _feeAdjustment ) internal view returns (bool, uint256) { uint256 wSqueethDelta = _debt.wmul(2e18).wmul(_wSqueethEthPrice); (uint256 targetHedge, bool isSellingAuction) = _getTargetHedgeAndAuctionType( wSqueethDelta, _ethDelta, _wSqueethEthPrice, _feeAdjustment ); require(targetHedge.wmul(_wSqueethEthPrice).wdiv(_ethDelta) > deltaHedgeThreshold, "strategy is delta neutral"); return (isSellingAuction, targetHedge); } /** * @dev calculate amount of strategy token to mint for depositor * @param _amount amount of ETH deposited * @param _strategyCollateralAmount amount of strategy collateral * @param _crabTotalSupply total supply of strategy token * @return amount of strategy token to mint */ function _calcSharesToMint( uint256 _amount, uint256 _strategyCollateralAmount, uint256 _crabTotalSupply ) internal pure returns (uint256) { uint256 depositorShare = _amount.wdiv(_strategyCollateralAmount.add(_amount)); if (_crabTotalSupply != 0) return _crabTotalSupply.wmul(depositorShare).wdiv(uint256(1e18).sub(depositorShare)); return _amount; } /** * @notice calculates the ownership proportion for strategy debt and collateral relative to a total amount of strategy tokens * @param _crabAmount strategy token amount * @param _totalSupply strategy total supply * @return ownership proportion of a strategy token amount relative to the total strategy tokens */ function _calcCrabRatio(uint256 _crabAmount, uint256 _totalSupply) internal pure returns (uint256) { return _crabAmount.wdiv(_totalSupply); } /** * @notice calculate ETH to withdraw from strategy given a ownership proportion * @param _crabRatio crab ratio * @param _strategyCollateralAmount amount of collateral in strategy * @return amount of ETH allowed to withdraw */ function _calcEthToWithdraw(uint256 _crabRatio, uint256 _strategyCollateralAmount) internal pure returns (uint256) { return _strategyCollateralAmount.wmul(_crabRatio); } /** * @notice determine target hedge and auction type (selling/buying auction) * @dev target hedge is the amount of WSqueeth the auction needs to sell or buy to be eth delta neutral * @param _wSqueethDelta WSqueeth delta * @param _ethDelta ETH delta * @param _wSqueethEthPrice WSqueeth/ETH price * @param _feeAdjustment the fee adjustment, the amount of ETH owed per wSqueeth minted * @return target hedge in wSqueeth * @return auction type: true if auction is selling WSqueeth, false if buying WSqueeth */ function _getTargetHedgeAndAuctionType( uint256 _wSqueethDelta, uint256 _ethDelta, uint256 _wSqueethEthPrice, uint256 _feeAdjustment ) internal pure returns (uint256, bool) { return (_wSqueethDelta > _ethDelta) ? ((_wSqueethDelta.sub(_ethDelta)).wdiv(_wSqueethEthPrice), false) : ((_ethDelta.sub(_wSqueethDelta)).wdiv(_wSqueethEthPrice.add(_feeAdjustment)), true); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma abicoder v2; import {VaultLib} from "../libs/VaultLib.sol"; interface IController { function ethQuoteCurrencyPool() external view returns (address); function feeRate() external view returns (uint256); function getFee( uint256 _vaultId, uint256 _wPowerPerpAmount, uint256 _collateralAmount ) external view returns (uint256); function quoteCurrency() external view returns (address); function vaults(uint256 _vaultId) external view returns (VaultLib.Vault memory); function shortPowerPerp() external view returns (address); function wPowerPerp() external view returns (address); function getExpectedNormalizationFactor() external view returns (uint256); function mintPowerPerpAmount( uint256 _vaultId, uint256 _powerPerpAmount, uint256 _uniTokenId ) external payable returns (uint256 vaultId, uint256 wPowerPerpAmount); function mintWPowerPerpAmount( uint256 _vaultId, uint256 _wPowerPerpAmount, uint256 _uniTokenId ) external payable returns (uint256 vaultId); /** * Deposit collateral into a vault */ function deposit(uint256 _vaultId) external payable; /** * Withdraw collateral from a vault. */ function withdraw(uint256 _vaultId, uint256 _amount) external payable; function burnWPowerPerpAmount( uint256 _vaultId, uint256 _wPowerPerpAmount, uint256 _withdrawAmount ) external; function burnOnPowerPerpAmount( uint256 _vaultId, uint256 _powerPerpAmount, uint256 _withdrawAmount ) external returns (uint256 wPowerPerpAmount); function liquidate(uint256 _vaultId, uint256 _maxDebtAmount) external returns (uint256); function updateOperator(uint256 _vaultId, address _operator) external; /** * External function to update the normalized factor as a way to pay funding. */ function applyFunding() external; function redeemShort(uint256 _vaultId) external; function reduceDebtShutdown(uint256 _vaultId) external; function isShutDown() external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWPowerPerp is IERC20 { function mint(address _account, uint256 _amount) external; function burn(address _account, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; interface IOracle { function getHistoricalTwap( address _pool, address _base, address _quote, uint32 _period, uint32 _periodToHistoricPrice ) external view returns (uint256); function getTwap( address _pool, address _base, address _quote, uint32 _period, bool _checkPeriod ) external view returns (uint256); function getMaxPeriod(address _pool) external view returns (uint32); function getTimeWeightedAverageTickSafe(address _pool, uint32 _period) external view returns (int24 timeWeightedAverageTick); } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH9 is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: GPL-3.0-only pragma solidity =0.7.6; pragma abicoder v2; // interface import {IController} from "../../interfaces/IController.sol"; import {IWPowerPerp} from "../../interfaces/IWPowerPerp.sol"; // contract import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // lib import {Address} from "@openzeppelin/contracts/utils/Address.sol"; // StrategyMath licensed under AGPL-3.0-only import {StrategyMath} from "./StrategyMath.sol"; import {VaultLib} from "../../libs/VaultLib.sol"; /** * @dev StrategyBase contract * @notice base contract for PowerToken strategy * @author opyn team */ contract StrategyBase is ERC20 { using StrategyMath for uint256; using Address for address payable; /// @dev power token controller IController public powerTokenController; /// @dev WETH token address public immutable weth; address public immutable wPowerPerp; /// @dev power token strategy vault ID uint256 public immutable vaultId; /** * @notice constructor for StrategyBase * @dev this will open a vault in the power token contract and store the vault ID * @param _powerTokenController power token controller address * @param _weth weth token address * @param _name token name for strategy ERC20 token * @param _symbol token symbol for strategy ERC20 token */ constructor(address _powerTokenController, address _weth, string memory _name, string memory _symbol) ERC20(_name, _symbol) { require(_powerTokenController != address(0), "invalid controller address"); require(_weth != address(0), "invalid weth address"); weth = _weth; powerTokenController = IController(_powerTokenController); wPowerPerp = address(powerTokenController.wPowerPerp()); vaultId = powerTokenController.mintWPowerPerpAmount(0, 0, 0); } /** * @notice get power token strategy vault ID * @return vault ID */ function getStrategyVaultId() external view returns (uint256) { return vaultId; } /** * @notice get the vault composition of the strategy * @return operator * @return nft collateral id * @return collateral amount * @return short amount */ function getVaultDetails() external view returns (address, uint256, uint256, uint256) { return _getVaultDetails(); } /** * @notice mint WPowerPerp and deposit collateral * @dev this function will not send WPowerPerp to msg.sender if _keepWSqueeth == true * @param _to receiver address * @param _wAmount amount of WPowerPerp to mint * @param _collateral amount of collateral to deposit * @param _keepWsqueeth keep minted wSqueeth in this contract if it is set to true */ function _mintWPowerPerp( address _to, uint256 _wAmount, uint256 _collateral, bool _keepWsqueeth ) internal { powerTokenController.mintWPowerPerpAmount{value: _collateral}(vaultId, _wAmount, 0); if (!_keepWsqueeth) { IWPowerPerp(wPowerPerp).transfer(_to, _wAmount); } } /** * @notice burn WPowerPerp and withdraw collateral * @dev this function will not take WPowerPerp from msg.sender if _isOwnedWSqueeth == true * @param _from WPowerPerp holder address * @param _amount amount of wPowerPerp to burn * @param _collateralToWithdraw amount of collateral to withdraw * @param _isOwnedWSqueeth transfer WPowerPerp from holder if it is set to false */ function _burnWPowerPerp( address _from, uint256 _amount, uint256 _collateralToWithdraw, bool _isOwnedWSqueeth ) internal { if (!_isOwnedWSqueeth) { IWPowerPerp(wPowerPerp).transferFrom(_from, address(this), _amount); } powerTokenController.burnWPowerPerpAmount(vaultId, _amount, _collateralToWithdraw); } /** * @notice mint strategy token * @param _to recepient address * @param _amount token amount */ function _mintStrategyToken(address _to, uint256 _amount) internal { _mint(_to, _amount); } /** * @notice get strategy debt amount for a specific strategy token amount * @param _strategyAmount strategy amount * @return debt amount */ function _getDebtFromStrategyAmount(uint256 _strategyAmount) internal view returns (uint256) { (, , ,uint256 strategyDebt) = _getVaultDetails(); return strategyDebt.wmul(_strategyAmount).wdiv(totalSupply()); } /** * @notice get the vault composition of the strategy * @return operator * @return nft collateral id * @return collateral amount * @return short amount */ function _getVaultDetails() internal view returns (address, uint256, uint256, uint256) { VaultLib.Vault memory strategyVault = powerTokenController.vaults(vaultId); return (strategyVault.operator, strategyVault.NftCollateralId, strategyVault.collateralAmount, strategyVault.shortAmount); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; // interface import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; // lib import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; import '@uniswap/v3-periphery/contracts/libraries/Path.sol'; import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol'; import '@uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/libraries/SafeCast.sol'; contract StrategyFlashSwap is IUniswapV3SwapCallback { using Path for bytes; using SafeCast for uint256; using LowGasSafeMath for uint256; using LowGasSafeMath for int256; /// @dev Uniswap factory address address public immutable factory; struct SwapCallbackData { bytes path; address caller; uint8 callSource; bytes callData; } /** * @dev constructor * @param _factory uniswap factory address */ constructor( address _factory ) { require(_factory != address(0), "invalid factory address"); factory = _factory; } /** * @notice uniswap swap callback function for flashes * @param amount0Delta amount of token0 * @param amount1Delta amount of token1 * @param _data callback data encoded as SwapCallbackData struct */ function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata _data ) external override { require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData)); (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool(); //ensure that callback comes from uniswap pool CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee); //determine the amount that needs to be repaid as part of the flashswap uint256 amountToPay = amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); //calls the strategy function that uses the proceeds from flash swap and executes logic to have an amount of token to repay the flash swap _strategyFlash(data.caller, tokenIn, tokenOut, fee, amountToPay, data.callData, data.callSource); } /** * @notice execute an exact-in flash swap (specify an exact amount to pay) * @param _tokenIn token address to sell * @param _tokenOut token address to receive * @param _fee pool fee * @param _amountIn amount to sell * @param _amountOutMinimum minimum amount to receive * @param _callSource function call source * @param _data arbitrary data assigned with the call */ function _exactInFlashSwap(address _tokenIn, address _tokenOut, uint24 _fee, uint256 _amountIn, uint256 _amountOutMinimum, uint8 _callSource, bytes memory _data) internal { //calls internal uniswap swap function that will trigger a callback for the flash swap uint256 amountOut = _exactInputInternal( _amountIn, address(this), uint160(0), SwapCallbackData({path: abi.encodePacked(_tokenIn, _fee, _tokenOut), caller: msg.sender, callSource: _callSource, callData: _data}) ); //slippage limit check require(amountOut >= _amountOutMinimum, "amount out less than min"); } /** * @notice execute an exact-out flash swap (specify an exact amount to receive) * @param _tokenIn token address to sell * @param _tokenOut token address to receive * @param _fee pool fee * @param _amountOut exact amount to receive * @param _amountInMaximum maximum amount to sell * @param _callSource function call source * @param _data arbitrary data assigned with the call */ function _exactOutFlashSwap(address _tokenIn, address _tokenOut, uint24 _fee, uint256 _amountOut, uint256 _amountInMaximum, uint8 _callSource, bytes memory _data) internal { //calls internal uniswap swap function that will trigger a callback for the flash swap uint256 amountIn = _exactOutputInternal( _amountOut, address(this), uint160(0), SwapCallbackData({path: abi.encodePacked(_tokenOut, _fee, _tokenIn), caller: msg.sender, callSource: _callSource, callData: _data}) ); //slippage limit check require(amountIn <= _amountInMaximum, "amount in greater than max"); } /** * @notice function to be called by uniswap callback. * @dev this function should be overridden by the child contract * param _caller initial strategy function caller * param _tokenIn token address sold * param _tokenOut token address bought * param _fee pool fee * param _amountToPay amount to pay for the pool second token * param _callData arbitrary data assigned with the flashswap call * param _callSource function call source */ function _strategyFlash(address /*_caller*/, address /*_tokenIn*/, address /*_tokenOut*/, uint24 /*_fee*/, uint256 /*_amountToPay*/, bytes memory _callData, uint8 _callSource) internal virtual {} /** * @notice internal function for exact-in swap on uniswap (specify exact amount to pay) * @param _amountIn amount of token to pay * @param _recipient recipient for receive * @param _sqrtPriceLimitX96 price limit * @return amount of token bought (amountOut) */ function _exactInputInternal( uint256 _amountIn, address _recipient, uint160 _sqrtPriceLimitX96, SwapCallbackData memory data ) private returns (uint256) { (address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool(); //uniswap token0 has a lower address than token1 //if tokenIn<tokenOut, we are selling an exact amount of token0 in exchange for token1 //zeroForOne determines which token is being sold and which is being bought bool zeroForOne = tokenIn < tokenOut; //swap on uniswap, including data to trigger call back for flashswap (int256 amount0, int256 amount1) = _getPool(tokenIn, tokenOut, fee).swap( _recipient, zeroForOne, _amountIn.toInt256(), _sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : _sqrtPriceLimitX96, abi.encode(data) ); //determine the amountOut based on which token has a lower address return uint256(-(zeroForOne ? amount1 : amount0)); } /** * @notice internal function for exact-out swap on uniswap (specify exact amount to receive) * @param _amountOut amount of token to receive * @param _recipient recipient for receive * @param _sqrtPriceLimitX96 price limit * @return amount of token sold (amountIn) */ function _exactOutputInternal( uint256 _amountOut, address _recipient, uint160 _sqrtPriceLimitX96, SwapCallbackData memory data ) private returns (uint256) { (address tokenOut, address tokenIn, uint24 fee) = data.path.decodeFirstPool(); //uniswap token0 has a lower address than token1 //if tokenIn<tokenOut, we are buying an exact amount of token1 in exchange for token0 //zeroForOne determines which token is being sold and which is being bought bool zeroForOne = tokenIn < tokenOut; //swap on uniswap, including data to trigger call back for flashswap (int256 amount0Delta, int256 amount1Delta) = _getPool(tokenIn, tokenOut, fee).swap( _recipient, zeroForOne, -_amountOut.toInt256(), _sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : _sqrtPriceLimitX96, abi.encode(data) ); //determine the amountIn and amountOut based on which token has a lower address (uint256 amountIn, uint256 amountOutReceived) = zeroForOne ? (uint256(amount0Delta), uint256(-amount1Delta)) : (uint256(amount1Delta), uint256(-amount0Delta)); // it's technically possible to not receive the full output amount, // so if no price limit has been specified, require this possibility away if (_sqrtPriceLimitX96 == 0) require(amountOutReceived == _amountOut); return amountIn; } /** * @notice returns the uniswap pool for the given token pair and fee * @dev the pool contract may or may not exist * @param tokenA address of first token * @param tokenB address of second token * @param fee fee tier for pool */ function _getPool( address tokenA, address tokenB, uint24 fee ) private view returns (IUniswapV3Pool) { return IUniswapV3Pool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: AGPL-3.0-only /// 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/>. pragma solidity >0.4.13; /** * @notice Copied from https://github.com/dapphub/ds-math/blob/e70a364787804c1ded9801ed6c27b440a86ebd32/src/math.sol * @dev change contract to library, added div() function */ library StrategyMath { 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"); } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; //rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; //interface import {IOracle} from "../interfaces/IOracle.sol"; //lib import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; library Power2Base { using SafeMath for uint256; uint32 private constant TWAP_PERIOD = 420 seconds; uint256 private constant INDEX_SCALE = 1e4; uint256 private constant ONE = 1e18; uint256 private constant ONE_ONE = 1e36; /** * @notice return the scaled down index of the power perp in USD, scaled by 18 decimals * @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool) * @param _oracle oracle address * @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency * @param _weth weth address * @param _quoteCurrency quoteCurrency address * @return for squeeth, return ethPrice^2 */ function _getIndex( uint32 _period, address _oracle, address _ethQuoteCurrencyPool, address _weth, address _quoteCurrency ) internal view returns (uint256) { uint256 ethQuoteCurrencyPrice = _getScaledTwap( _oracle, _ethQuoteCurrencyPool, _weth, _quoteCurrency, _period, false ); return ethQuoteCurrencyPrice.mul(ethQuoteCurrencyPrice).div(ONE); } /** * @notice return the unscaled index of the power perp in USD, scaled by 18 decimals * @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool) * @param _oracle oracle address * @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency * @param _weth weth address * @param _quoteCurrency quoteCurrency address * @return for squeeth, return ethPrice^2 */ function _getUnscaledIndex( uint32 _period, address _oracle, address _ethQuoteCurrencyPool, address _weth, address _quoteCurrency ) internal view returns (uint256) { uint256 ethQuoteCurrencyPrice = _getTwap(_oracle, _ethQuoteCurrencyPool, _weth, _quoteCurrency, _period, false); return ethQuoteCurrencyPrice.mul(ethQuoteCurrencyPrice).div(ONE); } /** * @notice return the mark price of power perp in quoteCurrency, scaled by 18 decimals * @param _period period of time for the twap in seconds (cannot be longer than maximum period for the pool) * @param _oracle oracle address * @param _wSqueethEthPool uniswap v3 pool for wSqueeth / weth * @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency * @param _weth weth address * @param _quoteCurrency quoteCurrency address * @param _wSqueeth wSqueeth address * @param _normalizationFactor current normalization factor * @return for squeeth, return ethPrice * squeethPriceInEth */ function _getDenormalizedMark( uint32 _period, address _oracle, address _wSqueethEthPool, address _ethQuoteCurrencyPool, address _weth, address _quoteCurrency, address _wSqueeth, uint256 _normalizationFactor ) internal view returns (uint256) { uint256 ethQuoteCurrencyPrice = _getScaledTwap( _oracle, _ethQuoteCurrencyPool, _weth, _quoteCurrency, _period, false ); uint256 wsqueethEthPrice = _getTwap(_oracle, _wSqueethEthPool, _wSqueeth, _weth, _period, false); return wsqueethEthPrice.mul(ethQuoteCurrencyPrice).div(_normalizationFactor); } /** * @notice get the fair collateral value for a _debtAmount of wSqueeth * @dev the actual amount liquidator can get should have a 10% bonus on top of this value. * @param _debtAmount wSqueeth amount paid by liquidator * @param _oracle oracle address * @param _wSqueethEthPool uniswap v3 pool for wSqueeth / weth * @param _wSqueeth wSqueeth address * @param _weth weth address * @return returns value of debt in ETH */ function _getDebtValueInEth( uint256 _debtAmount, address _oracle, address _wSqueethEthPool, address _wSqueeth, address _weth ) internal view returns (uint256) { uint256 wSqueethPrice = _getTwap(_oracle, _wSqueethEthPool, _wSqueeth, _weth, TWAP_PERIOD, false); return _debtAmount.mul(wSqueethPrice).div(ONE); } /** * @notice request twap from our oracle, scaled down by INDEX_SCALE * @param _oracle oracle address * @param _pool uniswap v3 pool address * @param _base base currency. to get eth/usd price, eth is base token * @param _quote quote currency. to get eth/usd price, usd is the quote currency * @param _period number of seconds in the past to start calculating time-weighted average. * @param _checkPeriod check that period is not longer than maximum period for the pool to prevent reverts * @return twap price scaled down by INDEX_SCALE */ function _getScaledTwap( address _oracle, address _pool, address _base, address _quote, uint32 _period, bool _checkPeriod ) internal view returns (uint256) { uint256 twap = _getTwap(_oracle, _pool, _base, _quote, _period, _checkPeriod); return twap.div(INDEX_SCALE); } /** * @notice request twap from our oracle * @dev this will revert if period is > max period for the pool * @param _oracle oracle address * @param _pool uniswap v3 pool address * @param _base base currency. to get eth/quoteCurrency price, eth is base token * @param _quote quote currency. to get eth/quoteCurrency price, quoteCurrency is the quote currency * @param _period number of seconds in the past to start calculating time-weighted average * @param _checkPeriod check that period is not longer than maximum period for the pool to prevent reverts * @return human readable price. scaled by 1e18 */ function _getTwap( address _oracle, address _pool, address _base, address _quote, uint32 _period, bool _checkPeriod ) internal view returns (uint256) { // period reaching this point should be check, otherwise might revert return IOracle(_oracle).getTwap(_pool, _base, _quote, _period, _checkPeriod); } /** * @notice get the index value of wsqueeth in wei, used when system settles * @dev the index of squeeth is ethPrice^2, so each squeeth will need to pay out {ethPrice} eth * @param _wsqueethAmount amount of wsqueeth used in settlement * @param _indexPriceForSettlement index price for settlement * @param _normalizationFactor current normalization factor * @return amount in wei that should be paid to the token holder */ function _getLongSettlementValue( uint256 _wsqueethAmount, uint256 _indexPriceForSettlement, uint256 _normalizationFactor ) internal pure returns (uint256) { return _wsqueethAmount.mul(_normalizationFactor).mul(_indexPriceForSettlement).div(ONE_ONE); } } //SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; //interface import {INonfungiblePositionManager} from "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; //lib import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {TickMathExternal} from "./TickMathExternal.sol"; import {SqrtPriceMathPartial} from "./SqrtPriceMathPartial.sol"; import {Uint256Casting} from "./Uint256Casting.sol"; /** * Error code: * V1: Vault already had nft * V2: Vault has no NFT */ library VaultLib { using SafeMath for uint256; using Uint256Casting for uint256; uint256 constant ONE_ONE = 1e36; // the collateralization ratio (CR) is checked with the numerator and denominator separately // a user is safe if - collateral value >= (COLLAT_RATIO_NUMER/COLLAT_RATIO_DENOM)* debt value uint256 public constant CR_NUMERATOR = 3; uint256 public constant CR_DENOMINATOR = 2; struct Vault { // the address that can update the vault address operator; // uniswap position token id deposited into the vault as collateral // 2^32 is 4,294,967,296, which means the vault structure will work with up to 4 billion positions uint32 NftCollateralId; // amount of eth (wei) used in the vault as collateral // 2^96 / 1e18 = 79,228,162,514, which means a vault can store up to 79 billion eth // when we need to do calculations, we always cast this number to uint256 to avoid overflow uint96 collateralAmount; // amount of wPowerPerp minted from the vault uint128 shortAmount; } /** * @notice add eth collateral to a vault * @param _vault in-memory vault * @param _amount amount of eth to add */ function addEthCollateral(Vault memory _vault, uint256 _amount) internal pure { _vault.collateralAmount = uint256(_vault.collateralAmount).add(_amount).toUint96(); } /** * @notice add uniswap position token collateral to a vault * @param _vault in-memory vault * @param _tokenId uniswap position token id */ function addUniNftCollateral(Vault memory _vault, uint256 _tokenId) internal pure { require(_vault.NftCollateralId == 0, "V1"); require(_tokenId != 0, "C23"); _vault.NftCollateralId = _tokenId.toUint32(); } /** * @notice remove eth collateral from a vault * @param _vault in-memory vault * @param _amount amount of eth to remove */ function removeEthCollateral(Vault memory _vault, uint256 _amount) internal pure { _vault.collateralAmount = uint256(_vault.collateralAmount).sub(_amount).toUint96(); } /** * @notice remove uniswap position token collateral from a vault * @param _vault in-memory vault */ function removeUniNftCollateral(Vault memory _vault) internal pure { require(_vault.NftCollateralId != 0, "V2"); _vault.NftCollateralId = 0; } /** * @notice add debt to vault * @param _vault in-memory vault * @param _amount amount of debt to add */ function addShort(Vault memory _vault, uint256 _amount) internal pure { _vault.shortAmount = uint256(_vault.shortAmount).add(_amount).toUint128(); } /** * @notice remove debt from vault * @param _vault in-memory vault * @param _amount amount of debt to remove */ function removeShort(Vault memory _vault, uint256 _amount) internal pure { _vault.shortAmount = uint256(_vault.shortAmount).sub(_amount).toUint128(); } /** * @notice check if a vault is properly collateralized * @param _vault the vault we want to check * @param _positionManager address of the uniswap position manager * @param _normalizationFactor current _normalizationFactor * @param _ethQuoteCurrencyPrice current eth price scaled by 1e18 * @param _minCollateral minimum collateral that needs to be in a vault * @param _wsqueethPoolTick current price tick for wsqueeth pool * @param _isWethToken0 whether weth is token0 in the wsqueeth pool * @return true if the vault is sufficiently collateralized * @return true if the vault is considered as a dust vault */ function getVaultStatus( Vault memory _vault, address _positionManager, uint256 _normalizationFactor, uint256 _ethQuoteCurrencyPrice, uint256 _minCollateral, int24 _wsqueethPoolTick, bool _isWethToken0 ) internal view returns (bool, bool) { if (_vault.shortAmount == 0) return (true, false); uint256 debtValueInETH = uint256(_vault.shortAmount).mul(_normalizationFactor).mul(_ethQuoteCurrencyPrice).div( ONE_ONE ); uint256 totalCollateral = _getEffectiveCollateral( _vault, _positionManager, _normalizationFactor, _ethQuoteCurrencyPrice, _wsqueethPoolTick, _isWethToken0 ); bool isDust = totalCollateral < _minCollateral; bool isAboveWater = totalCollateral.mul(CR_DENOMINATOR) >= debtValueInETH.mul(CR_NUMERATOR); return (isAboveWater, isDust); } /** * @notice get the total effective collateral of a vault, which is: * collateral amount + uniswap position token equivelent amount in eth * @param _vault the vault we want to check * @param _positionManager address of the uniswap position manager * @param _normalizationFactor current _normalizationFactor * @param _ethQuoteCurrencyPrice current eth price scaled by 1e18 * @param _wsqueethPoolTick current price tick for wsqueeth pool * @param _isWethToken0 whether weth is token0 in the wsqueeth pool * @return the total worth of collateral in the vault */ function _getEffectiveCollateral( Vault memory _vault, address _positionManager, uint256 _normalizationFactor, uint256 _ethQuoteCurrencyPrice, int24 _wsqueethPoolTick, bool _isWethToken0 ) internal view returns (uint256) { if (_vault.NftCollateralId == 0) return _vault.collateralAmount; // the user has deposited uniswap position token as collateral, see how much eth / wSqueeth the uniswap position token has (uint256 nftEthAmount, uint256 nftWsqueethAmount) = _getUniPositionBalances( _positionManager, _vault.NftCollateralId, _wsqueethPoolTick, _isWethToken0 ); // convert squeeth amount from uniswap position token as equivalent amount of collateral uint256 wSqueethIndexValueInEth = nftWsqueethAmount.mul(_normalizationFactor).mul(_ethQuoteCurrencyPrice).div( ONE_ONE ); // add eth value from uniswap position token as collateral return nftEthAmount.add(wSqueethIndexValueInEth).add(_vault.collateralAmount); } /** * @notice determine how much eth / wPowerPerp the uniswap position contains * @param _positionManager address of the uniswap position manager * @param _tokenId uniswap position token id * @param _wPowerPerpPoolTick current price tick * @param _isWethToken0 whether weth is token0 in the pool * @return ethAmount the eth amount this LP token contains * @return wPowerPerpAmount the wPowerPerp amount this LP token contains */ function _getUniPositionBalances( address _positionManager, uint256 _tokenId, int24 _wPowerPerpPoolTick, bool _isWethToken0 ) internal view returns (uint256 ethAmount, uint256 wPowerPerpAmount) { ( int24 tickLower, int24 tickUpper, uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) = _getUniswapPositionInfo(_positionManager, _tokenId); (uint256 amount0, uint256 amount1) = _getToken0Token1Balances( tickLower, tickUpper, _wPowerPerpPoolTick, liquidity ); return _isWethToken0 ? (amount0 + tokensOwed0, amount1 + tokensOwed1) : (amount1 + tokensOwed1, amount0 + tokensOwed0); } /** * @notice get uniswap position token info * @param _positionManager address of the uniswap position position manager * @param _tokenId uniswap position token id * @return tickLower lower tick of the position * @return tickUpper upper tick of the position * @return liquidity raw liquidity amount of the position * @return tokensOwed0 amount of token 0 can be collected as fee * @return tokensOwed1 amount of token 1 can be collected as fee */ function _getUniswapPositionInfo(address _positionManager, uint256 _tokenId) internal view returns ( int24, int24, uint128, uint128, uint128 ) { INonfungiblePositionManager positionManager = INonfungiblePositionManager(_positionManager); ( , , , , , int24 tickLower, int24 tickUpper, uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1 ) = positionManager.positions(_tokenId); return (tickLower, tickUpper, liquidity, tokensOwed0, tokensOwed1); } /** * @notice get balances of token0 / token1 in a uniswap position * @dev knowing liquidity, tick range, and current tick gives balances * @param _tickLower address of the uniswap position manager * @param _tickUpper uniswap position token id * @param _tick current price tick used for calculation * @return amount0 the amount of token0 in the uniswap position token * @return amount1 the amount of token1 in the uniswap position token */ function _getToken0Token1Balances( int24 _tickLower, int24 _tickUpper, int24 _tick, uint128 _liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { // get the current price and tick from wPowerPerp pool uint160 sqrtPriceX96 = TickMathExternal.getSqrtRatioAtTick(_tick); if (_tick < _tickLower) { amount0 = SqrtPriceMathPartial.getAmount0Delta( TickMathExternal.getSqrtRatioAtTick(_tickLower), TickMathExternal.getSqrtRatioAtTick(_tickUpper), _liquidity, true ); } else if (_tick < _tickUpper) { amount0 = SqrtPriceMathPartial.getAmount0Delta( sqrtPriceX96, TickMathExternal.getSqrtRatioAtTick(_tickUpper), _liquidity, true ); amount1 = SqrtPriceMathPartial.getAmount1Delta( TickMathExternal.getSqrtRatioAtTick(_tickLower), sqrtPriceX96, _liquidity, true ); } else { amount1 = SqrtPriceMathPartial.getAmount1Delta( TickMathExternal.getSqrtRatioAtTick(_tickLower), TickMathExternal.getSqrtRatioAtTick(_tickUpper), _liquidity, true ); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryPayments.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryPayments, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMathExternal { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) public pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), "T"); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) external pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R"); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@uniswap/v3-core/contracts/libraries/FullMath.sol"; import "@uniswap/v3-core/contracts/libraries/UnsafeMath.sol"; import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol"; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Exposes two functions from @uniswap/v3-core SqrtPriceMath /// that use square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMathPartial { /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) external pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) external pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } } //SPDX-License-Identifier: MIT pragma solidity =0.7.6; library Uint256Casting { /** * @notice cast a uint256 to a uint128, revert on overflow * @param y the uint256 to be downcasted * @return z the downcasted integer, now type uint128 */ function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y, "OF128"); } /** * @notice cast a uint256 to a uint96, revert on overflow * @param y the uint256 to be downcasted * @return z the downcasted integer, now type uint96 */ function toUint96(uint256 y) internal pure returns (uint96 z) { require((z = uint96(y)) == y, "OF96"); } /** * @notice cast a uint256 to a uint32, revert on overflow * @param y the uint256 to be downcasted * @return z the downcasted integer, now type uint32 */ function toUint32(uint256 y) internal pure returns (uint32 z) { require((z = uint32(y)) == y, "OF32"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../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.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.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) { // 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 = -denominator & 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); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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_) { _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 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.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Returns the number of pools in the path /// @param path The encoded swap path /// @return The number of pools in the path function numPools(bytes memory path) internal pure returns (uint256) { // Ignore the first token address. From then on every fee and token offset indicates a pool. return ((path.length - ADDR_SIZE) / NEXT_OFFSET); } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import './PoolAddress.sol'; /// @notice Provides validation for callbacks from Uniswap V3 Pools library CallbackValidation { /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The V3 pool contract address function verifyCallback( address factory, address tokenA, address tokenB, uint24 fee ) internal view returns (IUniswapV3Pool pool) { return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param poolKey The identifying key of the V3 pool /// @return pool The V3 pool contract address function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey) internal view returns (IUniswapV3Pool pool) { pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey)); require(msg.sender == address(pool)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } }
@dev power token controller @dev WETH token @dev power token strategy vault ID* @notice constructor for StrategyBase @dev this will open a vault in the power token contract and store the vault ID @param _powerTokenController power token controller address @param _weth weth token address @param _name token name for strategy ERC20 token @param _symbol token symbol for strategy ERC20 token/
constructor(address _powerTokenController, address _weth, string memory _name, string memory _symbol) ERC20(_name, _symbol) { require(_powerTokenController != address(0), "invalid controller address"); require(_weth != address(0), "invalid weth address"); weth = _weth; powerTokenController = IController(_powerTokenController); wPowerPerp = address(powerTokenController.wPowerPerp()); vaultId = powerTokenController.mintWPowerPerpAmount(0, 0, 0); }
1,220,138
[ 1, 12238, 1147, 2596, 225, 678, 1584, 44, 1147, 225, 7212, 1147, 6252, 9229, 1599, 225, 3885, 364, 19736, 2171, 225, 333, 903, 1696, 279, 9229, 316, 326, 7212, 1147, 6835, 471, 1707, 326, 9229, 1599, 225, 389, 12238, 1345, 2933, 7212, 1147, 2596, 1758, 225, 389, 91, 546, 341, 546, 1147, 1758, 225, 389, 529, 1147, 508, 364, 6252, 4232, 39, 3462, 1147, 225, 389, 7175, 1147, 3273, 364, 6252, 4232, 39, 3462, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 12, 2867, 389, 12238, 1345, 2933, 16, 1758, 389, 91, 546, 16, 533, 3778, 389, 529, 16, 533, 3778, 389, 7175, 13, 4232, 39, 3462, 24899, 529, 16, 389, 7175, 13, 288, 203, 3639, 2583, 24899, 12238, 1345, 2933, 480, 1758, 12, 20, 3631, 315, 5387, 2596, 1758, 8863, 203, 3639, 2583, 24899, 91, 546, 480, 1758, 12, 20, 3631, 315, 5387, 341, 546, 1758, 8863, 203, 203, 3639, 341, 546, 273, 389, 91, 546, 31, 203, 3639, 7212, 1345, 2933, 273, 467, 2933, 24899, 12238, 1345, 2933, 1769, 203, 3639, 341, 13788, 2173, 84, 273, 1758, 12, 12238, 1345, 2933, 18, 91, 13788, 2173, 84, 10663, 203, 3639, 9229, 548, 273, 7212, 1345, 2933, 18, 81, 474, 59, 13788, 2173, 84, 6275, 12, 20, 16, 374, 16, 374, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.2; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/DataStore.sol"; contract TestDataStore { function testInitialSetup() public { DataStore ds = DataStore(DeployedAddresses.DataStore()); Assert.equal(uint(ds.GetMapCount()), uint(0), "MapCount should be 0 at start."); } function testAddNewData() public { // DataStore ds = DataStore(DeployedAddresses.DataStore()); // on deployed DataStore contract DataStore ds = new DataStore(); //on new DataStore contract Assert.equal(ds.AddNewData(111, "Name1", "secret1"), true, "AddNewData should create a new Data in MapData"); Assert.equal(uint(ds.GetMapCount()), uint(1), "After adding new Data, MapCount should increase."); // Assert.NotNull(ds.GetDataByNumber(111), "Added data should be in the DataMap"); } }
DataStore ds = DataStore(DeployedAddresses.DataStore()); on deployed DataStore contract Assert.NotNull(ds.GetDataByNumber(111), "Added data should be in the DataMap");
function testAddNewData() public { Assert.equal(ds.AddNewData(111, "Name1", "secret1"), true, "AddNewData should create a new Data in MapData"); Assert.equal(uint(ds.GetMapCount()), uint(1), "After adding new Data, MapCount should increase."); }
12,686,854
[ 1, 24977, 3780, 273, 22961, 12, 31954, 7148, 18, 24977, 10663, 282, 603, 19357, 22961, 6835, 5452, 18, 5962, 12, 2377, 18, 967, 751, 858, 1854, 12, 20227, 3631, 315, 8602, 501, 1410, 506, 316, 326, 1910, 863, 8863, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 1842, 986, 1908, 751, 1435, 1071, 288, 203, 203, 565, 5452, 18, 9729, 12, 2377, 18, 986, 1908, 751, 12, 20227, 16, 315, 461, 21, 3113, 315, 5875, 21, 6, 3631, 638, 16, 315, 986, 1908, 751, 1410, 752, 279, 394, 1910, 316, 1635, 751, 8863, 203, 565, 5452, 18, 9729, 12, 11890, 12, 2377, 18, 967, 863, 1380, 1435, 3631, 2254, 12, 21, 3631, 315, 4436, 6534, 394, 1910, 16, 1635, 1380, 1410, 10929, 1199, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0xf0E82Ed35b0ECeC7a7a3D0e8D241Dd711b030485/sources/project:/contracts/SaleExchangeRate.sol
@notice Set price and its decimals of the secutity token in USD @param _priceInUSD price of Security in USD (price multiplied by 10**_priceDecimals) @param _priceDecimals decimals for price in USD
function setPrice( uint256 _priceInUSD, uint256 _priceDecimals ) external ownerOrSuperAdmin { baseSecurityToUSDPrice = _priceInUSD; priceDecimals = _priceDecimals; }
3,245,433
[ 1, 694, 6205, 471, 2097, 15105, 434, 326, 1428, 322, 560, 1147, 316, 587, 9903, 225, 389, 8694, 382, 3378, 40, 6205, 434, 6036, 316, 587, 9903, 261, 8694, 27789, 635, 1728, 67, 8694, 31809, 13, 225, 389, 8694, 31809, 15105, 364, 6205, 316, 587, 9903, 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, 444, 5147, 12, 203, 3639, 2254, 5034, 389, 8694, 382, 3378, 40, 16, 203, 3639, 2254, 5034, 389, 8694, 31809, 203, 565, 262, 3903, 3410, 1162, 8051, 4446, 288, 203, 3639, 1026, 4368, 774, 3378, 40, 5147, 273, 389, 8694, 382, 3378, 40, 31, 203, 3639, 6205, 31809, 273, 389, 8694, 31809, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin-upgradeable/contracts/access/OwnableUpgradeable.sol'; import '@openzeppelin-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol'; import '@openzeppelin-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol'; import '@openzeppelin-upgradeable/contracts/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol'; import '@openzeppelin-upgradeable/contracts/utils/AddressUpgradeable.sol'; import '@openzeppelin-upgradeable/contracts/utils/CountersUpgradeable.sol'; import '@openzeppelin-upgradeable/contracts/utils/math/SafeMathUpgradeable.sol'; import '@openzeppelin-upgradeable/contracts/utils/StringsUpgradeable.sol'; import '@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol'; import '../interfaces/IOpenSeaCompatible.sol'; import '../interfaces/IRarePizzas.sol'; import '../interfaces/IRarePizzasAdmin.sol'; import '../interfaces/IRarePizzasBox.sol'; import '../interfaces/IOrderAPIConsumer.sol'; contract RarePizzas is OwnableUpgradeable, ReentrancyGuardUpgradeable, ERC721EnumerableUpgradeable, IRarePizzas, IRarePizzasAdmin, IOrderAPICallback, IOpenSeaCompatible { using AddressUpgradeable for address; using StringsUpgradeable for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; using SafeMathUpgradeable for uint256; event SaleActive(bool state); event RarePizzasBoxContractUpdated(address previous, address current); event OrderAPIClientUpdated(address previous, address current); event InternalArtworkAssigned(uint256 tokenId, bytes32 artworkURI); // V1 Variables (do not modify this section when upgrading) bool public saleIsActive; bytes constant sha256MultiHash = hex'1220'; bytes constant ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; string public constant _uriBase = 'ipfs://'; string private _contractURI; // Other contracts this contract interacts with IOrderAPIConsumer internal _orderAPIClient; IRarePizzasBox internal _rarePizzasBoxContract; // A collection of Box Token Id's that have been redeemed mapping(uint256 => address) internal _redeemedBoxTokenAddress; // A collection of all of the pizza artwork IPFS hashes mapping(uint256 => bytes32) internal _tokenPizzaArtworkURIs; // A collection of render jobs associated with the requestor mapping(bytes32 => address) internal _renderRequests; // A collection of render jobs associated with the box token id mapping(bytes32 => uint256) internal _renderTokenIds; // END V1 Variables function initialize(address rarePizzasBoxContract) public initializer { __Ownable_init(); __ReentrancyGuard_init(); __ERC721_init('Rare Pizzas', 'PIZZA'); saleIsActive = false; if (rarePizzasBoxContract != address(0)) { _rarePizzasBoxContract = IRarePizzasBox(rarePizzasBoxContract); } _contractURI = 'https://raw.githubusercontent.com/PizzaDAO/pizza-smartcontract/master/data/opensea_pizza_metadata.mainnet.json'; } // IOpenSeaCompatible function contractURI() public view virtual override returns (string memory) { return _contractURI; } function setContractURI(string memory URI) external virtual override onlyOwner { _contractURI = URI; } // IRarePizzas function isRedeemed(uint256 boxTokenId) public view override returns (bool) { return _redeemedBoxTokenAddress[boxTokenId] != address(0); } function addressOfRedeemer(uint256 boxTokenId) public view override returns (address) { return _redeemedBoxTokenAddress[boxTokenId]; } function redeemRarePizzasBox(uint256 boxTokenId, uint256 recipeId) public override nonReentrant { require(saleIsActive == true, 'redeem not active'); //require(_msgSender() == _rarePizzasBoxContract.ownerOf(boxTokenId), 'caller must own box'); _redeemRarePizzasBox(_msgSender(), boxTokenId, recipeId); } // IOrderAPICallback // handle the callback from the order api function fulfillResponse(bytes32 request, bytes32 result) public virtual override nonReentrant { require(_msgSender() == address(_orderAPIClient), 'caller not order api'); address requestor = _renderRequests[request]; require(requestor != address(0), 'valid request must exist'); uint256 boxTokenId = _renderTokenIds[request]; require(!_exists(boxTokenId), 'token already redeemed'); _internalMintPizza(requestor, boxTokenId, result); } // IERC721 Overrides function tokenURI(uint256 tokenId) public view virtual override(ERC721Upgradeable, IERC721MetadataUpgradeable) returns (string memory) { require(_exists(tokenId), 'does not exist, paisano'); return string(abi.encodePacked(_uriBase, _base58Encode(_tokenPizzaArtworkURIs[tokenId]))); } // IRarePizzasAdmin // set the address of the order api client function setOrderAPIClient(address orderAPIClient) public virtual override onlyOwner { address previous = address(_orderAPIClient); _orderAPIClient = IOrderAPIConsumer(orderAPIClient); emit OrderAPIClientUpdated(previous, address(_orderAPIClient)); } // set the box contract address function setRarePizzasBoxContract(address boxContract) public virtual override onlyOwner { address previous = address(_rarePizzasBoxContract); _rarePizzasBoxContract = IRarePizzasBox(boxContract); emit RarePizzasBoxContractUpdated(previous, address(_rarePizzasBoxContract)); } // the multi sig can update the artwork for a pizza function setPizzaArtworkURI(uint256 tokenId, bytes32 artworkURI) public virtual override onlyOwner { _tokenPizzaArtworkURIs[tokenId] = artworkURI; emit InternalArtworkAssigned(tokenId, artworkURI); } function toggleSaleIsActive() public virtual override onlyOwner { saleIsActive = !saleIsActive; emit SaleActive(saleIsActive); } function withdraw() public virtual override onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } // Internal Stuff function _assignPizzaArtwork(uint256 tokenId, bytes32 artworkURI) internal virtual { _tokenPizzaArtworkURIs[tokenId] = artworkURI; emit InternalArtworkAssigned(tokenId, artworkURI); } function _getPizzaTokenId(uint256 boxTokenId) internal view virtual returns (uint256) { return boxTokenId; } function _externalMintPizza( address requestor, uint256 boxTokenId, uint256 recipeId ) internal virtual { (bool success, bytes memory data) = address(_orderAPIClient).call( abi.encodeWithSignature('executeRequest(address,uint256,uint256)', requestor, boxTokenId, recipeId) ); require(success == true, 'external call failed'); bytes32 requestId = bytes32(data); _renderRequests[requestId] = requestor; _renderTokenIds[requestId] = boxTokenId; } function _internalMintPizza( address requestor, uint256 boxTokenId, bytes32 artwork ) internal virtual { uint256 id = _getPizzaTokenId(boxTokenId); _safeMint(requestor, id); _assignPizzaArtwork(id, artwork); } function _redeemRarePizzasBox( address requestor, uint256 boxTokenId, uint256 recipeId ) internal virtual { require(_redeemedBoxTokenAddress[boxTokenId] == address(0), 'box already redeemed'); _redeemedBoxTokenAddress[boxTokenId] = requestor; _externalMintPizza(requestor, boxTokenId, recipeId); } function _base58Encode(bytes32 input) internal pure virtual returns (bytes memory) { // based on: https://github.com/MrChico/verifyIPFS/blob/master/contracts/verifyIPFS.sol#L28 if (input.length == 0) return new bytes(0); // prepend the stripped multihash values bytes memory source = abi.encodePacked(sha256MultiHash, input); // the ipfs hash takes up 46 characters uint8[] memory digits = new uint8[](46); digits[0] = 0; uint8 digitlength = 1; for (uint256 i = 0; i < source.length; ++i) { uint256 carry = uint8(source[i]); for (uint256 j = 0; j < digitlength; ++j) { carry += uint256(digits[j]) * 256; digits[j] = uint8(carry % 58); carry = carry / 58; } while (carry > 0) { digits[digitlength] = uint8(carry % 58); digitlength++; carry = carry / 58; } } return _toAlphabet(_reverse(digits)); } function _reverse(uint8[] memory input) internal pure virtual returns (uint8[] memory) { uint8[] memory output = new uint8[](input.length); for (uint256 i = 0; i < input.length; i++) { output[i] = input[input.length - 1 - i]; } return output; } function _toAlphabet(uint8[] memory indices) internal pure virtual returns (bytes memory) { bytes memory output = new bytes(indices.length); for (uint256 i = 0; i < indices.length; i++) { output[i] = ALPHABET[indices[i]]; } return output; } }
set the box contract address
function setRarePizzasBoxContract(address boxContract) public virtual override onlyOwner { address previous = address(_rarePizzasBoxContract); _rarePizzasBoxContract = IRarePizzasBox(boxContract); emit RarePizzasBoxContractUpdated(previous, address(_rarePizzasBoxContract)); }
1,045,415
[ 1, 542, 326, 3919, 6835, 1758, 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, 444, 54, 834, 52, 25695, 345, 3514, 8924, 12, 2867, 3919, 8924, 13, 1071, 5024, 3849, 1338, 5541, 288, 203, 3639, 1758, 2416, 273, 1758, 24899, 354, 266, 52, 25695, 345, 3514, 8924, 1769, 203, 3639, 389, 354, 266, 52, 25695, 345, 3514, 8924, 273, 15908, 834, 52, 25695, 345, 3514, 12, 2147, 8924, 1769, 203, 3639, 3626, 534, 834, 52, 25695, 345, 3514, 8924, 7381, 12, 11515, 16, 1758, 24899, 354, 266, 52, 25695, 345, 3514, 8924, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x139b70Ee124Fd701e10Fe1b90d2C53C4bfcdC4Ed/sources/BAKM.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Baby Arkham", "BARKM") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 5; uint256 _buyDevFee = 5; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 5; uint256 _sellDevFee = 15; uint256 totalSupply = 10000000000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x92291aD958EEf8dfF3Be26e148b7cD0bDDA69d7F); devWallet = address(0x92291aD958EEf8dfF3Be26e148b7cD0bDDA69d7F); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(address(marketingWallet), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(address(devWallet), true); excludeFromMaxTransaction(address(marketingWallet), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
15,922,064
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 38, 24383, 1201, 79, 31698, 3113, 315, 38, 9584, 49, 7923, 288, 203, 7010, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 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, 1769, 203, 7010, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 7010, 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, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 7010, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 1381, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 1381, 2 ]
./full_match/1/0x7C0f84E9Dc6F721de21D51A490dE6E370fa01cd6/sources/contracts/strategies/CubanApeStrategy.sol
[renDOGE, MATIC, AAVE, SUSHI, AXS, INJ, ALCX]
uint256[] public weights;
3,008,835
[ 1, 63, 1187, 3191, 7113, 16, 490, 11781, 16, 432, 26714, 16, 11726, 2664, 45, 16, 29539, 55, 16, 2120, 46, 16, 7981, 39, 60, 65, 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, 2254, 5034, 8526, 1071, 5376, 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 ]
pragma solidity 0.5.3; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } 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); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } contract Moloch is ReentrancyGuard { using SafeMath for uint256; /*************** GLOBAL CONSTANTS ***************/ uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day) uint256 public votingPeriodLength; // default = 35 periods (7 days) uint256 public gracePeriodLength; // default = 35 periods (7 days) uint256 public proposalDeposit; // default = 10 ETH (~$1,000 worth of ETH at contract deployment) uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit uint256 public processingReward; // default = 0.1 - amount of ETH to give to whoever processes a proposal uint256 public summoningTime; // needed to determine the current period bool private initialized; // internally tracks deployment under eip-1167 proxy pattern address public depositToken; // deposit token contract reference; default = wETH // HARD-CODED LIMITS // These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations // with periods or shares, yet big enough to not limit reasonable use cases. uint256 constant MAX_VOTING_PERIOD_LENGTH = 10**18; // maximum length of voting period uint256 constant MAX_GRACE_PERIOD_LENGTH = 10**18; // maximum length of grace period uint256 constant MAX_DILUTION_BOUND = 10**18; // maximum dilution bound uint256 constant MAX_NUMBER_OF_SHARES_AND_LOOT = 10**18; // maximum number of shares that can be minted uint256 constant MAX_TOKEN_WHITELIST_COUNT = 400; // maximum number of whitelisted tokens uint256 constant MAX_TOKEN_GUILDBANK_COUNT = 200; // maximum number of tokens with non-zero balance in guildbank // *************** // EVENTS // *************** event SubmitProposal(address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string details, bool[6] flags, uint256 proposalId, address indexed delegateKey, address indexed memberAddress); event SponsorProposal(address indexed delegateKey, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod); event SubmitVote(uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote); event ProcessProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessWhitelistProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event ProcessGuildKickProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass); event Ragequit(address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn); event TokensCollected(address indexed token, uint256 amountToCollect); event CancelProposal(uint256 indexed proposalId, address applicantAddress); event UpdateDelegateKey(address indexed memberAddress, address newDelegateKey); event Withdraw(address indexed memberAddress, address token, uint256 amount); // ******************* // INTERNAL ACCOUNTING // ******************* uint256 public proposalCount = 0; // total proposals submitted uint256 public totalShares = 0; // total shares across all members uint256 public totalLoot = 0; // total loot across all members uint256 public totalGuildBankTokens = 0; // total tokens with non-zero balance in guild bank address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xbeef); address public constant TOTAL = address(0xbabe); mapping (address => mapping(address => uint256)) public userTokenBalances; // userTokenBalances[userAddress][tokenAddress] enum Vote { Null, // default value, counted as abstention Yes, No } struct Member { address delegateKey; // the key responsible for submitting proposals and voting - defaults to member address unless updated uint256 shares; // the # of voting shares assigned to this member uint256 loot; // the loot amount available to this member (combined with shares on ragequit) bool exists; // always true once a member has been created uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES uint256 jailed; // set to proposalIndex of a passing guild kick proposal for this member, prevents voting on and sponsoring proposals } struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as guild kick target for gkick proposals) address proposer; // the account that submitted the proposal (can be non-member) address sponsor; // the member that sponsored the proposal (moving it into the queue) uint256 sharesRequested; // the # of shares the applicant is requesting uint256 lootRequested; // the amount of loot the applicant is requesting uint256 tributeOffered; // amount of tokens offered as tribute address tributeToken; // tribute token contract reference uint256 paymentRequested; // amount of tokens requested as payment address paymentToken; // payment token contract reference uint256 startingPeriod; // the period in which voting can start for this proposal uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal bool[6] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] string details; // proposal details - could be IPFS hash, plaintext, or JSON uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal mapping(address => Vote) votesByMember; // the votes on this proposal by each member } mapping(address => bool) public tokenWhitelist; address[] public approvedTokens; mapping(address => bool) public proposedToWhitelist; mapping(address => bool) public proposedToKick; mapping(address => Member) public members; mapping(address => address) public memberAddressByDelegateKey; mapping(uint256 => Proposal) public proposals; uint256[] public proposalQueue; modifier onlyMember { require(members[msg.sender].shares > 0 || members[msg.sender].loot > 0, "not a member"); _; } modifier onlyShareholder { require(members[msg.sender].shares > 0, "not a shareholder"); _; } modifier onlyDelegate { require(members[memberAddressByDelegateKey[msg.sender]].shares > 0, "not a delegate"); _; } function init( address[] calldata _summoner, address[] calldata _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward, uint256[] calldata _summonerShares ) external { require(!initialized, "initialized"); require(_summoner.length == _summonerShares.length, "summoner length mismatches summonerShares"); require(_periodDuration > 0, "_periodDuration cannot be 0"); require(_votingPeriodLength > 0, "_votingPeriodLength cannot be 0"); require(_votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "_votingPeriodLength exceeds limit"); require(_gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "_gracePeriodLength exceeds limit"); require(_dilutionBound > 0, "_dilutionBound cannot be 0"); require(_dilutionBound <= MAX_DILUTION_BOUND, "_dilutionBound exceeds limit"); require(_approvedTokens.length > 0, "need at least one approved token"); require(_approvedTokens.length <= MAX_TOKEN_WHITELIST_COUNT, "too many tokens"); require(_proposalDeposit >= _processingReward, "_proposalDeposit cannot be smaller than _processingReward"); depositToken = _approvedTokens[0]; for (uint256 i = 0; i < _summoner.length; i++) { require(_summoner[i] != address(0), "summoner cannot be 0"); members[_summoner[i]] = Member(_summoner[i], _summonerShares[i], 0, true, 0, 0); memberAddressByDelegateKey[_summoner[i]] = _summoner[i]; totalShares = totalShares.add(_summonerShares[i]); } require(totalShares <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested"); for (uint256 i = 0; i < _approvedTokens.length; i++) { require(_approvedTokens[i] != address(0), "_approvedToken cannot be 0"); require(!tokenWhitelist[_approvedTokens[i]], "duplicate approved token"); tokenWhitelist[_approvedTokens[i]] = true; approvedTokens.push(_approvedTokens[i]); } periodDuration = _periodDuration; votingPeriodLength = _votingPeriodLength; gracePeriodLength = _gracePeriodLength; proposalDeposit = _proposalDeposit; dilutionBound = _dilutionBound; processingReward = _processingReward; summoningTime = now; initialized = true; } /***************** PROPOSAL FUNCTIONS *****************/ function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details ) public nonReentrant returns (uint256 proposalId) { require(sharesRequested.add(lootRequested) <= MAX_NUMBER_OF_SHARES_AND_LOOT, "too many shares requested"); require(tokenWhitelist[tributeToken], "tributeToken is not whitelisted"); require(tokenWhitelist[paymentToken], "payment is not whitelisted"); require(applicant != address(0), "applicant cannot be 0"); require(applicant != GUILD && applicant != ESCROW && applicant != TOTAL, "applicant address cannot be reserved"); require(members[applicant].jailed == 0, "proposal applicant must not be jailed"); if (tributeOffered > 0 && userTokenBalances[GUILD][tributeToken] == 0) { require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, 'cannot submit more tribute proposals for new tokens - guildbank is full'); } // collect tribute from proposer and store it in the Moloch until the proposal is processed require(IERC20(tributeToken).transferFrom(msg.sender, address(this), tributeOffered), "tribute token transfer failed"); unsafeAddToBalance(ESCROW, tributeToken, tributeOffered); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] _submitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags); return proposalCount - 1; // return proposalId - contracts calling submit might want it } function submitWhitelistProposal(address tokenToWhitelist, string memory details) public nonReentrant returns (uint256 proposalId) { require(tokenToWhitelist != address(0), "must provide token address"); require(!tokenWhitelist[tokenToWhitelist], "cannot already have whitelisted the token"); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot submit more whitelist proposals"); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] flags[4] = true; // whitelist _submitProposal(address(0), 0, 0, 0, tokenToWhitelist, 0, address(0), details, flags); return proposalCount - 1; } function submitGuildKickProposal(address memberToKick, string memory details) public nonReentrant returns (uint256 proposalId) { Member memory member = members[memberToKick]; require(member.shares > 0 || member.loot > 0, "member must have at least one share or one loot"); require(members[memberToKick].jailed == 0, "member must not already be jailed"); bool[6] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] flags[5] = true; // guild kick _submitProposal(memberToKick, 0, 0, 0, address(0), 0, address(0), details, flags); return proposalCount - 1; } function _submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string memory details, bool[6] memory flags ) internal { Proposal memory proposal = Proposal({ applicant : applicant, proposer : msg.sender, sponsor : address(0), sharesRequested : sharesRequested, lootRequested : lootRequested, tributeOffered : tributeOffered, tributeToken : tributeToken, paymentRequested : paymentRequested, paymentToken : paymentToken, startingPeriod : 0, yesVotes : 0, noVotes : 0, flags : flags, details : details, maxTotalSharesAndLootAtYesVote : 0 }); proposals[proposalCount] = proposal; address memberAddress = memberAddressByDelegateKey[msg.sender]; // NOTE: argument order matters, avoid stack too deep emit SubmitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, proposalCount, msg.sender, memberAddress); proposalCount += 1; } function sponsorProposal(uint256 proposalId) public nonReentrant onlyDelegate { // collect proposal deposit from sponsor and store it in the Moloch until the proposal is processed require(IERC20(depositToken).transferFrom(msg.sender, address(this), proposalDeposit), "proposal deposit token transfer failed"); unsafeAddToBalance(ESCROW, depositToken, proposalDeposit); Proposal storage proposal = proposals[proposalId]; require(proposal.proposer != address(0), 'proposal must have been proposed'); require(!proposal.flags[0], "proposal has already been sponsored"); require(!proposal.flags[3], "proposal has been cancelled"); require(members[proposal.applicant].jailed == 0, "proposal applicant must not be jailed"); if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0) { require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, 'cannot sponsor more tribute proposals for new tokens - guildbank is full'); } // whitelist proposal if (proposal.flags[4]) { require(!tokenWhitelist[address(proposal.tributeToken)], "cannot already have whitelisted the token"); require(!proposedToWhitelist[address(proposal.tributeToken)], 'already proposed to whitelist'); require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "cannot sponsor more whitelist proposals"); proposedToWhitelist[address(proposal.tributeToken)] = true; // guild kick proposal } else if (proposal.flags[5]) { require(!proposedToKick[proposal.applicant], 'already proposed to kick'); proposedToKick[proposal.applicant] = true; } // compute startingPeriod for proposal uint256 startingPeriod = max( getCurrentPeriod(), proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length.sub(1)]].startingPeriod ).add(1); proposal.startingPeriod = startingPeriod; address memberAddress = memberAddressByDelegateKey[msg.sender]; proposal.sponsor = memberAddress; proposal.flags[0] = true; // sponsored // append proposal to the queue proposalQueue.push(proposalId); emit SponsorProposal(msg.sender, memberAddress, proposalId, proposalQueue.length.sub(1), startingPeriod); } // NOTE: In MolochV2 proposalIndex !== proposalId function submitVote(uint256 proposalIndex, uint8 uintVote) public nonReentrant onlyDelegate { address memberAddress = memberAddressByDelegateKey[msg.sender]; Member storage member = members[memberAddress]; require(proposalIndex < proposalQueue.length, "proposal does not exist"); Proposal storage proposal = proposals[proposalQueue[proposalIndex]]; require(uintVote < 3, "must be less than 3"); Vote vote = Vote(uintVote); require(getCurrentPeriod() >= proposal.startingPeriod, "voting period has not started"); require(!hasVotingPeriodExpired(proposal.startingPeriod), "proposal voting period has expired"); require(proposal.votesByMember[memberAddress] == Vote.Null, "member has already voted"); require(vote == Vote.Yes || vote == Vote.No, "vote must be either Yes or No"); proposal.votesByMember[memberAddress] = vote; if (vote == Vote.Yes) { proposal.yesVotes = proposal.yesVotes.add(member.shares); // set highest index (latest) yes vote - must be processed for member to ragequit if (proposalIndex > member.highestIndexYesVote) { member.highestIndexYesVote = proposalIndex; } // set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters if (totalShares.add(totalLoot) > proposal.maxTotalSharesAndLootAtYesVote) { proposal.maxTotalSharesAndLootAtYesVote = totalShares.add(totalLoot); } } else if (vote == Vote.No) { proposal.noVotes = proposal.noVotes.add(member.shares); } // NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set untill it's been sponsored but proposal is created on submission emit SubmitVote(proposalQueue[proposalIndex], proposalIndex, msg.sender, memberAddress, uintVote); } function processProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(!proposal.flags[4] && !proposal.flags[5], "must be a standard proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); // Make the proposal fail if the new total number of shares and loot exceeds the limit if (totalShares.add(totalLoot).add(proposal.sharesRequested).add(proposal.lootRequested) > MAX_NUMBER_OF_SHARES_AND_LOOT) { didPass = false; } // Make the proposal fail if it is requesting more tokens as payment than the available guild bank balance if (proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken]) { didPass = false; } // Make the proposal fail if it would result in too many tokens with non-zero balance in guild bank if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 && totalGuildBankTokens >= MAX_TOKEN_GUILDBANK_COUNT) { didPass = false; } // PROPOSAL PASSED if (didPass) { proposal.flags[2] = true; // didPass // if the applicant is already a member, add to their existing shares & loot if (members[proposal.applicant].exists) { members[proposal.applicant].shares = members[proposal.applicant].shares.add(proposal.sharesRequested); members[proposal.applicant].loot = members[proposal.applicant].loot.add(proposal.lootRequested); // the applicant is a new member, create a new record for them } else { // if the applicant address is already taken by a member's delegateKey, reset it to their member address if (members[memberAddressByDelegateKey[proposal.applicant]].exists) { address memberToOverride = memberAddressByDelegateKey[proposal.applicant]; memberAddressByDelegateKey[memberToOverride] = memberToOverride; members[memberToOverride].delegateKey = memberToOverride; } // use applicant address as delegateKey by default members[proposal.applicant] = Member(proposal.applicant, proposal.sharesRequested, proposal.lootRequested, true, 0, 0); memberAddressByDelegateKey[proposal.applicant] = proposal.applicant; } // mint new shares & loot totalShares = totalShares.add(proposal.sharesRequested); totalLoot = totalLoot.add(proposal.lootRequested); // if the proposal tribute is the first tokens of its kind to make it into the guild bank, increment total guild bank tokens if (userTokenBalances[GUILD][proposal.tributeToken] == 0 && proposal.tributeOffered > 0) { totalGuildBankTokens += 1; } unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered); unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested); // if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens if (userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0) { totalGuildBankTokens -= 1; } // PROPOSAL FAILED } else { // return all tokens to the proposer (not the applicant, because funds come from proposer) unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); } _returnDeposit(proposal.sponsor); emit ProcessProposal(proposalIndex, proposalId, didPass); } function processWhitelistProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[4], "must be a whitelist proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); if (approvedTokens.length >= MAX_TOKEN_WHITELIST_COUNT) { didPass = false; } if (didPass) { proposal.flags[2] = true; // didPass tokenWhitelist[address(proposal.tributeToken)] = true; approvedTokens.push(proposal.tributeToken); } proposedToWhitelist[address(proposal.tributeToken)] = false; _returnDeposit(proposal.sponsor); emit ProcessWhitelistProposal(proposalIndex, proposalId, didPass); } function processGuildKickProposal(uint256 proposalIndex) public nonReentrant { _validateProposalForProcessing(proposalIndex); uint256 proposalId = proposalQueue[proposalIndex]; Proposal storage proposal = proposals[proposalId]; require(proposal.flags[5], "must be a guild kick proposal"); proposal.flags[1] = true; // processed bool didPass = _didPass(proposalIndex); if (didPass) { proposal.flags[2] = true; // didPass Member storage member = members[proposal.applicant]; member.jailed = proposalIndex; // transfer shares to loot member.loot = member.loot.add(member.shares); totalShares = totalShares.sub(member.shares); totalLoot = totalLoot.add(member.shares); member.shares = 0; // revoke all shares } proposedToKick[proposal.applicant] = false; _returnDeposit(proposal.sponsor); emit ProcessGuildKickProposal(proposalIndex, proposalId, didPass); } function _didPass(uint256 proposalIndex) internal returns (bool didPass) { Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; didPass = proposal.yesVotes > proposal.noVotes; // Make the proposal fail if the dilutionBound is exceeded if ((totalShares.add(totalLoot)).mul(dilutionBound) < proposal.maxTotalSharesAndLootAtYesVote) { didPass = false; } // Make the proposal fail if the applicant is jailed // - for standard proposals, we don't want the applicant to get any shares/loot/payment // - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter if (members[proposal.applicant].jailed != 0) { didPass = false; } return didPass; } function _validateProposalForProcessing(uint256 proposalIndex) internal view { require(proposalIndex < proposalQueue.length, "proposal does not exist"); Proposal memory proposal = proposals[proposalQueue[proposalIndex]]; require(getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength), "proposal is not ready to be processed"); require(proposal.flags[1] == false, "proposal has already been processed"); require(proposalIndex == 0 || proposals[proposalQueue[proposalIndex.sub(1)]].flags[1], "previous proposal must be processed"); } function _returnDeposit(address sponsor) internal { unsafeInternalTransfer(ESCROW, msg.sender, depositToken, processingReward); unsafeInternalTransfer(ESCROW, sponsor, depositToken, proposalDeposit.sub(processingReward)); } function ragequit(uint256 sharesToBurn, uint256 lootToBurn) public nonReentrant onlyMember { _ragequit(msg.sender, sharesToBurn, lootToBurn); } function _ragequit(address memberAddress, uint256 sharesToBurn, uint256 lootToBurn) internal { uint256 initialTotalSharesAndLoot = totalShares.add(totalLoot); Member storage member = members[memberAddress]; require(member.shares >= sharesToBurn, "insufficient shares"); require(member.loot >= lootToBurn, "insufficient loot"); require(canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed"); uint256 sharesAndLootToBurn = sharesToBurn.add(lootToBurn); // burn shares and loot member.shares = member.shares.sub(sharesToBurn); member.loot = member.loot.sub(lootToBurn); totalShares = totalShares.sub(sharesToBurn); totalLoot = totalLoot.sub(lootToBurn); for (uint256 i = 0; i < approvedTokens.length; i++) { uint256 amountToRagequit = fairShare(userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot); if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit // deliberately not using safemath here to keep overflows from preventing the function execution (which would break ragekicks) // if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit; userTokenBalances[memberAddress][approvedTokens[i]] += amountToRagequit; } } emit Ragequit(msg.sender, sharesToBurn, lootToBurn); } function ragekick(address memberToKick) public nonReentrant { Member storage member = members[memberToKick]; require(member.jailed != 0, "member must be in jail"); require(member.loot > 0, "member must have some loot"); // note - should be impossible for jailed member to have shares require(canRagequit(member.highestIndexYesVote), "cannot ragequit until highest index proposal member voted YES on is processed"); _ragequit(memberToKick, 0, member.loot); } function withdrawBalance(address token, uint256 amount) public nonReentrant { _withdrawBalance(token, amount); } function withdrawBalances(address[] memory tokens, uint256[] memory amounts, bool max) public nonReentrant { require(tokens.length == amounts.length, "tokens and amounts arrays must be matching lengths"); for (uint256 i=0; i < tokens.length; i++) { uint256 withdrawAmount = amounts[i]; if (max) { // withdraw the maximum balance withdrawAmount = userTokenBalances[msg.sender][tokens[i]]; } _withdrawBalance(tokens[i], withdrawAmount); } } function _withdrawBalance(address token, uint256 amount) internal { require(userTokenBalances[msg.sender][token] >= amount, "insufficient balance"); unsafeSubtractFromBalance(msg.sender, token, amount); require(IERC20(token).transfer(msg.sender, amount), "transfer failed"); emit Withdraw(msg.sender, token, amount); } function collectTokens(address token) public onlyDelegate nonReentrant { uint256 amountToCollect = IERC20(token).balanceOf(address(this)).sub(userTokenBalances[TOTAL][token]); // only collect if 1) there are tokens to collect 2) token is whitelisted 3) token has non-zero balance require(amountToCollect > 0, 'no tokens to collect'); require(tokenWhitelist[token], 'token to collect must be whitelisted'); require(userTokenBalances[GUILD][token] > 0, 'token to collect must have non-zero guild bank balance'); unsafeAddToBalance(GUILD, token, amountToCollect); emit TokensCollected(token, amountToCollect); } // NOTE: requires that delegate key which sent the original proposal cancels, msg.sender == proposal.proposer function cancelProposal(uint256 proposalId) public nonReentrant { Proposal storage proposal = proposals[proposalId]; require(!proposal.flags[0], "proposal has already been sponsored"); require(!proposal.flags[3], "proposal has already been cancelled"); require(msg.sender == proposal.proposer, "solely the proposer can cancel"); proposal.flags[3] = true; // cancelled unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); emit CancelProposal(proposalId, msg.sender); } function updateDelegateKey(address newDelegateKey) public nonReentrant onlyShareholder { require(newDelegateKey != address(0), "newDelegateKey cannot be 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != msg.sender) { require(!members[newDelegateKey].exists, "cannot overwrite existing members"); require(!members[memberAddressByDelegateKey[newDelegateKey]].exists, "cannot overwrite existing delegate keys"); } Member storage member = members[msg.sender]; memberAddressByDelegateKey[member.delegateKey] = address(0); memberAddressByDelegateKey[newDelegateKey] = msg.sender; member.delegateKey = newDelegateKey; emit UpdateDelegateKey(msg.sender, newDelegateKey); } // can only ragequit if the latest proposal you voted YES on has been processed function canRagequit(uint256 highestIndexYesVote) public view returns (bool) { require(highestIndexYesVote < proposalQueue.length, "proposal does not exist"); return proposals[proposalQueue[highestIndexYesVote]].flags[1]; } function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) { return getCurrentPeriod() >= startingPeriod.add(votingPeriodLength); } /*************** GETTER FUNCTIONS ***************/ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x >= y ? x : y; } function getCurrentPeriod() public view returns (uint256) { return now.sub(summoningTime).div(periodDuration); } function getProposalQueueLength() public view returns (uint256) { return proposalQueue.length; } function getProposalFlags(uint256 proposalId) public view returns (bool[6] memory) { return proposals[proposalId].flags; } function getUserTokenBalance(address user, address token) public view returns (uint256) { return userTokenBalances[user][token]; } function getMemberProposalVote(address memberAddress, uint256 proposalIndex) public view returns (Vote) { require(members[memberAddress].exists, "member does not exist"); require(proposalIndex < proposalQueue.length, "proposal does not exist"); return proposals[proposalQueue[proposalIndex]].votesByMember[memberAddress]; } function getTokenCount() public view returns (uint256) { return approvedTokens.length; } /*************** HELPER FUNCTIONS ***************/ function unsafeAddToBalance(address user, address token, uint256 amount) internal { userTokenBalances[user][token] += amount; userTokenBalances[TOTAL][token] += amount; } function unsafeSubtractFromBalance(address user, address token, uint256 amount) internal { userTokenBalances[user][token] -= amount; userTokenBalances[TOTAL][token] -= amount; } function unsafeInternalTransfer(address from, address to, address token, uint256 amount) internal { unsafeSubtractFromBalance(from, token, amount); unsafeAddToBalance(to, token, amount); } function fairShare(uint256 balance, uint256 shares, uint256 totalShares) internal pure returns (uint256) { require(totalShares != 0); if (balance == 0) { return 0; } uint256 prod = balance * shares; if (prod / balance == shares) { // no overflow in multiplication above? return prod / totalShares; } return (balance / totalShares) * shares; } } /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract CloneFactory { // implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167 function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } } contract MolochSummoner is CloneFactory { address public template; constructor(address _template) public { template = _template; } event SummonComplete(address indexed moloch, address[] summoner, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDeposit, uint256 dilutionBound, uint256 processingReward, uint256[] summonerShares); function summonMoloch( address[] memory _summoner, address[] memory _approvedTokens, uint256 _periodDuration, uint256 _votingPeriodLength, uint256 _gracePeriodLength, uint256 _proposalDeposit, uint256 _dilutionBound, uint256 _processingReward, uint256[] memory _summonerShares ) public returns (address) { Moloch baal = Moloch(createClone(template)); baal.init( _summoner, _approvedTokens, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward, _summonerShares ); emit SummonComplete(address(baal), _summoner, _approvedTokens, now, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDeposit, _dilutionBound, _processingReward, _summonerShares); return address(baal); } }
use applicant address as delegateKey by default
members[proposal.applicant] = Member(proposal.applicant, proposal.sharesRequested, proposal.lootRequested, true, 0, 0);
45,168
[ 1, 1202, 513, 1780, 970, 1758, 487, 7152, 653, 635, 805, 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, 7734, 4833, 63, 685, 8016, 18, 438, 1780, 970, 65, 273, 8596, 12, 685, 8016, 18, 438, 1780, 970, 16, 14708, 18, 30720, 11244, 16, 14708, 18, 383, 352, 11244, 16, 638, 16, 374, 16, 374, 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 ]
./partial_match/1/0xD0478Ab51B53A8aCE00a402e0f190bbe6B0Eb969/sources/A.sol
**** ADD LIQUIDITY **** create the pair if it doesn't exist yet
function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { if (IBioFactory(factory).getPair(tokenA, tokenB) == address(0)) { IBioFactory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = BioLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint amountBOptimal = BioLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'BioRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); uint amountAOptimal = BioLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'BioRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } }
15,617,944
[ 1, 8355, 8961, 53, 3060, 4107, 225, 752, 326, 3082, 309, 518, 3302, 1404, 1005, 4671, 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, 389, 1289, 48, 18988, 24237, 12, 203, 3639, 1758, 1147, 37, 16, 203, 3639, 1758, 1147, 38, 16, 203, 3639, 2254, 3844, 1880, 281, 2921, 16, 203, 3639, 2254, 3844, 38, 25683, 16, 203, 3639, 2254, 3844, 2192, 267, 16, 203, 3639, 2254, 3844, 38, 2930, 203, 565, 262, 2713, 5024, 1135, 261, 11890, 3844, 37, 16, 2254, 3844, 38, 13, 288, 203, 3639, 309, 261, 13450, 1594, 1733, 12, 6848, 2934, 588, 4154, 12, 2316, 37, 16, 1147, 38, 13, 422, 1758, 12, 20, 3719, 288, 203, 5411, 23450, 1594, 1733, 12, 6848, 2934, 2640, 4154, 12, 2316, 37, 16, 1147, 38, 1769, 203, 3639, 289, 203, 3639, 261, 11890, 20501, 37, 16, 2254, 20501, 38, 13, 273, 21209, 9313, 18, 588, 607, 264, 3324, 12, 6848, 16, 1147, 37, 16, 1147, 38, 1769, 203, 3639, 309, 261, 455, 6527, 37, 422, 374, 597, 20501, 38, 422, 374, 13, 288, 203, 5411, 261, 8949, 37, 16, 3844, 38, 13, 273, 261, 8949, 1880, 281, 2921, 16, 3844, 38, 25683, 1769, 203, 5411, 2254, 3844, 5315, 337, 2840, 273, 21209, 9313, 18, 6889, 12, 8949, 1880, 281, 2921, 16, 20501, 37, 16, 20501, 38, 1769, 203, 5411, 309, 261, 8949, 5315, 337, 2840, 1648, 3844, 38, 25683, 13, 288, 203, 7734, 2583, 12, 8949, 5315, 337, 2840, 1545, 3844, 38, 2930, 16, 296, 38, 1594, 8259, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 38, 67, 2192, 51, 5321, 8284, 203, 7734, 261, 8949, 37, 16, 3844, 38, 13, 273, 261, 8949, 2 ]
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // 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).ISCONTRACT107(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // 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 ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many 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 HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (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 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function LOG714(uint p0, address p1, bool p2, string memory p3) internal view {
14,087,784
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 2018, 27, 3461, 12, 11890, 293, 20, 16, 1758, 293, 21, 16, 1426, 293, 22, 16, 533, 3778, 293, 23, 13, 2713, 1476, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xF4701742ED9De96B19a186979faF9a51BbF37B6D/sources/browser/SmartFundETHFactory.sol
* @dev Approve the passed address to spend the specified amount of shares on behalf of msg.sender. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: @param _spender The address which will spend the funds. @param _value The amount of shares to be spent. @return true upon success/
function approve(address _spender, uint256 _value) external override returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
715,320
[ 1, 12053, 537, 326, 2275, 1758, 358, 17571, 326, 1269, 3844, 434, 24123, 603, 12433, 6186, 434, 1234, 18, 15330, 18, 605, 359, 834, 716, 12770, 392, 1699, 1359, 598, 333, 707, 5186, 899, 326, 18404, 716, 18626, 2026, 999, 3937, 326, 1592, 471, 326, 394, 1699, 1359, 635, 640, 22618, 340, 2492, 9543, 18, 6942, 3323, 6959, 358, 20310, 360, 340, 333, 17996, 2269, 353, 358, 1122, 5459, 326, 17571, 264, 1807, 1699, 1359, 358, 374, 471, 444, 326, 6049, 460, 23838, 30, 225, 389, 87, 1302, 264, 565, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 389, 1132, 1377, 1021, 3844, 434, 24123, 358, 506, 26515, 18, 327, 638, 12318, 2216, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 3903, 3849, 1135, 261, 6430, 13, 288, 203, 565, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 203, 565, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @aragon/court/contracts/lib/os/IsContract.sol // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol // Adapted to use pragma ^0.5.8 and satisfy our linter rules pragma solidity ^0.5.8; contract IsContract { function ISCONTRACT505(address _target) internal view returns (bool) { //inject NONSTANDARD NAMING if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/court/contracts/lib/os/ERC20.sol // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/token/ERC20.sol // Adapted to use pragma ^0.5.8 and satisfy our linter rules pragma solidity ^0.5.8; contract ERC20 { function TOTALSUPPLY734() public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF87(address _who) public view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE217(address _owner, address _spender) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER438(address _to, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING function APPROVE791(address _spender, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM747(address _from, address _to, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING event TRANSFER133( //inject NONSTANDARD NAMING address indexed from, address indexed to, uint256 value ); event APPROVAL808( //inject NONSTANDARD NAMING address indexed owner, address indexed spender, uint256 value ); } // File: @aragon/court/contracts/lib/os/SafeERC20.sol // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol // Adapted to use pragma ^0.5.8 and satisfy our linter rules pragma solidity ^0.5.8; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant transfer_selector206 = 0xa9059cbb; //inject NONSTANDARD NAMING function SAFETRANSFER7(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING bytes memory transferCallData = abi.encodeWithSelector( transfer_selector206, _to, _amount ); return INVOKEANDCHECKSUCCESS678(address(_token), transferCallData); } function SAFETRANSFERFROM771(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING bytes memory transferFromCallData = abi.encodeWithSelector( _token.TRANSFERFROM747.selector, _from, _to, _amount ); return INVOKEANDCHECKSUCCESS678(address(_token), transferFromCallData); } function SAFEAPPROVE557(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING bytes memory approveCallData = abi.encodeWithSelector( _token.APPROVE791.selector, _spender, _amount ); return INVOKEANDCHECKSUCCESS678(address(_token), approveCallData); } function INVOKEANDCHECKSUCCESS678(address _addr, bytes memory _calldata) private returns (bool) { //inject NONSTANDARD NAMING bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } } // File: @aragon/court/contracts/standards/ERC900.sol pragma solidity ^0.5.8; // Interface for ERC900: https://eips.ethereum.org/EIPS/eip-900 interface ERC900 { event STAKED64(address indexed user, uint256 amount, uint256 total, bytes data); //inject NONSTANDARD NAMING event UNSTAKED870(address indexed user, uint256 amount, uint256 total, bytes data); //inject NONSTANDARD NAMING function STAKE84(uint256 _amount, bytes calldata _data) external; //inject NONSTANDARD NAMING function STAKEFOR84(address _user, uint256 _amount, bytes calldata _data) external; //inject NONSTANDARD NAMING function UNSTAKE238(uint256 _amount, bytes calldata _data) external; //inject NONSTANDARD NAMING function TOTALSTAKEDFOR777(address _addr) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSTAKED236() external view returns (uint256); //inject NONSTANDARD NAMING function TOKEN451() external view returns (address); //inject NONSTANDARD NAMING function SUPPORTSHISTORY821() external pure returns (bool); //inject NONSTANDARD NAMING } // File: contracts/lib/uniswap/interfaces/IUniswapExchange.sol pragma solidity ^0.5.0; interface IUniswapExchange { event TOKENPURCHASE996(address indexed buyer, uint256 indexed eth_sold, uint256 indexed tokens_bought); //inject NONSTANDARD NAMING event ETHPURCHASE686(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed eth_bought); //inject NONSTANDARD NAMING event ADDLIQUIDITY195(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); //inject NONSTANDARD NAMING event REMOVELIQUIDITY507(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); //inject NONSTANDARD NAMING function () external payable; function GETINPUTPRICE733(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); //inject NONSTANDARD NAMING function GETOUTPUTPRICE452(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); //inject NONSTANDARD NAMING function ETHTOTOKENSWAPINPUT342(uint256 min_tokens, uint256 deadline) external payable returns (uint256); //inject NONSTANDARD NAMING function ETHTOTOKENTRANSFERINPUT323(uint256 min_tokens, uint256 deadline, address recipient) external payable returns(uint256); //inject NONSTANDARD NAMING function ETHTOTOKENSWAPOUTPUT701(uint256 tokens_bought, uint256 deadline) external payable returns(uint256); //inject NONSTANDARD NAMING function ETHTOTOKENTRANSFEROUTPUT693(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256); //inject NONSTANDARD NAMING function TOKENTOETHSWAPINPUT977(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256); //inject NONSTANDARD NAMING function TOKENTOETHTRANSFERINPUT18(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256); //inject NONSTANDARD NAMING function TOKENTOETHSWAPOUTPUT664(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256); //inject NONSTANDARD NAMING function TOKENTOETHTRANSFEROUTPUT247(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256); //inject NONSTANDARD NAMING function TOKENTOTOKENSWAPINPUT27( //inject NONSTANDARD NAMING uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256); function TOKENTOTOKENTRANSFERINPUT278( //inject NONSTANDARD NAMING uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256); function TOKENTOTOKENSWAPOUTPUT751( //inject NONSTANDARD NAMING uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256); function TOKENTOTOKENTRANSFEROUTPUT428( //inject NONSTANDARD NAMING uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256); function TOKENTOEXCHANGESWAPINPUT174( //inject NONSTANDARD NAMING uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256); function TOKENTOEXCHANGETRANSFERINPUT767( //inject NONSTANDARD NAMING uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256); function TOKENTOEXCHANGESWAPOUTPUT918( //inject NONSTANDARD NAMING uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256); function TOKENTOEXCHANGETRANSFEROUTPUT147( //inject NONSTANDARD NAMING uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256); function GETETHTOTOKENINPUTPRICE69(uint256 eth_sold) external view returns (uint256); //inject NONSTANDARD NAMING function GETETHTOTOKENOUTPUTPRICE555(uint256 tokens_bought) external view returns (uint256); //inject NONSTANDARD NAMING function GETTOKENTOETHINPUTPRICE162(uint256 tokens_sold) external view returns (uint256); //inject NONSTANDARD NAMING function GETTOKENTOETHOUTPUTPRICE369(uint256 eth_bought) external view returns (uint256); //inject NONSTANDARD NAMING function TOKENADDRESS963() external view returns (address); //inject NONSTANDARD NAMING function FACTORYADDRESS389() external view returns (address); //inject NONSTANDARD NAMING function ADDLIQUIDITY566(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); //inject NONSTANDARD NAMING function REMOVELIQUIDITY718(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); //inject NONSTANDARD NAMING } // File: contracts/lib/uniswap/interfaces/IUniswapFactory.sol pragma solidity ^0.5.0; interface IUniswapFactory { event NEWEXCHANGE290(address indexed token, address indexed exchange); //inject NONSTANDARD NAMING function INITIALIZEFACTORY19(address template) external; //inject NONSTANDARD NAMING function CREATEEXCHANGE596(address token) external returns (address payable); //inject NONSTANDARD NAMING function GETEXCHANGE730(address token) external view returns (address payable); //inject NONSTANDARD NAMING function GETTOKEN772(address token) external view returns (address); //inject NONSTANDARD NAMING function GETTOKENWIHID451(uint256 token_id) external view returns (address); //inject NONSTANDARD NAMING } // File: contracts/Refundable.sol pragma solidity ^0.5.8; contract Refundable { using SafeERC20 for ERC20; string private constant error_not_governor455 = "REF_NOT_GOVERNOR"; //inject NONSTANDARD NAMING string private constant error_zero_amount252 = "REF_ZERO_AMOUNT"; //inject NONSTANDARD NAMING string private constant error_not_enough_balance862 = "REF_NOT_ENOUGH_BALANCE"; //inject NONSTANDARD NAMING string private constant error_eth_refund150 = "REF_ETH_REFUND"; //inject NONSTANDARD NAMING string private constant error_token_refund409 = "REF_TOKEN_REFUND"; //inject NONSTANDARD NAMING address public governor; modifier ONLYGOVERNOR318() { //inject NONSTANDARD NAMING require(msg.sender == governor, error_not_governor455); _; } constructor(address _governor) public { governor = _governor; } function REFUNDETH646(address payable _recipient, uint256 _amount) external ONLYGOVERNOR318 { //inject NONSTANDARD NAMING require(_amount > 0, error_zero_amount252); uint256 selfBalance = address(this).balance; require(selfBalance >= _amount, error_not_enough_balance862); // solium-disable security/no-call-value (bool result,) = _recipient.call.value(_amount)(""); require(result, error_eth_refund150); } function REFUNDTOKEN5(ERC20 _token, address _recipient, uint256 _amount) external ONLYGOVERNOR318 { //inject NONSTANDARD NAMING require(_amount > 0, error_zero_amount252); uint256 selfBalance = _token.BALANCEOF87(address(this)); require(selfBalance >= _amount, error_not_enough_balance862); require(_token.SAFETRANSFER7(_recipient, _amount), error_token_refund409); } } // File: contracts/UniswapWrapper.sol pragma solidity ^0.5.8; contract UniswapWrapper is Refundable, IsContract { using SafeERC20 for ERC20; string private constant error_token_not_contract383 = "UW_TOKEN_NOT_CONTRACT"; //inject NONSTANDARD NAMING string private constant error_registry_not_contract179 = "UW_REGISTRY_NOT_CONTRACT"; //inject NONSTANDARD NAMING string private constant error_uniswap_factory_not_contract907 = "UW_UNISWAP_FACTORY_NOT_CONTRACT"; //inject NONSTANDARD NAMING string private constant error_received_wrong_token364 = "UW_RECEIVED_WRONG_TOKEN"; //inject NONSTANDARD NAMING string private constant error_wrong_data_length344 = "UW_WRONG_DATA_LENGTH"; //inject NONSTANDARD NAMING string private constant error_zero_amount252 = "UW_ZERO_AMOUNT"; //inject NONSTANDARD NAMING string private constant error_token_transfer_failed211 = "UW_TOKEN_TRANSFER_FAILED"; //inject NONSTANDARD NAMING string private constant error_token_approval_failed944 = "UW_TOKEN_APPROVAL_FAILED"; //inject NONSTANDARD NAMING string private constant error_uniswap_unavailable264 = "UW_UNISWAP_UNAVAILABLE"; //inject NONSTANDARD NAMING bytes32 internal constant activate_data805 = keccak256("activate(uint256)"); //inject NONSTANDARD NAMING ERC20 public bondedToken; ERC900 public registry; IUniswapFactory public uniswapFactory; constructor(address _governor, ERC20 _bondedToken, ERC900 _registry, IUniswapFactory _uniswapFactory) Refundable(_governor) public { require(ISCONTRACT505(address(_bondedToken)), error_token_not_contract383); require(ISCONTRACT505(address(_registry)), error_registry_not_contract179); require(ISCONTRACT505(address(_uniswapFactory)), error_uniswap_factory_not_contract907); bondedToken = _bondedToken; registry = _registry; uniswapFactory = _uniswapFactory; } function RECEIVEAPPROVAL744(address _from, uint256 _amount, address _token, bytes calldata _data) external { //inject NONSTANDARD NAMING require(_token == msg.sender, error_received_wrong_token364); // data must have 4 words require(_data.length == 128, error_wrong_data_length344); bool activate; uint256 minTokens; uint256 minEth; uint256 deadline; bytes memory data = _data; assembly { activate := mload(add(data, 0x20)) minTokens := mload(add(data, 0x40)) minEth := mload(add(data, 0x60)) deadline := mload(add(data, 0x80)) } _CONTRIBUTEEXTERNALTOKEN25(_from, _amount, _token, minTokens, minEth, deadline, activate); } function CONTRIBUTEEXTERNALTOKEN307( //inject NONSTANDARD NAMING uint256 _amount, address _token, uint256 _minTokens, uint256 _minEth, uint256 _deadline, bool _activate ) external { _CONTRIBUTEEXTERNALTOKEN25(msg.sender, _amount, _token, _minTokens, _minEth, _deadline, _activate); } function CONTRIBUTEETH468(uint256 _minTokens, uint256 _deadline, bool _activate) external payable { //inject NONSTANDARD NAMING require(msg.value > 0, error_zero_amount252); // get the Uniswap exchange for the bonded token address payable uniswapExchangeAddress = uniswapFactory.GETEXCHANGE730(address(bondedToken)); require(uniswapExchangeAddress != address(0), error_uniswap_unavailable264); IUniswapExchange uniswapExchange = IUniswapExchange(uniswapExchangeAddress); // swap tokens uint256 bondedTokenAmount = uniswapExchange.ETHTOTOKENSWAPINPUT342.value(msg.value)(_minTokens, _deadline); // stake and activate in the registry _STAKEANDACTIVATE532(msg.sender, bondedTokenAmount, _activate); } function _CONTRIBUTEEXTERNALTOKEN25( //inject NONSTANDARD NAMING address _from, uint256 _amount, address _token, uint256 _minTokens, uint256 _minEth, uint256 _deadline, bool _activate ) internal { require(_amount > 0, error_zero_amount252); // move tokens to this contract ERC20 token = ERC20(_token); require(token.SAFETRANSFERFROM771(_from, address(this), _amount), error_token_transfer_failed211); // get the Uniswap exchange for the external token address payable uniswapExchangeAddress = uniswapFactory.GETEXCHANGE730(_token); require(uniswapExchangeAddress != address(0), error_uniswap_unavailable264); IUniswapExchange uniswapExchange = IUniswapExchange(uniswapExchangeAddress); require(token.SAFEAPPROVE557(address(uniswapExchange), _amount), error_token_approval_failed944); // swap tokens uint256 bondedTokenAmount = uniswapExchange.TOKENTOTOKENSWAPINPUT27(_amount, _minTokens, _minEth, _deadline, address(bondedToken)); // stake and activate in the registry _STAKEANDACTIVATE532(_from, bondedTokenAmount, _activate); } function _STAKEANDACTIVATE532(address _from, uint256 _amount, bool _activate) internal { //inject NONSTANDARD NAMING // activate in registry bondedToken.APPROVE791(address(registry), _amount); bytes memory data; if (_activate) { data = abi.encodePacked(activate_data805); } registry.STAKEFOR84(_from, _amount, data); } }
inject NONSTANDARD NAMING
function GETINPUTPRICE733(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256);
2,479,457
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4978, 15934, 7698, 1441, 27, 3707, 12, 11890, 5034, 810, 67, 8949, 16, 2254, 5034, 810, 67, 455, 6527, 16, 2254, 5034, 876, 67, 455, 6527, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; /* * From OpenZeppelin project: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ /** * @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&#39;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; } } /* * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool); function transferFrom(address from, address to, uint value) returns (bool); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * Standard ERC20 token with Short Hand Attack and approve() race condition mitigation. * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20 { using SafeMath for uint; /* Actual balances of token holders */ mapping (address => uint) balances; /* approve() allowances */ mapping (address => mapping (address => uint)) allowed; /* Interface declaration */ function isToken() public constant returns (bool) { return true; } /** * * Fix for the ERC20 short address attack * * http://vessenes.com/the-erc20-short-address-attack-explained/ */ modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } /** * @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, uint _value) onlyPayloadSize(2 * 32) returns (bool) { require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _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 transferFrom(address _from, address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool) { require(balances[_from] >= _value && allowed[_from][_to] >= _value); allowed[_from][_to] = allowed[_from][_to].sub(_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _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 (uint balance) { return balances[_owner]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; 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) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @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 = 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 { require(newOwner != address(0)); owner = newOwner; } } contract EmeraldToken is StandardToken, Ownable { string public name; string public symbol; uint public decimals; mapping (address => bool) public producers; bool public released = false; /* * Only producer allowed */ modifier onlyProducer() { require(producers[msg.sender] == true); _; } /** * Limit token transfer until the distribution is over. * Owner can transfer tokens anytime */ modifier canTransfer(address _sender) { if (_sender != owner) require(released); _; } modifier inProduction() { require(!released); _; } function EmeraldToken(string _name, string _symbol, uint _decimals) { require(_decimals > 0); name = _name; symbol = _symbol; decimals = _decimals; // Make owner a producer of Emeralds producers[msg.sender] = true; } /* * Sets a producer&#39;s status * Distribution contract can be a producer */ function setProducer(address _addr, bool _status) onlyOwner { producers[_addr] = _status; } /* * Creates new Emeralds */ function produceEmeralds(address _receiver, uint _amount) onlyProducer inProduction { balances[_receiver] = balances[_receiver].add(_amount); totalSupply = totalSupply.add(_amount); Transfer(0, _receiver, _amount); } /** * One way function to release the tokens to the wild. No more tokens can be created. */ function releaseTokenTransfer() onlyOwner { released = true; } function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool) { // Call StandardToken.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool) { // Call StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } } /* * Haltable * * Abstract contract that allows children to implement an * emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. * * * Originally envisioned in FirstBlood ICO contract. */ contract Haltable is Ownable { bool public halted = false; modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } /* * The main contract for the Token Distribution Event */ contract TokenDistribution is Haltable { using SafeMath for uint; address public wallet; // an account for withdrow uint public presaleStart; // presale start time uint public start; // distribution start time uint public end; // distribution end time EmeraldToken public token; // token contract address uint public weiGoal; // minimum wei amount we want to get during token distribution uint public weiPresaleMax; // maximum wei amount we can get during presale uint public contributorsCount = 0; // number of contributors uint public weiTotal = 0; // total wei amount we have received uint public weiDistributed = 0; // total wei amount we have received in Distribution state uint public maxCap; // maximum token supply uint public tokensSold = 0; // tokens sold uint public loadedRefund = 0; // wei amount for refund uint public weiRefunded = 0; // wei amount refunded mapping (address => uint) public contributors; // list of contributors mapping (address => uint) public presale; // list of presale contributors enum States {Preparing, Presale, Waiting, Distribution, Success, Failure, Refunding} event Contributed(address _contributor, uint _weiAmount, uint _tokenAmount); event GoalReached(uint _weiAmount); event LoadedRefund(address _address, uint _loadedRefund); event Refund(address _contributor, uint _weiAmount); modifier inState(States _state) { require(getState() == _state); _; } function TokenDistribution(EmeraldToken _token, address _wallet, uint _presaleStart, uint _start, uint _end, uint _ethPresaleMaxNoDecimals, uint _ethGoalNoDecimals, uint _maxTokenCapNoDecimals) { require(_token != address(0) && _wallet != address(0) && _presaleStart > 0 && _start > _presaleStart && _end > _start && _ethPresaleMaxNoDecimals > 0 && _ethGoalNoDecimals > _ethPresaleMaxNoDecimals && _maxTokenCapNoDecimals > 0); require(_token.isToken()); token = _token; wallet = _wallet; presaleStart = _presaleStart; start = _start; end = _end; weiPresaleMax = _ethPresaleMaxNoDecimals * 1 ether; weiGoal = _ethGoalNoDecimals * 1 ether; maxCap = _maxTokenCapNoDecimals * 10 ** token.decimals(); } function() payable { buy(); } /* * Contributors can make payment and receive their tokens */ function buy() payable stopInEmergency { require(getState() == States.Presale || getState() == States.Distribution); require(msg.value > 0); if (getState() == States.Presale) presale[msg.sender] = presale[msg.sender].add(msg.value); else { contributors[msg.sender] = contributors[msg.sender].add(msg.value); weiDistributed = weiDistributed.add(msg.value); } contributeInternal(msg.sender, msg.value, getTokenAmount(msg.value)); } /* * Preallocate tokens for reserve, bounties etc. */ function preallocate(address _receiver, uint _tokenAmountNoDecimals) onlyOwner stopInEmergency { require(getState() != States.Failure && getState() != States.Refunding && !token.released()); uint tokenAmount = _tokenAmountNoDecimals * 10 ** token.decimals(); contributeInternal(_receiver, 0, tokenAmount); } /* * Allow load refunds back on the contract for the refunding. */ function loadRefund() payable { require(getState() == States.Failure || getState() == States.Refunding); require(msg.value > 0); loadedRefund = loadedRefund.add(msg.value); LoadedRefund(msg.sender, msg.value); } /* * Changes dates of token distribution event */ function setDates(uint _presaleStart, uint _start, uint _end) onlyOwner { require(_presaleStart > 0 && _start > _presaleStart && _end > _start); presaleStart = _presaleStart; start = _start; end = _end; } /* * Internal function that creates and distributes tokens */ function contributeInternal(address _receiver, uint _weiAmount, uint _tokenAmount) internal { require(token.totalSupply().add(_tokenAmount) <= maxCap); token.produceEmeralds(_receiver, _tokenAmount); if (_weiAmount > 0) wallet.transfer(_weiAmount); if (contributors[_receiver] == 0) contributorsCount++; tokensSold = tokensSold.add(_tokenAmount); weiTotal = weiTotal.add(_weiAmount); Contributed(_receiver, _weiAmount, _tokenAmount); } /* * Contributors can claim refund. */ function refund() inState(States.Refunding) { uint weiValue = contributors[msg.sender]; require(weiValue <= loadedRefund && weiValue <= this.balance); msg.sender.transfer(weiValue); contributors[msg.sender] = 0; weiRefunded = weiRefunded.add(weiValue); loadedRefund = loadedRefund.sub(weiValue); Refund(msg.sender, weiValue); } /* * State machine */ function getState() constant returns (States) { if (now < presaleStart) return States.Preparing; if (now >= presaleStart && now < start && weiTotal < weiPresaleMax) return States.Presale; if (now < start && weiTotal >= weiPresaleMax) return States.Waiting; if (now >= start && now < end) return States.Distribution; if (weiTotal >= weiGoal) return States.Success; if (now >= end && weiTotal < weiGoal && loadedRefund == 0) return States.Failure; if (loadedRefund > 0) return States.Refunding; } /* * Calculating token price */ function getTokenAmount(uint _weiAmount) internal constant returns (uint) { uint rate = 1000 * 10 ** 18 / 10 ** token.decimals(); // 1000 EMR = 1 ETH uint tokenAmount = _weiAmount * rate; if (getState() == States.Presale) tokenAmount *= 2; return tokenAmount; } }
minimum wei amount we want to get during token distribution
uint public weiGoal;
10,535,917
[ 1, 15903, 732, 77, 3844, 732, 2545, 358, 336, 4982, 1147, 7006, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 1071, 732, 77, 27716, 31, 10402, 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 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.6; interface IAMB { function messageSender() external view returns (address); function messageSourceChainId() external view returns (uint256); function messageId() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.6; interface IOmniBridge { /** @dev Initiate the bridge operation for some amount of tokens from msg.sender. The user should first call Approve method of the ERC677 token. @param token bridged token contract address. @param _receiver address that will receive the native tokens on the other network. @param _value amount of tokens to be transferred to the other network. */ function relayTokens( address token, address _receiver, uint256 _value ) external; /** @dev Tells the expected token balance of the contract. @param _token address of token contract. @return the current tracked token balance of the contract. */ function mediatorBalance(address _token) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.6; interface ITREEOracle { function update() external returns (bool success); function consult(address token, uint256 amountIn) external view returns (uint256 amountOut); function updated() external view returns (bool); function updateAndConsult(address token, uint256 amountIn) external returns (uint256 amountOut); function blockTimestampLast() external view returns (uint32); function pair() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.6; interface ITREERewards { function notifyRewardAmount(uint256 reward) external; } pragma solidity 0.6.6; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly contract CloneFactory { function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and( eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))) ) } } } // COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Modifications were made to support an IDChain/xDAI address as admin using the Arbitrary Message Bridge (AMB) // Also did linting so it looks nicer pragma solidity 0.6.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IAMB.sol"; contract Timelock { using SafeMath for uint256; modifier onlyAdmin(address admin_) { address actualSender = amb.messageSender(); uint256 sourceL2ChainID = amb.messageSourceChainId(); require( actualSender == admin_, "Timelock::onlyAdmin: L2 call must come from admin." ); require( sourceL2ChainID == l2ChainID, "Timelock::onlyAdmin: L2 call must come from correct chain." ); require( msg.sender == address(amb), "Timelock::onlyAdmin: L1 call must come from AMB." ); _; } event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint256 indexed newDelay); event NewAMB(address indexed newAMB); event NewL2ChainID(uint256 indexed newL2ChainID); event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); uint256 public constant GRACE_PERIOD = 14 days; uint256 public constant MINIMUM_DELAY = 2 days; uint256 public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint256 public delay; bool public admin_initialized; IAMB public amb; uint256 public l2ChainID; mapping(bytes32 => bool) public queuedTransactions; constructor( address admin_, uint256 delay_, address amb_, uint256 l2ChainID_ ) public { require( delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay." ); require( delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay." ); admin = admin_; delay = delay_; admin_initialized = false; amb = IAMB(amb_); l2ChainID = l2ChainID_; } receive() external payable {} function setDelay(uint256 delay_) public { require( msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock." ); require( delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay." ); require( delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay." ); delay = delay_; emit NewDelay(delay_); } function setAMB(address amb_) public { require( msg.sender == address(this), "Timelock::setAMB: Call must come from Timelock." ); require(amb_ != address(0), "Timelock::setAMB: AMB must be non zero."); amb = IAMB(amb_); emit NewAMB(amb_); } function setL2ChainID(uint256 l2ChainID_) public { require( msg.sender == address(this), "Timelock::setL2ChainID: Call must come from Timelock." ); l2ChainID = l2ChainID_; emit NewL2ChainID(l2ChainID_); } function acceptAdmin() public onlyAdmin(pendingAdmin) { admin = pendingAdmin; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require( msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock." ); } else { require( msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin." ); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin_); } function queueTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external onlyAdmin(admin) returns (bytes32) { require( eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external onlyAdmin(admin) { bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external payable onlyAdmin(admin) returns (bytes memory) { bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require( queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued." ); require( getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock." ); require( getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale." ); queuedTransactions[txHash] = false; bool success; bytes memory returnData; if (bytes(signature).length == 0) { // solium-disable-next-line security/no-call-value (success, returnData) = target.call{ value: value }(data); } else { // solium-disable-next-line security/no-call-value (success, returnData) = target.call{ value: value }( abi.encodePacked(bytes4(keccak256(bytes(signature))), data) ); } require( success, "Timelock::executeTransaction: Transaction execution reverted." ); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint256) { // solium-disable-next-line security/no-block-members return block.timestamp; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract TREE is ERC20("tree.finance", "TREE"), Ownable { /** @notice the TREERebaser contract */ address public rebaser; /** @notice the TREEReserve contract */ address public reserve; function initContracts(address _rebaser, address _reserve) external onlyOwner { require(_rebaser != address(0), "TREE: invalid rebaser"); require(rebaser == address(0), "TREE: rebaser already set"); rebaser = _rebaser; require(_reserve != address(0), "TREE: invalid reserve"); require(reserve == address(0), "TREE: reserve already set"); reserve = _reserve; } function ownerMint(address account, uint256 amount) external onlyOwner { _mint(account, amount); } function rebaserMint(address account, uint256 amount) external { require(msg.sender == rebaser); _mint(account, amount); } function reserveBurn(address account, uint256 amount) external { require(msg.sender == reserve); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/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 { /** * @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: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./TREE.sol"; import "./interfaces/ITREEOracle.sol"; import "./TREEReserve.sol"; contract TREERebaser is ReentrancyGuard { using SafeMath for uint256; /** Modifiers */ modifier onlyGov { require(msg.sender == gov, "TREEReserve: not gov"); _; } /** Events */ event Rebase(uint256 treeSupplyChange); event SetGov(address _newValue); event SetOracle(address _newValue); event SetMinimumRebaseInterval(uint256 _newValue); event SetDeviationThreshold(uint256 _newValue); event SetRebaseMultiplier(uint256 _newValue); /** Public constants */ /** @notice precision for decimal calculations */ uint256 public constant PRECISION = 10**18; /** @notice the minimum value of minimumRebaseInterval */ uint256 public constant MIN_MINIMUM_REBASE_INTERVAL = 12 hours; /** @notice the maximum value of minimumRebaseInterval */ uint256 public constant MAX_MINIMUM_REBASE_INTERVAL = 14 days; /** @notice the minimum value of deviationThreshold */ uint256 public constant MIN_DEVIATION_THRESHOLD = 10**16; // 1% /** @notice the maximum value of deviationThreshold */ uint256 public constant MAX_DEVIATION_THRESHOLD = 10**17; // 10% /** @notice the minimum value of rebaseMultiplier */ uint256 public constant MIN_REBASE_MULTIPLIER = 5 * 10**16; // 0.05x /** @notice the maximum value of rebaseMultiplier */ uint256 public constant MAX_REBASE_MULTIPLIER = 10**19; // 10x /** System parameters */ /** @notice the minimum interval between rebases, in seconds */ uint256 public minimumRebaseInterval; /** @notice the threshold for the off peg percentage of TREE price above which rebase will occur */ uint256 public deviationThreshold; /** @notice the multiplier for calculating how much TREE to mint during a rebase */ uint256 public rebaseMultiplier; /** Public variables */ /** @notice the timestamp of the last rebase */ uint256 public lastRebaseTimestamp; /** @notice the address that has governance power over the reserve params */ address public gov; /** External contracts */ TREE public immutable tree; ITREEOracle public oracle; TREEReserve public immutable reserve; constructor( uint256 _minimumRebaseInterval, uint256 _deviationThreshold, uint256 _rebaseMultiplier, address _tree, address _oracle, address _reserve, address _gov ) public { minimumRebaseInterval = _minimumRebaseInterval; deviationThreshold = _deviationThreshold; rebaseMultiplier = _rebaseMultiplier; lastRebaseTimestamp = block.timestamp; // have a delay between deployment and the first rebase tree = TREE(_tree); oracle = ITREEOracle(_oracle); reserve = TREEReserve(_reserve); gov = _gov; } function rebase() external nonReentrant { // ensure the last rebase was not too recent require( block.timestamp > lastRebaseTimestamp.add(minimumRebaseInterval), "TREERebaser: last rebase too recent" ); lastRebaseTimestamp = block.timestamp; // query TREE price from oracle uint256 treePrice = _treePrice(); // check whether TREE price has deviated from the peg by a proportion over the threshold require(treePrice >= PRECISION && treePrice.sub(PRECISION) >= deviationThreshold, "TREERebaser: not off peg"); // calculate off peg percentage and apply multiplier uint256 indexDelta = treePrice.sub(PRECISION).mul(rebaseMultiplier).div(PRECISION); // calculate the change in total supply uint256 treeSupply = tree.totalSupply(); uint256 supplyChangeAmount = treeSupply.mul(indexDelta).div(PRECISION); // rebase TREE // mint TREE proportional to deviation // (1) mint TREE to reserve tree.rebaserMint(address(reserve), supplyChangeAmount); // (2) let reserve perform actions with the minted TREE reserve.handlePositiveRebase(supplyChangeAmount); // emit rebase event emit Rebase(supplyChangeAmount); } /** Utils */ /** * @return price the price of TREE in reserve tokens */ function _treePrice() internal returns (uint256 price) { bool updated = oracle.update(); require(updated || oracle.updated(), "TREERebaser: oracle no price"); return oracle.consult(address(tree), PRECISION); } /** Param setters */ function setGov(address _newValue) external onlyGov { require(_newValue != address(0), "TREEReserve: address is 0"); gov = _newValue; emit SetGov(_newValue); } function setOracle(address _newValue) external onlyGov { require(_newValue != address(0), "TREEReserve: address is 0"); oracle = ITREEOracle(_newValue); emit SetOracle(_newValue); } function setMinimumRebaseInterval(uint256 _newValue) external onlyGov { require( _newValue >= MIN_MINIMUM_REBASE_INTERVAL && _newValue <= MAX_MINIMUM_REBASE_INTERVAL, "TREERebaser: value out of range" ); minimumRebaseInterval = _newValue; emit SetMinimumRebaseInterval(_newValue); } function setDeviationThreshold(uint256 _newValue) external onlyGov { require( _newValue >= MIN_DEVIATION_THRESHOLD && _newValue <= MAX_DEVIATION_THRESHOLD, "TREERebaser: value out of range" ); deviationThreshold = _newValue; emit SetDeviationThreshold(_newValue); } function setRebaseMultiplier(uint256 _newValue) external onlyGov { require( _newValue >= MIN_REBASE_MULTIPLIER && _newValue <= MAX_REBASE_MULTIPLIER, "TREERebaser: value out of range" ); rebaseMultiplier = _newValue; emit SetRebaseMultiplier(_newValue); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.6; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "./TREE.sol"; import "./TREERebaser.sol"; import "./interfaces/ITREERewards.sol"; import "./interfaces/IOmniBridge.sol"; contract TREEReserve is ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; /** Modifiers */ modifier onlyRebaser { require(msg.sender == address(rebaser), "TREEReserve: not rebaser"); _; } modifier onlyGov { require(msg.sender == gov, "TREEReserve: not gov"); _; } /** Events */ event SellTREE(uint256 treeSold, uint256 reserveTokenReceived); event BurnTREE( address indexed sender, uint256 burnTreeAmount, uint256 receiveReserveTokenAmount ); event SetGov(address _newValue); event SetCharity(address _newValue); event SetLPRewards(address _newValue); event SetUniswapPair(address _newValue); event SetUniswapRouter(address _newValue); event SetOmniBridge(address _newValue); event SetCharityCut(uint256 _newValue); event SetRewardsCut(uint256 _newValue); /** Public constants */ /** @notice precision for decimal calculations */ uint256 public constant PRECISION = 10**18; /** @notice Uniswap takes 0.3% fee, gamma = 1 - 0.3% = 99.7% */ uint256 public constant UNISWAP_GAMMA = 997 * 10**15; /** @notice the minimum value of charityCut */ uint256 public constant MIN_CHARITY_CUT = 10**17; // 10% /** @notice the maximum value of charityCut */ uint256 public constant MAX_CHARITY_CUT = 5 * 10**17; // 50% /** @notice the minimum value of rewardsCut */ uint256 public constant MIN_REWARDS_CUT = 5 * 10**15; // 0.5% /** @notice the maximum value of rewardsCut */ uint256 public constant MAX_REWARDS_CUT = 10**17; // 10% /** System parameters */ /** @notice the address that has governance power over the reserve params */ address public gov; /** @notice the address that will store the TREE donation, NEEDS TO BE ON L2 CHAIN */ address public charity; /** @notice the proportion of rebase income given to charity */ uint256 public charityCut; /** @notice the proportion of rebase income given to LPRewards */ uint256 public rewardsCut; /** External contracts */ TREE public immutable tree; ERC20 public immutable reserveToken; TREERebaser public rebaser; ITREERewards public lpRewards; IUniswapV2Pair public uniswapPair; IUniswapV2Router02 public uniswapRouter; IOmniBridge public omniBridge; constructor( uint256 _charityCut, uint256 _rewardsCut, address _tree, address _gov, address _charity, address _reserveToken, address _lpRewards, address _uniswapPair, address _uniswapRouter, address _omniBridge ) public { charityCut = _charityCut; rewardsCut = _rewardsCut; tree = TREE(_tree); gov = _gov; charity = _charity; reserveToken = ERC20(_reserveToken); lpRewards = ITREERewards(_lpRewards); uniswapPair = IUniswapV2Pair(_uniswapPair); uniswapRouter = IUniswapV2Router02(_uniswapRouter); omniBridge = IOmniBridge(_omniBridge); } function initContracts(address _rebaser) external onlyOwner { require(_rebaser != address(0), "TREE: invalid rebaser"); require(address(rebaser) == address(0), "TREE: rebaser already set"); rebaser = TREERebaser(_rebaser); } /** @notice distribute minted TREE to TREERewards and TREEGov, and sell the rest @param mintedTREEAmount the amount of TREE minted */ function handlePositiveRebase(uint256 mintedTREEAmount) external onlyRebaser nonReentrant { // sell remaining TREE for reserveToken uint256 rewardsCutAmount = mintedTREEAmount.mul(rewardsCut).div(PRECISION); uint256 remainingTREEAmount = mintedTREEAmount.sub(rewardsCutAmount); (uint256 treeSold, uint256 reserveTokenReceived) = _sellTREE( remainingTREEAmount ); // handle unsold TREE if (treeSold < remainingTREEAmount) { // the TREE going to rewards should be decreased if there's unsold TREE // to maintain the ratio between charityCut and rewardsCut uint256 newRewardsCutAmount = rewardsCutAmount.mul(treeSold).div(remainingTREEAmount); uint256 burnAmount = remainingTREEAmount.sub(treeSold).add(rewardsCutAmount).sub(newRewardsCutAmount); rewardsCutAmount = newRewardsCutAmount; // burn unsold TREE tree.reserveBurn(address(this), burnAmount); } // send reserveToken to charity uint256 charityCutAmount = reserveTokenReceived.mul(charityCut).div( PRECISION.sub(rewardsCut) ); reserveToken.safeIncreaseAllowance(address(omniBridge), charityCutAmount); omniBridge.relayTokens(address(reserveToken), charity, charityCutAmount); // send TREE to TREERewards tree.transfer(address(lpRewards), rewardsCutAmount); lpRewards.notifyRewardAmount(rewardsCutAmount); // emit event emit SellTREE(treeSold, reserveTokenReceived); } function burnTREE(uint256 amount) external nonReentrant { require(!Address.isContract(msg.sender), "TREEReserve: not EOA"); uint256 treeSupply = tree.totalSupply(); // burn TREE for msg.sender tree.reserveBurn(msg.sender, amount); // give reserveToken to msg.sender based on quadratic shares uint256 reserveTokenBalance = reserveToken.balanceOf(address(this)); uint256 deserveAmount = reserveTokenBalance.mul(amount.mul(amount)).div( treeSupply.mul(treeSupply) ); reserveToken.safeTransfer(msg.sender, deserveAmount); // emit event emit BurnTREE(msg.sender, amount, deserveAmount); } /** Utilities */ /** @notice create a sell order for TREE @param amount the amount of TREE to sell @return treeSold the amount of TREE sold reserveTokenReceived the amount of reserve tokens received */ function _sellTREE(uint256 amount) internal returns (uint256 treeSold, uint256 reserveTokenReceived) { (uint256 token0Reserves, uint256 token1Reserves, ) = uniswapPair .getReserves(); // the max amount of TREE that can be sold such that // the price doesn't go below the peg uint256 maxSellAmount = _uniswapMaxSellAmount( token0Reserves, token1Reserves ); treeSold = amount > maxSellAmount ? maxSellAmount : amount; tree.increaseAllowance(address(uniswapRouter), treeSold); address[] memory path = new address[](2); path[0] = address(tree); path[1] = address(reserveToken); uint256[] memory amounts = uniswapRouter.swapExactTokensForTokens( treeSold, 1, path, address(this), block.timestamp ); reserveTokenReceived = amounts[1]; } function _uniswapMaxSellAmount(uint256 token0Reserves, uint256 token1Reserves) internal view returns (uint256 result) { // the max amount of TREE we can sell brings the price down to the peg // maxSellAmount = (sqrt(R_tree * R_reserveToken) - R_tree) / UNISWAP_GAMMA result = Babylonian.sqrt(token0Reserves.mul(token1Reserves)); if (address(tree) < address(reserveToken)) { // TREE is token0 of the Uniswap pair result = result.sub(token0Reserves); } else { // TREE is token1 of the Uniswap pair result = result.sub(token1Reserves); } result = result.mul(PRECISION).div(UNISWAP_GAMMA); } /** Param setters */ function setGov(address _newValue) external onlyGov { require(_newValue != address(0), "TREEReserve: address is 0"); gov = _newValue; emit SetGov(_newValue); } function setCharity(address _newValue) external onlyGov { require(_newValue != address(0), "TREEReserve: address is 0"); charity = _newValue; emit SetCharity(_newValue); } function setLPRewards(address _newValue) external onlyGov { require(_newValue != address(0), "TREEReserve: address is 0"); lpRewards = ITREERewards(_newValue); emit SetLPRewards(_newValue); } function setUniswapPair(address _newValue) external onlyGov { require(_newValue != address(0), "TREEReserve: address is 0"); uniswapPair = IUniswapV2Pair(_newValue); emit SetUniswapPair(_newValue); } function setUniswapRouter(address _newValue) external onlyGov { require(_newValue != address(0), "TREEReserve: address is 0"); uniswapRouter = IUniswapV2Router02(_newValue); emit SetUniswapRouter(_newValue); } function setOmniBridge(address _newValue) external onlyGov { require(_newValue != address(0), "TREEReserve: address is 0"); omniBridge = IOmniBridge(_newValue); emit SetOmniBridge(_newValue); } function setCharityCut(uint256 _newValue) external onlyGov { require( _newValue >= MIN_CHARITY_CUT && _newValue <= MAX_CHARITY_CUT, "TREEReserve: value out of range" ); charityCut = _newValue; emit SetCharityCut(_newValue); } function setRewardsCut(uint256 _newValue) external onlyGov { require( _newValue >= MIN_REWARDS_CUT && _newValue <= MAX_REWARDS_CUT, "TREEReserve: value out of range" ); rewardsCut = _newValue; emit SetRewardsCut(_newValue); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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"); } } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.6; /** *Submitted for verification at Etherscan.io on 2020-07-17 */ /* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: TREERewards.sol * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, TREEAGES 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 */ import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called internally. */ function _transferOwnership(address newOwner) internal virtual { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } abstract contract IRewardDistributionRecipient is Ownable { address public rewardDistribution; function notifyRewardAmount(uint256 reward) external virtual; modifier onlyRewardDistribution() { require( _msgSender() == rewardDistribution, "Caller is not reward distribution" ); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { require(_rewardDistribution != address(0), "0 input"); rewardDistribution = _rewardDistribution; } } contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakeToken; uint256 private _totalSupply; mapping(address => uint256) private _balances; function _initStakeToken(address _stakeToken) internal { stakeToken = IERC20(_stakeToken); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public virtual { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakeToken.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public virtual { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakeToken.safeTransfer(msg.sender, amount); } } contract TREERewards is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public rewardToken; uint256 public constant DURATION = 7 days; uint256 public constant PRECISION = 10**18; uint256 public starttime; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; bool public initialized; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier checkStart() { require(block.timestamp >= starttime, "not start"); _; } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function init( address _sender, uint256 _starttime, address _stakeToken, address _rewardToken ) public { require(!initialized, "Initialized"); initialized = true; starttime = _starttime; rewardToken = IERC20(_rewardToken); _initStakeToken(_stakeToken); _transferOwnership(_sender); } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(PRECISION) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(PRECISION) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) checkStart { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp > starttime) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } else { rewardRate = reward.div(DURATION); lastUpdateTime = starttime; periodFinish = starttime.add(DURATION); emit RewardAdded(reward); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity 0.6.6; import "./TREERewards.sol"; import "./libraries/CloneFactory.sol"; contract TREERewardsFactory is CloneFactory { address public immutable template; event CreateRewards(address _rewards); constructor(address _template) public { template = _template; } function createRewards( uint256 _starttime, address _stakeToken, address _rewardToken ) external returns (TREERewards) { TREERewards rewards = TREERewards(createClone(template)); rewards.init(msg.sender, _starttime, _stakeToken, _rewardToken); emit CreateRewards(address(rewards)); return rewards; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.6; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/FixedPoint.sol"; import "@uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol"; import "@uniswap/v2-periphery/contracts/libraries/UniswapV2Library.sol"; // fixed window oracle that recomputes the average price for the entire period once every period // note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract UniswapOracle { using FixedPoint for *; uint256 public PERIOD; IUniswapV2Pair public immutable pair; address public immutable token0; address public immutable token1; uint256 public price0CumulativeLast; uint256 public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; bool public initialized; bool public updated; constructor( address factory, address tokenA, address tokenB, uint256 period ) public { IUniswapV2Pair _pair = IUniswapV2Pair( UniswapV2Library.pairFor(factory, tokenA, tokenB) ); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); PERIOD = period; } function init() external { require(!initialized, "UniswapOracle: INITIALIZED"); initialized = true; price0CumulativeLast = pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0) price1CumulativeLast = pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, "UniswapOracle: NO_RESERVES"); // ensure that there's liquidity in the pair } function update() external returns (bool success) { require(initialized, "UniswapOracle: NOT_INITIALIZED"); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update if (timeElapsed < PERIOD) { return false; } // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112( uint224((price0Cumulative - price0CumulativeLast) / timeElapsed) ); price1Average = FixedPoint.uq112x112( uint224((price1Cumulative - price1CumulativeLast) / timeElapsed) ); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; updated = true; return true; } // note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint256 amountIn) external view returns (uint256 amountOut) { if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, "UniswapOracle: INVALID_TOKEN"); amountOut = price1Average.mul(amountIn).decode144(); } } // used in frontend for checking the latest price function updateAndConsult(address token, uint256 amountIn) external returns (uint256 amountOut) { this.update(); return this.consult(token, amountIn); } } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; import './Babylonian.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } pragma solidity >=0.5.0; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '@uniswap/lib/contracts/libraries/FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } pragma solidity >=0.5.0; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import "./SafeMath.sol"; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } pragma solidity =0.6.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } }
solium-disable-next-line security/no-call-value solium-disable-next-line security/no-call-value
function executeTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external payable onlyAdmin(admin) returns (bytes memory) { bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require( queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued." ); require( getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock." ); require( getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale." ); queuedTransactions[txHash] = false; bool success; bytes memory returnData; if (bytes(signature).length == 0) { abi.encodePacked(bytes4(keccak256(bytes(signature))), data) ); } require( success, "Timelock::executeTransaction: Transaction execution reverted." ); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; }
179,259
[ 1, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 1991, 17, 1132, 3704, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 1991, 17, 1132, 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, 225, 445, 1836, 3342, 12, 203, 565, 1758, 1018, 16, 203, 565, 2254, 5034, 460, 16, 203, 565, 533, 745, 892, 3372, 16, 203, 565, 1731, 745, 892, 501, 16, 203, 565, 2254, 5034, 14251, 203, 225, 262, 3903, 8843, 429, 1338, 4446, 12, 3666, 13, 1135, 261, 3890, 3778, 13, 288, 203, 565, 1731, 1578, 2229, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 3299, 16, 460, 16, 3372, 16, 501, 16, 14251, 10019, 203, 565, 2583, 12, 203, 1377, 12234, 14186, 63, 978, 2310, 6487, 203, 1377, 315, 10178, 292, 975, 2866, 8837, 3342, 30, 5947, 13342, 1404, 2118, 12234, 1199, 203, 565, 11272, 203, 565, 2583, 12, 203, 1377, 11902, 4921, 1435, 1545, 14251, 16, 203, 1377, 315, 10178, 292, 975, 2866, 8837, 3342, 30, 5947, 13342, 1404, 5056, 23603, 813, 2176, 1199, 203, 565, 11272, 203, 565, 2583, 12, 203, 1377, 11902, 4921, 1435, 1648, 14251, 18, 1289, 12, 43, 9254, 67, 28437, 3631, 203, 1377, 315, 10178, 292, 975, 2866, 8837, 3342, 30, 5947, 353, 14067, 1199, 203, 565, 11272, 203, 203, 565, 12234, 14186, 63, 978, 2310, 65, 273, 629, 31, 203, 203, 565, 1426, 2216, 31, 203, 565, 1731, 3778, 327, 751, 31, 203, 565, 309, 261, 3890, 12, 8195, 2934, 2469, 422, 374, 13, 288, 203, 3639, 24126, 18, 3015, 4420, 329, 12, 3890, 24, 12, 79, 24410, 581, 5034, 12, 3890, 12, 8195, 3719, 3631, 501, 13, 203, 1377, 11272, 203, 565, 289, 203, 203, 565, 2583, 12, 203, 1377, 2216, 16, 2 ]
./full_match/3/0x0651b43922721aA5452aCE716c47676e435Ab410/sources/NewDebitDollar-v1.sol
* @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) Emits an Approval event. @param spender The address which will spend the funds. @param value The amount of tokens to decrease the allowance by./
function decrease_allowance(address spender, uint256 value) external returns (bool) { require(spender != address(0)); _allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(value); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } ======================================*/ mapping(address => bool) public CustodialStablecoins;
8,111,991
[ 1, 23326, 448, 326, 3844, 434, 2430, 716, 392, 3410, 2935, 358, 279, 17571, 264, 18, 6617, 537, 1410, 506, 2566, 1347, 2935, 67, 63, 67, 87, 1302, 264, 65, 422, 374, 18, 2974, 15267, 2935, 460, 353, 7844, 358, 999, 333, 445, 358, 4543, 576, 4097, 261, 464, 2529, 3180, 326, 1122, 2492, 353, 1131, 329, 13, 7377, 1282, 392, 1716, 685, 1125, 871, 18, 225, 17571, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 460, 1021, 3844, 434, 2430, 358, 20467, 326, 1699, 1359, 635, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 20467, 67, 5965, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 87, 1302, 264, 480, 1758, 12, 20, 10019, 203, 3639, 389, 5965, 1359, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 389, 5965, 1359, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 8009, 1717, 12, 1132, 1769, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 389, 5965, 1359, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 19226, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 422, 4428, 894, 5549, 203, 377, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 385, 641, 369, 649, 30915, 71, 9896, 31, 203, 377, 203, 377, 203, 377, 203, 377, 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 ]
// Правила для изменения достоверности распознавания конкретных словоформ в русском словаре. // Обычное предназначение этих правил - изменить равновероятные распознавания // омонимичных форм жаль(безличный глагол)>жаль(императив), // либо повлиять на выбор многословных форм в противовес // выбору отдельных слов: [слева от] <--> [слева] [от] wordform_score смеси{глагол}=-10 // из чего смеси ? wordform_score ага{ существительное }=-5 wordform_score малышки{ род:муж }=-10 // Малышки будут прыгать от радости! wordform_score мебели{ число:мн }=-10 // Рвали обивку мебели. wordform_score начало{ глагол }=-6 // Сегодня неплохое начало. wordform_score воды{ род:муж }=-10 // мы приплывем в их воды wordform_score скалы{ род:муж }=-10 // там должны быть скалы wordform_score кафе{ род:муж }=-10 // в кафе wordform_score скалы{ род:муж }=-10 // волны бились о скалы wordform_score кроме{ существительное }=-10 // кроме этой вот ягоды wordform_score жилище{ род:жен }=-10 // в ее жилище wordform_score почитай{ наречие }=-4 // Ты лучше почитай. wordform_score без{ существительное }=-10 // Без кладовок и гардеробных комнат wordform_score бренды{род:жен}=-10 // Вообще-то перечисленные бренды давно уже избавились от налета местечковости. wordform_score ярки{ существительное }=-10 // Глаза его были ярки wordform_score голубей{ прилагательное }=-1 // Ты будешь Петькиных голубей подманивать. wordform_score дело{ глагол }=-10 // Дело наше лесное. wordform_score правило{ глагол }=-5 // Такое наше правило... wordform_score карусель{ глагол }=-10 // Карусель начинается мировая. wordform_score Германии{ число:мн }=-10 // В Германии беженец спрыгнул с поезда из-за угрозы депортации в Италию wordform_score бусы { род:муж }=-5 // Весенние бусы персикового дерева разорвались. wordform_score суеты { число:мн }=-10 // Завершился 26-ой тур российской премьер-лиги. wordform_score метель { глагол }=-10 // На улице метель. //wordform_score по-видимому { наречие }=2 //wordform_score по-видимому { вводное }=2 // Ему, по-видимому, не терпелось начать. wordform_score энергии { существительное число:мн }=-2 // Ему и сейчас не занимать энергии. wordform_score таки { существительное }=-5 // Ему-таки удалось ее завести. wordform_score выстуживаем { прилагательное }=-1 wordform_score уполномочиваем { прилагательное }=-1 wordform_score кормим { прилагательное }=-1 wordform_score чиним { прилагательное }=-1 wordform_score заводим { прилагательное }=-1 wordform_score периодизируем { прилагательное }=-1 wordform_score завозим { прилагательное }=-1 wordform_score дегустируем { прилагательное }=-1 wordform_score увозим { прилагательное }=-1 wordform_score вообразим { прилагательное }=-1 wordform_score дробим { прилагательное }=-1 wordform_score таскаем { прилагательное }=-1 wordform_score превозносим { прилагательное }=-1 wordform_score потопляем { прилагательное }=-1 wordform_score волочим { прилагательное }=-1 wordform_score перевиваем { прилагательное }=-1 wordform_score засекречиваем { прилагательное }=-1 wordform_score храним { прилагательное }=-1 wordform_score уносим { прилагательное }=-1 wordform_score предводим { прилагательное }=-1 wordform_score мыслим { прилагательное }=-1 wordform_score проходим { прилагательное }=-1 wordform_score влачим { прилагательное }=-1 wordform_score творим { прилагательное }=-1 wordform_score сравним { прилагательное }=-1 wordform_score измерим { прилагательное }=-1 wordform_score душим { прилагательное }=-1 wordform_score сопоставим { прилагательное }=-1 wordform_score досягаем { прилагательное }=-1 wordform_score травим { прилагательное }=-1 wordform_score благоволим { прилагательное }=-1 wordform_score убеждаем { прилагательное }=-1 wordform_score слышим { прилагательное }=-1 wordform_score слышим { прилагательное }=-1 wordform_score подгружаем { прилагательное }=-1 wordform_score укрупняем { прилагательное }=-1 wordform_score взымаем { прилагательное }=-1 wordform_score зашвыриваем { прилагательное }=-1 wordform_score зависим { прилагательное }=-1 wordform_score ощутим { прилагательное }=-1 wordform_score громим { прилагательное }=-1 wordform_score застраиваем { прилагательное }=-1 wordform_score исправим { прилагательное }=-1 wordform_score выполним { прилагательное }=-1 wordform_score производим { прилагательное }=-1 wordform_score втемяшиваем { прилагательное }=-1 wordform_score содержим { прилагательное }=-1 wordform_score подносим { прилагательное }=-1 wordform_score вкраиваем { прилагательное }=-1 wordform_score беспокоим { прилагательное }=-1 wordform_score взнуздываем { прилагательное }=-1 wordform_score носим { прилагательное }=-1 wordform_score любим { прилагательное }=-1 wordform_score доносим { прилагательное }=-1 wordform_score уценяем { прилагательное }=-1 wordform_score ненавидим { прилагательное }=-1 wordform_score судим { прилагательное }=-1 wordform_score вмораживаем { прилагательное }=-1 wordform_score ввозим { прилагательное }=-1 wordform_score подвозим { прилагательное }=-1 wordform_score развозим { прилагательное }=-1 wordform_score привозим { прилагательное }=-1 wordform_score реструктурируем { прилагательное }=-1 wordform_score реструктурируем { прилагательное }=-1 wordform_score подтопляем { прилагательное }=-1 wordform_score перезаписываем { прилагательное }=-1 wordform_score ценим { прилагательное }=-1 wordform_score национализируем { прилагательное }=-1 wordform_score национализируем { прилагательное }=-1 wordform_score проминаем { прилагательное }=-1 wordform_score переносим { прилагательное }=-1 wordform_score возводим { прилагательное }=-1 wordform_score проницаем { прилагательное }=-1 wordform_score проводим { прилагательное }=-1 wordform_score проводим { прилагательное }=-1 wordform_score таим { прилагательное }=-1 wordform_score синхронизируем { прилагательное }=-1 wordform_score вводим { прилагательное }=-1 wordform_score гоним { прилагательное }=-1 wordform_score разделим { прилагательное }=-1 wordform_score ввариваем { прилагательное }=-1 wordform_score бороздим { прилагательное }=-1 wordform_score воспоминаем { прилагательное }=-1 wordform_score руководим { прилагательное }=-1 wordform_score сносим { прилагательное }=-1 wordform_score разносим { прилагательное }=-1 wordform_score стандартизируем { прилагательное }=-1 wordform_score терпим { прилагательное }=-1 wordform_score выносим { прилагательное }=-1 wordform_score выносим { прилагательное }=-1 wordform_score боготворим { прилагательное }=-1 wordform_score клоним { прилагательное }=-1 wordform_score прозываем { прилагательное }=-1 wordform_score привносим { прилагательное }=-1 wordform_score соизмерим { прилагательное }=-1 wordform_score компилируем { прилагательное }=-1 wordform_score централизуем { прилагательное }=-1 wordform_score упаковываем { прилагательное }=-1 wordform_score возбудим { прилагательное }=-1 wordform_score отделим { прилагательное }=-1 wordform_score ограбляем { прилагательное }=-1 wordform_score объясним { прилагательное }=-1 wordform_score наводим { прилагательное }=-1 wordform_score подводим { прилагательное }=-1 wordform_score исполним { прилагательное }=-1 wordform_score вычислим { прилагательное }=-1 wordform_score монетизируем { прилагательное }=-1 wordform_score отряжаем { прилагательное }=-1 wordform_score разъединим { прилагательное }=-1 wordform_score заменим { прилагательное }=-1 wordform_score охаиваем { прилагательное }=-1 wordform_score растворим { прилагательное }=-1 wordform_score наносим { прилагательное }=-1 wordform_score уничтожим { прилагательное }=-1 wordform_score томим { прилагательное }=-1 wordform_score заполним { прилагательное }=-1 wordform_score сводим { прилагательное }=-1 wordform_score выводим { прилагательное }=-1 wordform_score перевозим { прилагательное }=-1 wordform_score взаимозаменяем { прилагательное }=-1 wordform_score поносим { прилагательное }=-1 wordform_score вверстываем { прилагательное }=-1 wordform_score воспроизводим { прилагательное }=-1 wordform_score вывозим { прилагательное }=-1 wordform_score прорежаем { прилагательное }=-1 wordform_score дренируем { прилагательное }=-1 wordform_score разграбляем { прилагательное }=-1 wordform_score обеззараживаем { прилагательное }=-1 wordform_score тесним { прилагательное }=-1 wordform_score вносим { прилагательное }=-1 wordform_score разрешим { прилагательное }=-1 wordform_score подбодряем { прилагательное }=-1 wordform_score уловим { прилагательное }=-1 wordform_score вдергиваем { прилагательное }=-1 wordform_score автопилотируем { прилагательное }=-1 wordform_score автопилотируем { прилагательное }=-1 wordform_score воссоединяем { прилагательное }=-1 wordform_score фондируем { прилагательное }=-1 wordform_score зрим { прилагательное }=-1 wordform_score допустим { прилагательное }=-1 wordform_score преподносим { прилагательное }=-1 wordform_score устраним { прилагательное }=-1 wordform_score устрашим { прилагательное }=-1 wordform_score поправим { прилагательное }=-1 wordform_score нарезаем { прилагательное }=-1 wordform_score значим { прилагательное }=-1 wordform_score истребим { прилагательное }=-1 wordform_score окормляем { прилагательное }=-1 wordform_score воплотим { прилагательное }=-1 wordform_score будоражим { прилагательное }=-1 wordform_score тревожим { прилагательное }=-1 wordform_score применим { прилагательное }=-1 wordform_score дактилоскопируем { прилагательное }=-1 wordform_score дактилоскопируем { прилагательное }=-1 wordform_score браним { прилагательное }=-1 wordform_score провозим { прилагательное }=-1 wordform_score чтим { прилагательное }=-1 wordform_score приложим { прилагательное }=-1 wordform_score повторим { прилагательное }=-1 wordform_score вменяем { прилагательное }=-1 wordform_score раздробляем { прилагательное }=-1 wordform_score льготируем { прилагательное }=-1 wordform_score перезаправляем { прилагательное }=-1 wordform_score удовлетворим { прилагательное }=-1 wordform_score отводим { прилагательное }=-1 wordform_score переводим { прилагательное }=-1 wordform_score утапливаем { прилагательное }=-1 wordform_score предотвратим { прилагательное }=-1 wordform_score тормозим { прилагательное }=-1 wordform_score вербализуем { прилагательное }=-1 wordform_score тостуем { прилагательное }=-1 wordform_score разводим { прилагательное }=-1 wordform_score уводим { прилагательное }=-1 wordform_score искореним { прилагательное }=-1 wordform_score протапливаем { прилагательное }=-1 wordform_score изготавливаем { прилагательное }=-1 wordform_score изъясним { прилагательное }=-1 wordform_score употребим { прилагательное }=-1 wordform_score разложим { прилагательное }=-1 wordform_score возносим { прилагательное }=-1 wordform_score проносим { прилагательное }=-1 wordform_score предвидим { прилагательное }=-1 wordform_score полимеризуем { прилагательное }=-1 wordform_score полимеризуем { прилагательное }=-1 wordform_score исчислим { прилагательное }=-1 wordform_score погрешим { прилагательное }=-1 wordform_score совместим { прилагательное }=-1 wordform_score впериваем { прилагательное }=-1 wordform_score приносим { прилагательное }=-1 wordform_score доводим { прилагательное }=-1 wordform_score заносим { прилагательное }=-1 wordform_score вытаращиваем { прилагательное }=-1 wordform_score обоготворяем { прилагательное }=-1 wordform_score наметаем { прилагательное }=-1 wordform_score делим { прилагательное }=-1 wordform_score хвалим { прилагательное }=-1 wordform_score излечим { прилагательное }=-1 wordform_score обратим { прилагательное }=-1 wordform_score уязвим { прилагательное }=-1 wordform_score определим { прилагательное }=-1 wordform_score произносим { прилагательное }=-1 wordform_score возобновим { прилагательное }=-1 wordform_score соотносим { прилагательное }=-1 wordform_score победим { прилагательное }=-1 wordform_score раним { прилагательное }=-1 wordform_score отличим { прилагательное }=-1 wordform_score прокачиваем { прилагательное }=-1 wordform_score рейтингуем { прилагательное }=-1 wordform_score растравляем { прилагательное }=-1 wordform_score коров { род:муж } = -2 // Без коров мужчины погибли бы. wordform_score ангел { род:жен } = -2 // А мисс Уиллоу была просто ангел. wordform_score слаб { глагол } = -1 // Просто ты слаб! //wordform_score писал { stress:"п^исал" } = -1 // Державин писал: //wordform_score писала { stress:"п^исала" } = -1 wordform_score сердит { глагол } = -1 // Он очень сердит. wordform_score ребят { падеж:зват } = -1 // Ребят пора вернуть wordform_score помочь { существительное } = -10 // мы хотим вам помочь wordform_score вон { существительное } = -1 // Я вон зарабатываю. wordform_score скалами { род:муж } = -5 // Миновав Море Акул, путешественники оказались над Крабьими Скалами. wordform_score воды { род:муж } = -5 // выпить воды wordform_score воде { род:муж } = -5 // рожать в воде wordform_score лук { род:жен } = -5 // возьми с собой лук wordform_score базе { род:муж } = -5 // заправлять на базе wordform_score порошки { род:жен } = -5 // Порошки не помогают... wordform_score обезвреживания { число:мн } = -5 // Разработали план обезвреживания. wordform_score трех { существительное } = -10 // Считаю до трех. wordform_score метель { глагол } = -10 // На улице метель. wordforms_score городской { существительное }=-1 // Существуют городские правила, касающиеся этих процедур. wordforms_score утесать {глагол}=-5 // Я утешу тебя. wordforms_score примереть {глагол}=-5 // Внутри пример wordforms_score запоить {глагол}=-5 // Я запою wordforms_score новое { существительное }=-5 // Начинаются поиски новых приемов, новых методов. wordforms_score просек { существительное }=-5 // Матросы переползали просеку. wordforms_score прививок { существительное }=-10 wordforms_score полок { существительное род:муж }=-5 // Началась переправа полков. wordforms_score уток { существительное род:муж }=-10 wordforms_score юр { существительное }=-10 wordforms_score наркотика { существительное род:жен }=-10 // Одно время она даже пыталась бросить наркотики wordforms_score полян { существительное род:муж }=-10 wordforms_score полянин { существительное род:муж }=-10 wordforms_score чужой { существительное }=-5 // голос ее стал чужим wordforms_score живой { существительное }=-5 // но оно было живым! wordforms_score пяток { существительное }=-5 // сверкать пятками wordforms_score ложок { существительное }=-5 // звякнуть ложками wordforms_score костра { существительное }=-5 // сжечь на костре wordforms_score роить { глагол }=-10 // Я рою траншеи wordforms_score ситце { род:ср }=-10 // шить из ситца wordforms_score взяток { существительное }=-10 // Врач попался на взятке wordforms_score сило { существительное }=-10 // Оставить в силе закон. wordforms_score покадить { глагол }=-5 // Я после покажу... wordforms_score выло { существительное }=-5 // Як не выл больше. wordforms_score вылезть { глагол }=-1 // Я медленно вылез. wordforms_score лунь { существительное }=-1 // Астронавты смогут оставаться на Луне в течение недели wordforms_score закроить { глагол }=-1 // Я потом закрою. wordforms_score вылезть { глагол }=-1 // Машинист вылез. wordforms_score охаять { глагол }=-1 // Кто охает? wordforms_score покадить { глагол }=-1 // Я покажу! wordforms_score ила { существительное род:жен }=-5 // Я раскопал ил wordforms_score ос { существительное род:муж }=-5 // В воздухе гудели мухи и осы. wordforms_score прикроить { глагол }=-2 // Атакуй, прикрою. wordforms_score ох { существительное }=-2 // Ей это ох как не нравилось. wordforms_score кровяный { прилагательное }=-2 // Стимулирует кровообращение и снижает кровяное давление. wordforms_score жило { существительное }=-5 // Именно так выглядит обычный кварц рудных жил. wordforms_score крон { существительное } =-5 // Видите эти могучие кроны, тяжелые плоды? wordforms_score утюжка { существительное }=-5 wordforms_score нар { существительное }=-2 wordforms_score подбора { существительное }=-10 wordforms_score кормило { существительное }=-10 wordforms_score дубка { существительное }=-2 // Сам горб порос крепкими дубками. wordforms_score кода { существительное }=-5 // Серые ячейки указывают на неназначенные коды wordforms_score песнь { существительное }=-1 // Проводится круглогодичный конкурс бардовской песни. wordforms_score тоника { существительное }=-10 wordforms_score рака { существительное }=-10 wordforms_score бахчевый { прилагательное }=-5 // Особое внимание уделялось бахчевым культурам. wordforms_score нецелевый { прилагательное }=-5 // Процветало нецелевое использование этих средств. wordforms_score запасный { прилагательное }=-5 // Пятигорский вокзал был запасным вариантом. wordforms_score бредовой { прилагательное }=-5 // Первая стопка содержала бредовые работы. wordforms_score меньшой { прилагательное }=-5 // Такие передачи имеют меньшую аудиторию. wordforms_score меховый { прилагательное }=-5 // Летняя распродажа меховых изделий продолжается! wordforms_score заводский { прилагательное }=-10 // Существует заводская группа внутренних аудиторов. wordforms_score щенка { существительное }=-10 // Продаются красивые щенки йоркширского терьера. wordforms_score кур { существительное }=-10 wordforms_score любый { прилагательное }=-10 // Для него любая власть является раздражителем. wordforms_score ванный { прилагательное }=-1 // большая ванная wordforms_score плавной { прилагательное }=-10 // Такая конструкция обеспечивает плавное перемещение wordforms_score санатория { существительное }=-10 wordforms_score шпалер { существительное }=-10 wordforms_score хромый { прилагательное }=-5 // Волшебный лепесток излечивает хромого мальчика. wordforms_score газа { существительное }=-1 // Раскаленные газы с чудовищной силой вырываются wordforms_score рейки { род:ср }=-10 // Многочисленные рейки стягивала стальная проволока. wordforms_score протяжной { прилагательное }=-5 // Каменные своды отозвались протяжным эхом. wordforms_score страстной { прилагательное }=-2 // Страстная любовь вызывает страстную борьбу. wordforms_score дневный { прилагательное }=-2 // Дневная суета сменилась полной тишиной. wordforms_score хромый { прилагательное }=-2 // Гони эту свору хромого горбуна! wordforms_score восковой { прилагательное }=-5 // Восковые свечи разливали мягкое сияние. wordforms_score угловый { прилагательное }=-5 // Угловая камера записала этот момент. wordforms_score пестрить { глагол }=-10 // Мировая пресса пестрит сенсационными сообщениями. wordforms_score чина { существительное }=-5 // Это требование поддержали высшие чины. wordforms_score языковый { прилагательное }=-5 wordforms_score половый { прилагательное }=-5 // Переполненный желудок затрудняет половой акт. wordforms_score шампанский { прилагательное }=-5 wordforms_score замок { глагол }=-10 // Замок небольшой и необычный. wordforms_score синоптика { существительное }=-5 // Русский сухогруз утопили турецкие синоптики. wordforms_score корректив { существительное род:муж }=-10 // Президентские выборы вносят определенные коррективы. wordforms_score поджога { существительное род:жен }=-10 // Умышленные поджоги стали доходным бизнесом. wordforms_score матерь { существительное }=-1 wordforms_score плюсовый { прилагательное }=-1 wordforms_score экой { прилагательное }=-1 // Экую несуразицу плетет этот мужик. wordforms_score овсяной { прилагательное }=-5 // Сморщенный чиновник жует овсяную лепешку. wordforms_score хмельный { прилагательное }=-1 // Остался ровный шелест хмельных кипарисов. wordforms_score спазма { существительное }=-10 // Пустой желудок разрывали болезненные спазмы. wordforms_score мазка { существительное }=-10 // Замельтешили нервные мазки ярких красок... wordforms_score громовый { прилагательное }=-5 // Эти вспышки сопровождались громовыми ударами. wordforms_score зарев { существительное }=-10 // Длинные пальцы налились красноватым заревом. wordforms_score шара { существительное }=-5 // Латунные шары заполнялись керосиновой смесью. wordforms_score корн { существительное }=-5 // в корне мандрагоры содержится наркотический сок wordforms_score справа { существительное }=-10 // Справа Дэни разглядела маленькое каменное святилище. wordforms_score теля { существительное }=-5 // Было чувство клаустрофобии в собственном теле. wordforms_score коленной { прилагательное }=-5 // 26-летний футболист получил растяжение коленного сустава. wordforms_score полом { существительное }=-5 // Бойцы рыли под полом окопы. wordforms_score бород { существительное }=-5 // Елена просит молодого мужа сбрить бороду. wordform_score присутствия { число:мн }=-5 // // Ей стало не хватать его присутствия. wordform_score косы { род:муж число:мн }=-10 // Ее косы были убраны под шапку. wordform_score обожания { число:мн }=-10 // Изливают любвеобильные лучи обожания wordform_score смелости { число:мн }=-10 // Ей просто недоставало смелости его сделать. wordform_score ясности { число:мн }=-10 // Черные ящики не добавили ясности. wordform_score с { частица }=-2 // // Загадали желания – ждем-с! wordform_score "ей-богу"{} = 10 // Ей-богу, отлично выйдет. wordform_score дыхания { число:мн }=-2 // Ее подключили к аппарату искусственного дыхания. wordform_score реставрации { число:мн }=-2 // Ее не ремонтировали со времен Реставрации. wordform_score бересты { число:мн }=-10 // Сверху настелили большие куски бересты. wordform_score охоты { число:мн }=-10 // Сезон охоты откроют 25 августа. wordform_score развития { существительное число:мн }=-10 // В Чувашии обсуждают проблемы инновационного развития регионов wordform_score наглости { существительное число:мн }=-10 // противопоставить наглости wordform_score еды { существительное число:мн }=-5 // хозяин должен дать еды wordform_score безопасности { существительное число:мн }=-5 // Его обвинили в пренебрежении вопросами безопасности. wordform_score выдержки { существительное число:мн }=-5 // Если хватит выдержки... wordform_score истерик { существительное }=-2 // И хватит истерик! wordform_score послезавтра { существительное }=-5 // Послезавтра утром проверю... wordform_score дискриминации { число:мн }=-5 // Его называли анахронизмом и признаком дискриминации. wordform_score полиции { число:мн }=-5 // Его доставили в 20-й отдел полиции. wordform_score уверенности { число:мн }=-10 // Его немое обожание придавало Анне уверенности. wordform_score насилия { число:мн }=-5 // А насилия Рекс никогда не совершит. wordform_score болтовни { число:мн }=-10 // А теперь хватит болтовни, Кейн. wordform_score оружия { число:мн }=-10 // А Филип вообще не любит оружия. wordform_score внимания { число:мн }=-10 // А на брата не обращай внимания. wordform_score бытия { число:мн }=-10 // Имеют телесную форму предшествовавшего бытия. wordform_score сочувствия { число:мн }=-5 // А вот Мария действительно заслуживает сочувствия. wordform_score разнообразия { число:мн }=-5 // Болото хотело разнообразия в компании. wordform_score ним { существительное }=-5 // А вместе с ним и свою душу. wordform_score ник { глагол }=-5 // А ты как думаешь, Ник? wordform_score тете { одуш:неодуш }=-1 // А перед этим послал тете цветы. wordform_score гораздо { прилагательное }=-5 // А кажется, что гораздо больше. wordform_score Калифорнии { число:мн }=-10 // А в Калифорнии сейчас цветет мимоза. wordform_score замок { глагол }=-10 // А на краю леса красивый замок. wordform_score мирке { род:жен }=-5 // В их мирке вдруг оказался третий. wordform_score жалости { число:мн }=-5 // В этом деле не знают жалости. wordform_score орала { существительное }=-5 // Я била подушки и орала в ярости. wordform_score яркости { число:мн }=-2 // Второй цвет добавляет яркости и выразительности. wordform_score выразительности { число:мн }=-10 // Второй цвет добавляет яркости и выразительности. wordform_score македонии { число:мн }=-10 // Встретились главы МИД России и Македонии. wordform_score бочками { род:муж }=-5 // Грузить апельсины бочками? wordform_score полдня { существительное }=-5 // Полдня шел дождь. wordform_score пол { падеж:род }=-5 // Меряю шагами пол. wordform_score правей { глагол }=-10 // Еще чуть правей... wordform_score чуточку { существительное }=-10 // Самолет чуточку подбросило. wordform_score правосудья { число:мн }=-10 // Жид хочет правосудья wordform_score единства { число:мн }=-10 // Партия хочет единства. wordform_score счастья { число:мн }=-10 // Все хотят счастья. wordform_score агрессии { число:мн }=-10 // Фашизм хочет агрессии?.. wordform_score горючки { число:мн }=-10 // Не хватило горючки. wordform_score усмирения { число:мн }=-10 // Потребовать усмирения Петрограда. wordform_score метель { глагол }=-15 // На улице метель. wordform_score ясней { глагол }=-10 // Куда уж ясней. wordform_score штурману { глагол }=-10 // Штурману тоже трудно. wordform_score целиком { существительное }=-10 // Скука съела целиком. wordform_score хмелю { глагол }=-10 wordform_score четкой { существительное }=-2 // Работа персонала была четкой wordform_score милую { глагол }=-10 wordform_score гордости { число:мн }=-10 // Есть другие предметы, достойные гордости. wordform_score тих { глагол }=-10 wordform_score инфраструктуры { число:мн }=-2 // РАЗРАБОТАЮТ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ЭЛЕКТРОННОЙ ИНФРАСТРУКТУРЫ. wordform_score ангелы { род:жен }=-5 wordform_score большие { СТЕПЕНЬ:СРАВН }=-10 // большие отели wordform_score больших { СТЕПЕНЬ:СРАВН }=-10 wordform_score большим { СТЕПЕНЬ:СРАВН }=-10 wordform_score большими { СТЕПЕНЬ:СРАВН }=-10 wordform_score физики { род:жен } =-5 // Волгоградские Физики совершили научную революцию. wordform_score хорошей { глагол }=-10 // хорошей душевой кабиной wordform_score стиле { существительное род:ср }=-2 // Продам свадебное платье в греческом стиле wordform_score молока { род:жен падеж:им }=-2 wordform_score Турции { число:мн }=-5 // В Турции муллы провозглашают священную войну. wordform_score гости { глагол }=-5 // В саду могут оказаться и гости. wordform_score администрации { число:мн }=-5 // Структуру администрации Краснодара изменят wordform_score горячим { глагол }=-5 wordform_score свежую { глагол }=-5 // свежую рыбу wordform_score голубой { существительное }=-10 // за дверью жил голубой лев wordform_score фанту { род:муж }=-5 wordform_score фанте { род:муж }=-5 wordform_score баню { ГЛАГОЛ }=-5 wordform_score бань { ГЛАГОЛ }=-5 wordform_score сласти { ГЛАГОЛ }=-10 wordform_score сыр { ПРИЛАГАТЕЛЬНОЕ }=-5 wordform_score сыра { ПРИЛАГАТЕЛЬНОЕ }=-5 wordform_score сыры { ПРИЛАГАТЕЛЬНОЕ }=-5 wordform_score альбом { ПАДЕЖ:ТВОР }=-5 // По запросу могу показать альбом. wordform_score хоре { падеж:предл одуш:одуш }=-5 // подпевать в церковном хоре wordform_score Европы { число:мн }=-5 // Ее считали прекраснейшей женщиной Европы. wordform_score свежую { глагол }=-6 // свежую форель wordform_score содействия { число:мн }=-5 wordform_score общества { число:мн }=-1 // Индивидуальную честность связали с прогрессивностью общества wordform_score подготовки { число:мн }=-5 // Процесс подготовки спутника к запуску уместили в короткий видеоролик wordform_score недвижимости { число:мн }=-10 // Тест: способны ли вы отличить рекламу недвижимости от рекламы презервативов? wordform_score родины { число:мн }=-2 // Кандидата «Родины» уличили в получении поддельного военного билета wordform_score защиты { число:мн }=-2 // Google просит защиты у Аркадия Дворковича wordform_score освобождения { число:мн }=-5 // В Болгарии отпраздновали годовщину освобождения от османского ига wordform_score веры { число:мн }=-5 // Папу Римского призвали отказаться от догмата своей непогрешимости в вопросах веры wordforms_score гнома { существительное }=-10 // Но гномы начали погоню wordform_score рада { существительное }=-2 wordform_score полон { существительное }=-10 // а этот полон ненависти wordform_score Марин { существительное }=-2 // Алла отпустила Марину wordforms_score снимка { существительное }=-5 wordforms_score ям { существительное }=-5 wordforms_score купа { существительное }=-5 // мы нашли в его купе wordforms_score половый { прилагательное }=-5 wordforms_score теста { существительное }=-5 // выявляться тестами wordforms_score гриба { существительное }=-5 // отравиться грибами wordforms_score босый { прилагательное }=-5 // ноги ее были босые wordforms_score арен { существительное }=-5 wordforms_score плат { существительное }=-5 wordforms_score теста { существительное род:жен }=-5 wordforms_score бара { существительное род:жен }=1 // праздновать в баре wordform_score погиб { существительное }=-5 wordforms_score хора { существительное }=-5 wordforms_score дворовой { прилагательное }=-5 wordforms_score сводной { прилагательное }=-5 wordforms_score шпор { существительное }=-5 wordform_score сдачи { число:мн }=-2 // Сдачи не надо. wordforms_score комара { существительное }=-5 wordforms_score бара { существительное }=-5 wordforms_score теста { существительное }=-5 wordforms_score венка { существительное }=-5 wordforms_score метода { существительное }=-5 wordforms_score мор { существительное }=-5 wordforms_score мора { существительное }=-5 // Море достаточно холодное wordform_score трое { существительное }=-5 // трое из мира людей wordform_score повезло { глагол }=-2 // - Не повезло тебе. wordforms_score распоряженье { существительное }=-5 // Полицейские стали ждать дальнейших распоряжений. wordforms_score варианта { существительное род:жен }=-10 // Для разных ситуаций есть предпочтительные варианты. wordforms_score лангуста { существительное }=-10 // В рыбном купила огромного сырокопченого лангуста. wordforms_score верховый { прилагательное }=-5 // Бывало, возьмут верховых лошадей и уедут в поле. wordforms_score об { существительное }=-10 wordforms_score слушанье { существительное }=-5 // Регламент проведения публичных слушаний утверждается постановлением городского парламента. wordforms_score леса { существительное }=-5 // В алтайских лесах истребили сибирского коконопряда, объедающего хвою wordforms_score рельса { существительное }=-1 // В основном были подорваны рельсы на второстепенных запасных путях. wordforms_score перекрытье { существительное }=-5 // Лишь в одной части здания перекрытия оказались бетонными. wordforms_score бракосочетанье { существительное }=-5 // Но в понедельник во Дворце бракосочетания был выходной. wordforms_score благополучье { существительное } =-5 // В полном благополучии путешественники достигли Вефиля. wordforms_score лет { род:муж }=-5 // Летом в этой бухте собиралась целая флотилия яхт. wordforms_score снов { существительное }=-10 wordforms_score така { существительное }=-5 // Сигнал бедствия от лыжницы так и не поступил. wordforms_score корпусный { прилагательное }=-5 // Снаряд выпустила наша батарея 5-го корпусного артиллерийского полка. wordforms_score окружный { прилагательное }=-5 // В Агинском округе началась внеочередная сессия окружной думы. wordforms_score входный { прилагательное }=-5 // Для делегатов напечатали специальные входные билеты. wordforms_score образной { прилагательное }=-5 // Образное выражение, однако, отражает реальную жизнь. wordforms_score окружный { прилагательное }=-5 // Финансирование осуществлялось из окружного бюджета. wordforms_score дверный { прилагательное }=-5 wordforms_score личной{ прилагательное }=-5 // - А ты пробовал концентрировать свои личные мысли? wordforms_score основный{ прилагательное }=-5 // Основные "боевые" мероприятия проходят в Самаре. wordforms_score мирной{ прилагательное }=-5 // Уже в мирное время миссии тачали хорошие сапоги; wordforms_score ЧЕСТНОЙ{ прилагательное }=-5 // Это было хорошее, честное, благородное желание. wordforms_score РОДНЫЙ{ прилагательное }=-5 // Израильские танкисты приняли меня как родного. wordforms_score назначенье{ существительное }=-5 // В администрации Алтайского края произошел ряд отставок и назначений wordforms_score кадра{ существительное }=-5 wordforms_score перекрытье{ существительное }=-5 // Лишь в одной части здания перекрытия оказались бетонными. wordforms_score увечье{ существительное }=-5 // Жертва аварии скончалась в больнице от полученных увечий. wordforms_score исключенье{ существительное }=-5 // Однако из этого правила существует несколько исключений. wordforms_score подкрепленье{ существительное }=-5 // При этом используется вероятностная схема подкреплений. wordforms_score нет{ существительное }=-5 // решение жениться или нет можешь принять только ты сам. wordforms_score признанье{ существительное }=-5 // wordforms_score втора{ существительное }=-5 wordforms_score настроенье{ существительное }=-5 // Но антироссийских настроений вы в Грузии не найдете. wordforms_score заседанье{ существительное }=-5 // Семеро акционеров не были допущены в зал заседаний. wordforms_score сбора{ существительное }=-5 // В ближайшее время Денис улетает на очередные сборы. wordforms_score предложенье{ существительное }=-5 // Вячеслав Евгеньевич готовит свой пакет предложений. wordforms_score свитка{ существительное }=-5 // В кумранских свитках нередко встречается тайнопись wordforms_score носка{ существительное }=-5 // Из-под подола выглядывали белые спортивные носки. wordforms_score дыханье{ существительное }=-5 // При виде обнажившихся грудей перехватило дыхание. wordforms_score усилье{ существительное }=-5 // Бесконечная борьба требовала беспрестанных усилий. wordforms_score помещенье{ существительное }=-5 // Для обработки помещений ядами привлекают бомжей. wordforms_score до{ существительное }=-5 // Санкционированная акция прошла с 16 до 17 часов. wordforms_score ПАРКА{ существительное }=-5 // Королевские парки занимали обширную территорию. wordforms_score НИМ{ существительное }=-5 // Василий, не отрываясь, следит за ним взглядом. wordforms_score СТОЛА{ существительное }=-5 // На столе могут вырастать лужайки зеленой пищи. wordforms_score низка { существительное }=-5 wordforms_score мешка{ существительное }=-5 // Мешки с углем один за другим полетели в темную воду. wordforms_score стен { существительное }=-5 // По стенам развеваются блестящие знамена света. wordforms_score ряда { существительное }=-5 wordforms_score так { существительное }=-5 wordforms_score снова { существительное }=-5 wordforms_score лагер { существительное }=-5 wordforms_score гор { существительное }=-5 wordforms_score карт { существительное }=-5 // Военные топографы и геодезисты сверяют карты. wordforms_score зала { существительное }=-5 wordforms_score зало { существительное }=-5 wordforms_score миро { существительное }=-5 // В макротеле Мира отпечатывается мировая душа. wordforms_score мира { существительное }=-5 wordforms_score облак { существительное }=-5 // По ночным облакам зарумянилось дымное зарево. wordforms_score троп { существительное }=-5 // По берегу идут нерегулярные туристские тропы. wordforms_score пещер { существительное }=-5 wordforms_score ко{ существительное }=-10 // Разумеется, ко мне он больше не показывался. wordforms_score суда{ существительное }=-5 // В ближайшее время начнется его рассмотрение в суде. wordform_score "то и дело" { наречие }=5 // Во всяком случае, не придется то и дело нагибаться. wordform_score "воды" { число:мн } =-1 // они дали ему воды wordform_score "лицо" { одуш:одуш } =-1 wordform_score "лица" { одуш:одуш } =-1 // Ему даже делают специальный массаж лица. wordform_score "лицу" { одуш:одуш } =-1 wordform_score "лице" { одуш:одуш } =-1 wordform_score "лицом" { одуш:одуш } =-1 wordform_score "замок" { глагол } =-5 // замок на горе wordform_score "самогонки" { число:мн } = -1 // Пришлось добавить самогонки. wordform_score "интуиции" { число:мн } = -1 // Больше доверяют интуиции. wordform_score "воды" { число:мн } = -1 // Джек добавил воды. wordform_score "во" { вводное } = -2 // В детях эта программа усиливается во много раз. wordform_score "на" { глагол } =-1 // В эфир выходили на несколько секунд. wordform_score "веселей" { глагол } = -8 // В колонне веселей. wordform_score "гранит" { глагол } = -3 // Почем гранит науки? wordform_score "катя" { деепричастие } = -2 // Катя, давай! wordform_score "прочь" { глагол } = -5 // пойти прочь wordform_score "сволочь" { глагол } = -5 // - Сволочь! wordform_score "юля" { деепричастие } = -2 // Юля, уважь человека. wordform_score "катя" { деепричастие } = -2 // я направляюсь сюда, Катя. wordform_score "женя" { деепричастие } = -2 // Я больше не буду, Женя. wordform_score "нашей" { глагол } = -3 // - А вот и первые плоды нашей работы! wordform_score "Камчатки" { число:мн } = -2 // К аварийной подстанции в столице Камчатки подключают новый трансформатор wordform_score "воротам" { род:муж } = -2 // Беседуя, они подошли к воротам. wordform_score "один" { существительное } = -5 // Значит, он не один. wordform_score "то-то" { частица } = 2 // То-то выслуживается, вас гоняет. wordform_score "погреб" { глагол } =-2 // А вот погреб... wordform_score "просим" { прилагательное } = -5 // Просим всей группой. wordform_score "крови" { число:мн } = -5 // Скорее разойдитесь, не проливая крови! wordform_score "скоро" { прилагательное } = -4 // Скоро в строй? wordform_score "подъем" { глагол } = -5 // Подъем, товарищ майор! wordform_score "порой" { глагол } = -5 // И порой не без успеха. wordform_score "порой" { существительное } = -1 // Они ворчат порой. wordform_score "погоды" { число:мн } = -3 // По случаю чудной погоды Алексея тоже вывозили кататься. wordform_score "дарим" { прилагательное} = -5 // - Решено, дарим один ящик командиру полка! wordform_score "хватит" { глагол } = -1 // - На одну атаку хватит. wordform_score "как ни в чем не бывало" { наречие } = 1 // Ординарец в сенях спал как ни в чем не бывало. wordform_score "разве что" { наречие } = 1 // Так жарко бывает разве что перед грозой. wordform_score "потому что" { союз } =5 // - Потому что мне так нравится. wordform_score "на поводу у"{ предлог} = 1 // Нельзя идти на поводу у таких состояний wordform_score "что" { наречие } = -8 wordform_score "так что" { наречие } = -5 // Ну, так что вы скажете? wordform_score "вот" { наречие } = -3 wordform_score "Иду" { существительное } = -3 // - Иду к тебе! wordform_score "хотите" { НАКЛОНЕНИЕ:ПОБУД } = -5 wordform_score "всего" { наречие } = -4 // Он всего боялся wordform_score "всего лишь" { наречие } = 2 wordform_score "еле-еле" { наречие } = 2 wordform_score "туда-сюда" { наречие } = 2 wordform_score "туда-то" { наречие } = 2 wordform_score "отчего-то" { наречие } = 2 wordform_score "когда-то" { наречие } = 2 wordform_score "чуть-чуть" { наречие } = 2 wordform_score "так-то" { наречие } = 2 wordform_score "наконец-то" { наречие } = 2 wordform_score "туда-то" { наречие } = 2 wordform_score "тут-то" { наречие } = 2 wordform_score "Наконец-то" { наречие } = 2 wordform_score "добро" { наречие } = -4 // - Знаю я это добро. wordform_score "должно" { наречие } = -5 // Но так и должно быть. wordform_score "тем не менее" { наречие } = 1 wordform_score "прежде всего" { наречие } = 1 // Нужно прежде всего знать группу крови. wordform_score "выходит" { наречие } = -2 // это из тебя страх так выходит wordform_score "трибуны" { одуш:одуш } = -2 // Трибуны взрываются аплодисментами. wordform_score "по прошествии" { предлог } = 5 // По прошествии двух дней следствие не может установить их личности. wordform_score "сроком на" { предлог } = 2 // Аэропорт перешел в управление компании сроком на 30 лет. // Я ничего подобного не видал wordform_score "ничего" { наречие } = -5 // Не было таких прецедентов пока что. // ^^^^^^^^ wordform_score "пока что" { наречие } = 1 wordform_score "приводим" { прилагательное } = -5 // Приводим полный текст этого заявления. // Она поколебалась, прежде чем ответить. // ^^^^^^^^^^ wordform_score "прежде чем" { союз } = 1 wordform_score "а то" { союз } = 1 // А то тебе плохо станет. wordform_score "не то" { союз } = 1 // Вставай, не то опоздаем wordform_score "а не то" { союз } = 1 // Сядь, а не то упадешь // кости у всех одинаковые // ^^^^^ wordform_score "кости" { глагол } = -3 wordform_score "чести" { глагол } = -3 // Мы знаем друг друга много лет // ^^^^^^^^^^ wordform_score "друг друга" { существительное падеж:парт } = -1 // Текст речи премьер-министра // ^^^^^^^^^^^^^^^^ wordform_score "премьер-министр" { существительное } = 1 wordform_score "премьер-министра" { существительное } = 1 wordform_score "премьер-министром" { существительное } = 1 wordform_score "премьер-министру" { существительное } = 1 wordform_score "премьер-министре" { существительное } = 1 wordform_score "премьер-министры" { существительное } = 1 wordform_score "премьер-министров" { существительное } = 1 wordform_score "премьер-министрами" { существительное } = 1 wordform_score "премьер-министрам" { существительное } = 1 wordform_score "премьер-министрах" { существительное } = 1 // Хотим получить максимум информации // ^^^^^^^^^^ wordform_score "информации" { существительное число:мн } = -5 wordform_score "тому назад" { послелог } = 1 // Он просто вынужден закончить цикл историй, так как ограничены размеры книги. wordform_score "так как" { союз } = 5 // Поможем ему сена накосить // ^^^^ wordform_score "сена" { существительное число:мн } = -5 // Подавляем множественное число "ПУШОК": // "Мы видели их пушки" wordform_score "пушки" { существительное род:муж } = -5 wordform_score "это" { частица } = -2 // Кажется, вчера еще бродил я в этих рощах. wordform_score "кажется" { наречие } = -2 wordform_score "лицом к лицу" { наречие } = 5 // из конюшни они возвращались бок о бок. wordform_score "бок о бок" { наречие } = 2 // люди спят тем более. wordform_score "тем более" { наречие } = 2 wordform_score "в связи с" { предлог } = 1 // то есть могла бы wordform_score "то есть" { союз } = 3 // ПОКАДИТЬ(ПОКАЖУ) // wordform_score "покажу" { глагол глагол:покадить{} } = -5 // ПРОПАСТЬ>ПРОПАЛИТЬ(ПРОПАЛИ) wordform_score "пропали" { глагол наклонение:побуд } = -5 // ПОПАСТЬ > ПОПАЛИТЬ wordform_score "попали" { глагол наклонение:побуд } = -5 // предпочитаем вариант безличного глагола: //wordform_score "оставалось" { глагол } = -2 //wordform_score "остается" { глагол } = -2 //wordform_score "останется" { глагол } = -2 //wordform_score "осталось" { глагол } = -2 wordform_score "стали" { существительное число:мн } = -5 wordform_score "стали" { существительное падеж:род } = -3 // Жаль, если принятые обязательства не выполняются // ^^^^ wordform_score "жаль" { глагол } = -3 wordform_score "давным-давно" { наречие } = 2 // Можно ли сейчас применять старые методы? wordform_score "методам" { существительное род:жен } = -5 wordform_score "методах" { существительное род:жен } = -5 wordform_score "методу" { существительное род:жен } = -5 wordform_score "методе" { существительное род:жен } = -5 wordform_score "метода" { существительное род:жен } = -5 wordform_score "методы" { существительное род:жен } = -5 // Не вижу необходимости // ^^^^^^^^^^^^^ wordform_score "необходимости" { число:мн } = -1 wordform_score "о" { частица } = -2 wordform_score "Спешите" { наклонение:побуд } = -1 // отдадим преимущество безличной форме: // мне удалось поспать // ^^^^^^^ wordform_score "удалось" { глагол } = -3 // Придавим вариант "ПАР^ОК" // В парке был бассейн с золотыми рыбками. // ^^^^^ wordform_score "парке" { ПЕРЕЧИСЛИМОСТЬ:НЕТ } = -10 // слово БЫЛО редко выступает в роли наречия, но иногда бывает: // один из воинов пошел было к дверям // ^^^^ wordform_score "было" { наречие } = -10 // Это было примерно месяц назад wordform_score "примерно" { прилагательное } = -2 // чтобы подавить ВРЯД(ЛИ) wordform_score "вряд ли" { наречие } = 2 // при помощи женской страсти? // ^^^^^^^^^^ wordform_score "при помощи" { предлог } = 5 wordform_score "Владимиру" { существительное род:жен } = -2 wordform_score "Владимира" { существительное род:жен } = -2 wordform_score "Владимире" { существительное род:жен } = -2 // у тебя впереди серьезное дело wordform_score "дело" { глагол } = -5 wordform_score "правды" { существительное число:мн } = -2 // ты сволочь wordform_score "сволочь" { глагол } = -2 // во мне все же росло беспокойство wordform_score "росло" { прилагательное } = -1 // конкуренция между ЗАБРАТЬ.гл и ЗАБРАЛО.сущ wordform_score "забрала" { существительное } = -2 wordform_score "забрало" { существительное } = -2 wordform_score "забрал" { существительное } = -2 // обычно ЗАВТРА - наречие: // можно зайти за этим завтра? // ^^^^^^ wordform_score "завтра" { существительное } = -10 wordform_score "сегодня" { существительное } = -15 // взять деньги wordform_score "деньги" { существительное падеж:род } = -10 // Подавляем просторечный вариант "Сашок" // Сашка не знал wordform_score "Сашка" { существительное падеж:вин } = -1 wordform_score "Сашка" { существительное падеж:род } = -1 // обычно это - прилагательное wordform_score "простой" { глагол } = -1 // есть варианты ТУШЬ и ТУША (помимо глагола ТУШИТЬ). Вариант ТУШЬ гасим. wordform_score "тушь" { существительное одуш:неодуш } = -5 // обычно ПОЧТИ - это наречие // Почти совсем темно. // ^^^^^ wordform_score "почти" { глагол } = -5 // теперь самое время бросить кости wordform_score "кости" { глагол } = -5 wordform_score "брехло" { наречие } = -10 wordform_score "силой" { наречие } = -2 wordform_score "может" { вводное } = -1 // скорее доедай wordform_score "скорее" { вводное } = -1 wordform_score "пять" { глагол } = -5 wordform_score "спины" { существительное род:муж } = -1 wordform_score "спинах" { существительное род:муж } = -1 wordform_score "спине" { существительное род:муж } = -1 // хозяин дает корм псам wordform_score "корм" { существительное род:жен падеж:род } = -5 // несмотря на жару, солдаты носили шлемы и кирасы. wordform_score "несмотря на" { предлог } = 10 // В соответствии с шариатом, свинину употреблять запрещено // ^^^^^^^^^^^^^^^^ wordform_score "В соответствии с" { предлог } = 2 wordform_score "В соответствии со" { предлог } = 2 // В Дамаске в ходе ракетного обстрела погиб чиновник Евросоюза // ^^^^^^ wordform_score "в ходе" { предлог } = 2 // Мы пошли вместе по направлению к городу. // ^^^^^^^^^^^^^^^^ wordform_score "по направлению к" { предлог } = 2 wordform_score "по направлению ко" { предлог } = 2 // шеф просит еще раз проверить // wordform_score "еще раз" { наречие } = 10 // очень трудно найти задачу по силам wordform_score "по силам" { безлич_глагол } = -1 // есть все же средства // ^^^^^^ wordform_score "все же" { наречие } = 10 // все время находился в командировках // ^^^^^^^^^ //wordform_score "все время" { наречие } = 2 // Однако эти средства до сих пор не дошли до реального сектора экономики wordform_score "до сих пор" { наречие } = 10 // сбыться на самом деле wordform_score "на самом деле" { наречие } = 10 // Лошадь встала на дыбы. wordform_score "встать на дыбы" { инфинитив } = 2 wordform_score "встала на дыбы" { глагол } = 2 wordform_score "встал на дыбы" { глагол } = 2 wordform_score "встали на дыбы" { глагол } = 2 wordform_score "встанет на дыбы" { глагол } = 2 wordform_score "пузырь" { глагол } = -2 // выражение его лица было довольно странным wordform_score "довольно" { прилагательное } = -1 // они как будто пришли издалека // ^^^^^^^^^ wordform_score "как будто" { наречие } = 2 // Лошадь встала на дыбы. wordform_score "встать на дыбы" { глагол } = 2 // мой друг как всегда был прав // ^^^^^^^^^^ wordform_score "как всегда" { наречие } = 2 // без кольца все стало как обычно // ^^^^^^^^^^ wordform_score "как обычно" { наречие } = 2 // однако совершенно необходимо время от времени менять темп. // ^^^^^^^^^^^^^^^^ wordform_score "время от времени" { наречие } = 5 // все равно уже сорвал // ^^^^^^^^^ wordform_score "все равно" { наречие } = 10 // деревья полностью закрывают серое небо // ^^^^^^^^^ wordform_score "полностью" { существительное } = -100 // волосы обоих были все еще мокрые. // ^^^^^^^ wordform_score "все еще" { наречие } = 2 // всего один день. wordform_score "день" { глагол } = -1 // ты все это прекрасно знаешь // ^^^^^^^ wordform_score "все это" { местоим_сущ } = 1 // Андрюха хотел жить на отшибе // ^^^^^^^^^ wordform_score "на отшибе" { наречие } = 1 // ПОЙМА vs ПОНЯТЬ wordform_score "пойму" { существительное } = -1 // лучше всего сделать это сразу // ^^^^^^^^^^^ wordform_score "лучше всего" { безлич_глагол } = 1 wordform_score "нахожусь" { глагол вид:соверш } = -2 wordform_score "находимся" { глагол вид:соверш } = -2 wordform_score "находится" { глагол вид:соверш } = -2 wordform_score "находитесь" { глагол вид:соверш } = -2 wordform_score "находился" { глагол вид:соверш } = -2 wordform_score "находилась" { глагол вид:соверш } = -2 wordform_score "находилось" { глагол вид:соверш } = -2 wordform_score "находились" { глагол вид:соверш } = -2 wordform_score "находим" { прилагательное } = -5 // В Полинезии находим культ черепов вождей. wordform_score пошли { глагол время:прошедшее } = 1 // мы пошли домой wordform_score пошли { глагол наклонение:побуд } = -1 // не пошли! wordform_score спешить { инфинитив вид:несоверш } = 1 // спеш^ить (торопиться) wordform_score спешил { глагол вид:несоверш }=1 wordform_score спешила { глагол вид:несоверш }=1 wordform_score спешили { глагол вид:несоверш }=1 wordform_score спеши { глагол вид:несоверш }=1 wordform_score спешить { инфинитив вид:соверш } =-2 // сп^ешить (спустить с коня на землю) wordform_score спешил { глагол вид:соверш }=-2 wordform_score спешила { глагол вид:соверш }=-2 wordform_score спешили { глагол вид:соверш }=-2 wordform_score лето { существительное род:ср } = 1 wordform_score лёт { существительное род:муж } = -5 // Коля, давай-ка выпей молока wordform_score выпей { глагол } = 1 wordform_score выпей { существительное } = -2 wordform_score видно { наречие } = -3 //wordform_score видно { прилагательное } = 0 //wordform_score видно { вводное } = -1 //wordform_score времени { существительное } = 1 wordform_score времени { глагол } = -5 // О факторе времени. //wordform_score перед { предлог } = 1 wordform_score перед { существительное } = -2 wordform_score на { предлог } = 1 wordform_score на { частица } = -10 wordform_score жил { существительное } = -1 // жила wordform_score жил { глагол } = 1 // жить wordform_score любой { существительное } = -1 // Люба wordform_score жал { существительное } = -10 // жало wordform_score жал { глагол } = 1 // жать wordform_score велик { прилагательное } = -1 // великий wordform_score велика { существительное } = -10 wordform_score велика { прилагательное } = 1 // великий wordform_score велики { существительное } = -10 wordform_score велики { прилагательное } = 1 // великий wordform_score были { существительное } = -10 wordform_score были { глагол } = 1 wordform_score весь { существительное } = -10 wordform_score весь { глагол } = -10 wordform_score весь { прилагательное } = 1 wordform_score вещей { существительное } = 1 wordform_score вещей { прилагательное } = -1 wordform_score времени { глагол } = -10 wordform_score времени { существительное } = 1 //wordform_score все { местоим_сущ } = 1 //wordform_score все { прилагательное } = 1 wordform_score все { наречие } = -2 wordform_score все { частица } = -2 wordform_score всей { глагол } = -10 wordform_score всей { прилагательное } = 1 //wordform_score дали { глагол } = 1 wordform_score дали { существительное } = -1 //wordform_score смог { глагол } = 1 wordform_score смог { существительное } = -1 wordform_score действительно { прилагательное } = -10 wordform_score действительно { наречие } = 1 // wordform_score дел { существительное } = 1 // wordform_score дел { глагол } = 1 wordform_score дело { существительное } = 1 wordform_score дело { глагол } = -1 // wordform_score дела { существительное } = 1 // wordform_score дела { глагол } = 1 wordform_score день { существительное } = 1 wordform_score день { глагол } = -10 wordform_score для { предлог } = 1 wordform_score для { деепричастие } = -10 wordform_score какая { прилагательное } = 1 wordform_score какая { деепричастие } = -10 wordform_score конечно { прилагательное } = -1 wordform_score конечно { наречие } = 1 wordform_score мая { существительное одуш:неодуш } = 1 wordform_score мая { существительное одуш:одуш } = -1 wordform_score моря { существительное } = 1 wordform_score моря { деепричастие } = -10 wordform_score моя { прилагательное } = 1 wordform_score моя { деепричастие } = -10 wordform_score особой { прилагательное } = 1 wordform_score особой { существительное } = -1 wordform_score пора { существительное } = -1 wordform_score пора { безлич_глагол } = 1 wordform_score при { предлог } = 1 wordform_score при { глагол } = -10 wordform_score разрыв { существительное } = 1 wordform_score разрыв { деепричастие } = -1 wordform_score совести { существительное число:ед } = 1 wordform_score совести { существительное число:мн } = -5 wordform_score совести { глагол } = -2 wordform_score хвои { глагол } = -2 // Кубдя подбросил хвои. wordform_score споров { существительное } = 1 wordform_score споров { деепричастие } = -1 wordform_score стать { существительное } = -1 wordform_score стать { инфинитив } = 1 wordform_score такая { деепричастие } = -10 // такать wordform_score такая { прилагательное } = 1 wordform_score три { глагол } = -1 // тереть wordform_score три { числительное } = 1 wordform_score тут { существительное одуш:неодуш } = -10 // тут (тутовое дерево) wordform_score тут { наречие } = 1 wordform_score уж { частица } = 1 wordform_score уж { наречие } = 1 wordform_score уж { существительное } = -2 wordform_score уже { наречие степень:атриб } = 1 wordform_score уже { прилагательное } = -3 // узкий wordform_score уже { существительное } = -2 wordform_score уже { наречие степень:сравн } = -5 // узко wordform_score хотя { деепричастие } = -10 // хотеть wordform_score хотя { союз } = 1 // краткие формы среднего рода прилагательных используются очень редко, в отличие // от буквально совпадающих с ними наречий #define PreferAdverb(x) \ #begin //wordform_score x { наречие } = 2000000 wordform_score x { прилагательное } = -2 #end PreferAdverb( "абсолютно" ) PreferAdverb( "абстрактно" ) PreferAdverb( "абсурдно" ) PreferAdverb( "аварийно" ) PreferAdverb( "автоматично" ) PreferAdverb( "авторитарно" ) PreferAdverb( "авторитетно" ) PreferAdverb( "азартно" ) PreferAdverb( "аккуратно" ) PreferAdverb( "активно" ) PreferAdverb( "актуально" ) PreferAdverb( "алогично" ) PreferAdverb( "амбивалентно" ) PreferAdverb( "аномально" ) PreferAdverb( "анонимно" ) PreferAdverb( "аргументировано" ) PreferAdverb( "аристократично" ) PreferAdverb( "архиважно" ) PreferAdverb( "аскетично" ) PreferAdverb( "афористично" ) PreferAdverb( "капризно" ) PreferAdverb( "кардинально" ) PreferAdverb( "карикатурно" ) PreferAdverb( "категорично" ) PreferAdverb( "качественно" ) PreferAdverb( "классно" ) PreferAdverb( "комично" ) PreferAdverb( "комфортабельно" ) PreferAdverb( "комфортно" ) PreferAdverb( "конвульсивно" ) PreferAdverb( "конечно" ) PreferAdverb( "конкретно" ) PreferAdverb( "конструктивно" ) PreferAdverb( "контрастно" ) PreferAdverb( "концептуально" ) PreferAdverb( "корректно" ) PreferAdverb( "кратковременно" ) PreferAdverb( "крестообразно" ) PreferAdverb( "кристально" ) PreferAdverb( "круглосуточно" ) PreferAdverb( "курьезно" ) PreferAdverb( "кучно" ) PreferAdverb( "комплиментарно" ) PreferAdverb( "агрессивно" ) PreferAdverb( "адекватно" ) PreferAdverb( "алчно" ) PreferAdverb( "амбициозно" ) PreferAdverb( "аморально" ) PreferAdverb( "аналогично" ) PreferAdverb( "анекдотично" ) PreferAdverb( "апатично" ) PreferAdverb( "аполитично" ) PreferAdverb( "артистично" ) PreferAdverb( "асимметрично" ) PreferAdverb( "ассоциативно" ) PreferAdverb( "красно" ) PreferAdverb( "конфиденциально" ) PreferAdverb( "клятвенно" ) PreferAdverb( "краткосрочно" ) PreferAdverb( "круглогодично" ) PreferAdverb( "когерентно" ) PreferAdverb( "конъюнктурно" ) PreferAdverb( "конформно" ) PreferAdverb( "асинхронно" ) PreferAdverb( "аритмично" ) PreferAdverb( "альтруистично" ) PreferAdverb( "критично" ) PreferAdverb( "авантюрно" ) PreferAdverb( "автобиографично" ) PreferAdverb( "автономно" ) PreferAdverb( "аддитивно" ) PreferAdverb( "ажурно" ) PreferAdverb( "азбучно" ) PreferAdverb( "академично" ) PreferAdverb( "аллегорично" ) PreferAdverb( "альтернативно" ) PreferAdverb( "аморфно" ) PreferAdverb( "антагонистично" ) PreferAdverb( "антинаучно" ) PreferAdverb( "антиобщественно" ) PreferAdverb( "аппетитно" ) PreferAdverb( "ароматно" ) PreferAdverb( "архаично" ) PreferAdverb( "атипично" ) PreferAdverb( "аутентично" ) PreferAdverb( "каверзно" ) PreferAdverb( "капитально" ) PreferAdverb( "каплеобразно" ) PreferAdverb( "катастрофично" ) PreferAdverb( "келейно" ) PreferAdverb( "клешнеобразно" ) PreferAdverb( "клиновидно" ) PreferAdverb( "клинообразно" ) PreferAdverb( "коварно" ) PreferAdverb( "комедийно" ) PreferAdverb( "консервативно" ) PreferAdverb( "конституционно" ) PreferAdverb( "конусовидно" ) PreferAdverb( "конусообразно" ) PreferAdverb( "корыстно" ) PreferAdverb( "косвенно" ) PreferAdverb( "косноязычно" ) PreferAdverb( "кошмарно" ) PreferAdverb( "кощунственно" ) PreferAdverb( "красочно" ) PreferAdverb( "криводушно" ) PreferAdverb( "кровожадно" ) PreferAdverb( "крохотно" ) PreferAdverb( "крупно" ) PreferAdverb( "культурно" ) PreferAdverb( "куполообразно" ) PreferAdverb( "кустарно" ) PreferAdverb( "акцентировано" ) /*----------------------- select F1.name as word, Concat( '// ', C1.name, ':', E1.name, '{} и ', C2.name, ':', E2.name, '{}' ) from sg_entry E1, sg_entry E2, sg_form F1, sg_form F2, sg_class C1, sg_class C2 where E1.id_class!=E2.id_class and E1.name!='???' and F1.id_entry=E1.id and F2.id_entry=E2.id and F1.name=F2.name and C1.id=E1.id_class and C2.id=E2.id_class and E1.id<E2.id order by F1.name -------------------------*/ wordform_score "атакуем" { глагол } = 1 // ГЛАГОЛ:атаковать{} и ПРИЛАГАТЕЛЬНОЕ:атакуемый{} wordform_score "атакуем" { прилагательное } = -10 // ГЛАГОЛ:атаковать{} и ПРИЛАГАТЕЛЬНОЕ:атакуемый{} wordform_score "классифицируем" { глагол } = 1 // ГЛАГОЛ:классифицировать{} и ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} wordform_score "классифицируем" { прилагательное } = -10 // ГЛАГОЛ:классифицировать{} и ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} wordform_score "компенсируем" { глагол } = 1 // ГЛАГОЛ:компенсировать{} и ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} wordform_score "компенсируем" { прилагательное } = -10 // ГЛАГОЛ:компенсировать{} и ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} wordform_score "Коля" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ДЕЕПРИЧАСТИЕ:коля{} wordform_score "Коля" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Коли" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и СОЮЗ:коли{} wordform_score "Коли" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Колю" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Колю" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Кати" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Катя{} и ГЛАГОЛ:катить{} wordform_score "Кати" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Катя{} и ГЛАГОЛ:катить{} wordform_score "куплю" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:купля{} и ГЛАГОЛ:купить{} wordform_score "куплю" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:купля{} и ГЛАГОЛ:купить{} wordform_score "крали" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:краля{} и ГЛАГОЛ:красть{} wordform_score "крали" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:краля{} и ГЛАГОЛ:красть{} wordform_score "крести" { СУЩЕСТВИТЕЛЬНОЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:крести{} и ГЛАГОЛ:крестить{} wordform_score "крести" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крести{} и ГЛАГОЛ:крестить{} wordform_score "крыло" { СУЩЕСТВИТЕЛЬНОЕ } = 1000000 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыло" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыла" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыла" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыло" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыло" { ГЛАГОЛ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "ком" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "ком" { МЕСТОИМ_СУЩ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кому" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кому" { МЕСТОИМ_СУЩ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "Костя" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Костя{} и ДЕЕПРИЧАСТИЕ:костя{} wordform_score "Костя" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:Костя{} и ДЕЕПРИЧАСТИЕ:костя{} wordform_score "кувырком" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кувырок{} и НАРЕЧИЕ:кувырком{} wordform_score "кувырком" { НАРЕЧИЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кувырок{} и НАРЕЧИЕ:кувырком{} wordform_score "колея" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:колея{} и ДЕЕПРИЧАСТИЕ:колея{} wordform_score "колея" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:колея{} и ДЕЕПРИЧАСТИЕ:колея{} wordform_score "качком" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:качок{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "качком" { ПРИЛАГАТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:качок{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "канал" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "канал" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "канала" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "канала" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "автостопом" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:автостоп{} и НАРЕЧИЕ:автостопом{} wordform_score "автостопом" { НАРЕЧИЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:автостоп{} и НАРЕЧИЕ:автостопом{} wordform_score "Ковровом" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Ковров{} и ПРИЛАГАТЕЛЬНОЕ:ковровый{} wordform_score "Ковровом" { ПРИЛАГАТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Ковров{} и ПРИЛАГАТЕЛЬНОЕ:ковровый{} wordform_score "кладу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клад{} и ГЛАГОЛ:класть{} wordform_score "кладу" { ГЛАГОЛ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:клад{} и ГЛАГОЛ:класть{} wordform_score "клей" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ГЛАГОЛ:клеить{} wordform_score "клей" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ГЛАГОЛ:клеить{} wordform_score "клея" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ДЕЕПРИЧАСТИЕ:клея{} wordform_score "клея" { ДЕЕПРИЧАСТИЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ДЕЕПРИЧАСТИЕ:клея{} wordform_score "кубарем" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кубарь{} и НАРЕЧИЕ:кубарем{} wordform_score "кубарем" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:кубарь{} и НАРЕЧИЕ:кубарем{} wordform_score "калачиком" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:калачик{} и НАРЕЧИЕ:калачиком{} wordform_score "калачиком" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:калачик{} и НАРЕЧИЕ:калачиком{} wordform_score "ковали" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:коваль{} и ГЛАГОЛ:ковать{} wordform_score "ковали" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:коваль{} и ГЛАГОЛ:ковать{} wordform_score "Алле" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Алла{} и ЧАСТИЦА:алле{} wordform_score "Алле" { ЧАСТИЦА } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Алла{} и ЧАСТИЦА:алле{} wordform_score "кому" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:кома{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кому" { МЕСТОИМ_СУЩ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кома{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кисла" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "кисла" { ГЛАГОЛ } = 2 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "кисло" { наречие } = 2 wordform_score "кисло" { ПРИЛАГАТЕЛЬНОЕ } = -2 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "кисло" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "конвертируем" { ПРИЛАГАТЕЛЬНОЕ } = -1 // ПРИЛАГАТЕЛЬНОЕ:конвертируемый{} и ГЛАГОЛ:конвертировать{} wordform_score "конвертируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конвертируемый{} и ГЛАГОЛ:конвертировать{} wordform_score "клади" { СУЩЕСТВИТЕЛЬНОЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:кладь{} и ГЛАГОЛ:класть{} wordform_score "клади" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кладь{} и ГЛАГОЛ:класть{} wordform_score "копи" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:копь{} и ГЛАГОЛ:копить{} wordform_score "копи" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:копь{} и ГЛАГОЛ:копить{} wordform_score "крепи" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:крепь{} и ГЛАГОЛ:крепить{} wordform_score "крепи" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крепь{} и ГЛАГОЛ:крепить{} wordform_score "крошку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крошка{} и НАРЕЧИЕ:крошку{} wordform_score "крошку" { НАРЕЧИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:крошка{} и НАРЕЧИЕ:крошку{} wordform_score "качкой" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:качка{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "качкой" { ПРИЛАГАТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:качка{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "какой" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} //wordform_score "какой" { ПРИЛАГАТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} wordform_score "какою" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} wordform_score "какою" { ПРИЛАГАТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} // СУЩЕСТВИТЕЛЬНОЕ:кака{} и СОЮЗ:как{} wordform_score "как" { СОЮЗ } = 3 wordform_score "как" { НАРЕЧИЕ } = 2 wordform_score "как" { ЧАСТИЦА } = 1 wordform_score "как" { СУЩЕСТВИТЕЛЬНОЕ } = -10 wordform_score "ковка" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ковка{} и ПРИЛАГАТЕЛЬНОЕ:ковкий{} wordform_score "ковка" { ПРИЛАГАТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:ковка{} и ПРИЛАГАТЕЛЬНОЕ:ковкий{} wordform_score "кучу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:куча{} и ГЛАГОЛ:кутить{} wordform_score "кучу" { ГЛАГОЛ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:куча{} и ГЛАГОЛ:кутить{} wordform_score "кручу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ГЛАГОЛ:крутить{} wordform_score "кручу" { ГЛАГОЛ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ГЛАГОЛ:крутить{} wordform_score "круче" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и НАРЕЧИЕ:круто{} wordform_score "круче" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и НАРЕЧИЕ:круто{} wordform_score "круче" { ПРИЛАГАТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ПРИЛАГАТЕЛЬНОЕ:крутой{} wordform_score "как" { СОЮЗ } = 3 // НАРЕЧИЕ:как{} и СУЩЕСТВИТЕЛЬНОЕ:кака{} wordform_score "как" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:как{} и СУЩЕСТВИТЕЛЬНОЕ:кака{} wordform_score "как" { ЧАСТИЦА } = 0 // НАРЕЧИЕ:как{} и СОЮЗ:как{} wordform_score "как" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:как{} и ЧАСТИЦА:как{} wordform_score "кругом" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:кругом{} и СУЩЕСТВИТЕЛЬНОЕ:круг{} wordform_score "кругом" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:кругом{} и СУЩЕСТВИТЕЛЬНОЕ:круг{} wordform_score "кувырком" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:кувырком{} и СУЩЕСТВИТЕЛЬНОЕ:кувырок{} wordform_score "кувырком" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:кувырком{} и СУЩЕСТВИТЕЛЬНОЕ:кувырок{} wordform_score "каплю" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:каплю{} и СУЩЕСТВИТЕЛЬНОЕ:капля{} wordform_score "каплю" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:каплю{} и СУЩЕСТВИТЕЛЬНОЕ:капля{} wordform_score "крошечку" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:крошечку{} и СУЩЕСТВИТЕЛЬНОЕ:крошечка{} wordform_score "крошечку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:крошечку{} и СУЩЕСТВИТЕЛЬНОЕ:крошечка{} wordform_score "крошку" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:крошку{} и СУЩЕСТВИТЕЛЬНОЕ:крошка{} wordform_score "крошку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:крошку{} и СУЩЕСТВИТЕЛЬНОЕ:крошка{} wordform_score "кубарем" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:кубарем{} и СУЩЕСТВИТЕЛЬНОЕ:кубарь{} wordform_score "кубарем" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:кубарем{} и СУЩЕСТВИТЕЛЬНОЕ:кубарь{} wordform_score "кипуче" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:кипуче{} и ПРИЛАГАТЕЛЬНОЕ:кипучий{} wordform_score "кипуче" { ПРИЛАГАТЕЛЬНОЕ } = -1 // НАРЕЧИЕ:кипуче{} и ПРИЛАГАТЕЛЬНОЕ:кипучий{} wordform_score "куце" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:куце{} и ПРИЛАГАТЕЛЬНОЕ:куцый{} wordform_score "куце" { ПРИЛАГАТЕЛЬНОЕ } = -1 // НАРЕЧИЕ:куце{} и ПРИЛАГАТЕЛЬНОЕ:куцый{} wordform_score "антенной" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:антенный{} и СУЩЕСТВИТЕЛЬНОЕ:антенна{} wordform_score "антенной" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:антенный{} и СУЩЕСТВИТЕЛЬНОЕ:антенна{} wordform_score "анализируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:анализируемый{} и ГЛАГОЛ:анализировать{} wordform_score "анализируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:анализируемый{} и ГЛАГОЛ:анализировать{} wordform_score "ассоциируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:ассоциируемый{} и ГЛАГОЛ:ассоциировать{} wordform_score "ассоциируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:ассоциируемый{} и ГЛАГОЛ:ассоциировать{} wordform_score "культивируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:культивируемый{} и ГЛАГОЛ:культивировать{} wordform_score "контролируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:контролируемый{} и ГЛАГОЛ:контролировать{} wordform_score "автоматизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:автоматизируемый{} и ГЛАГОЛ:автоматизировать{} wordform_score "автоматизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:автоматизируемый{} и ГЛАГОЛ:автоматизировать{} wordform_score "адаптируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:адаптируемый{} и ГЛАГОЛ:адаптировать{} wordform_score "адаптируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адаптируемый{} и ГЛАГОЛ:адаптировать{} wordform_score "адресуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:адресуемый{} и ГЛАГОЛ:адресовать{} wordform_score "адресуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адресуемый{} и ГЛАГОЛ:адресовать{} wordform_score "аккумулируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:аккумулируемый{} и ГЛАГОЛ:аккумулировать{} wordform_score "аккумулируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:аккумулируемый{} и ГЛАГОЛ:аккумулировать{} wordform_score "акцептуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акцептуемый{} и ГЛАГОЛ:акцептовать{} wordform_score "акцептуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акцептуемый{} и ГЛАГОЛ:акцептовать{} wordform_score "акционируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акционируемый{} и ГЛАГОЛ:акционировать{} wordform_score "акционируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акционируемый{} и ГЛАГОЛ:акционировать{} wordform_score "амортизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:амортизируемый{} и ГЛАГОЛ:амортизировать{} wordform_score "амортизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:амортизируемый{} и ГЛАГОЛ:амортизировать{} wordform_score "арендуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:арендуемый{} и ГЛАГОЛ:арендовать{} wordform_score "арендуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:арендуемый{} и ГЛАГОЛ:арендовать{} wordform_score "афишируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:афишируемый{} и ГЛАГОЛ:афишировать{} wordform_score "афишируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:афишируемый{} и ГЛАГОЛ:афишировать{} wordform_score "капитализируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:капитализируемый{} и ГЛАГОЛ:капитализировать{} wordform_score "капитализируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:капитализируемый{} и ГЛАГОЛ:капитализировать{} wordform_score "классифицируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "классифицируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "классифицируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "классифицируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "комментируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:комментируемый{} и ГЛАГОЛ:комментировать{} wordform_score "комментируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:комментируемый{} и ГЛАГОЛ:комментировать{} wordform_score "коммутируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:коммутируемый{} и ГЛАГОЛ:коммутировать{} wordform_score "коммутируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:коммутируемый{} и ГЛАГОЛ:коммутировать{} wordform_score "конвоируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:конвоируемый{} и ГЛАГОЛ:конвоировать{} wordform_score "конвоируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конвоируемый{} и ГЛАГОЛ:конвоировать{} wordform_score "координируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:координируемый{} и ГЛАГОЛ:координировать{} wordform_score "координируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:координируемый{} и ГЛАГОЛ:координировать{} wordform_score "котируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:котируемый{} и ГЛАГОЛ:котировать{} wordform_score "котируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:котируемый{} и ГЛАГОЛ:котировать{} wordform_score "кредитуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кредитуемый{} и ГЛАГОЛ:кредитовать{} wordform_score "кредитуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кредитуемый{} и ГЛАГОЛ:кредитовать{} wordform_score "критикуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:критикуемый{} и ГЛАГОЛ:критиковать{} wordform_score "критикуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:критикуемый{} и ГЛАГОЛ:критиковать{} wordform_score "курируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:курируемый{} и ГЛАГОЛ:курировать{} wordform_score "курируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курируемый{} и ГЛАГОЛ:курировать{} wordform_score "корректируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:корректируемый{} и ГЛАГОЛ:корректировать{} wordform_score "корректируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:корректируемый{} и ГЛАГОЛ:корректировать{} wordform_score "ковровом" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:ковровый{} и СУЩЕСТВИТЕЛЬНОЕ:Ковров{} wordform_score "ковровом" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // ПРИЛАГАТЕЛЬНОЕ:ковровый{} и СУЩЕСТВИТЕЛЬНОЕ:Ковров{} wordform_score "кочевым" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кочевой{} и СУЩЕСТВИТЕЛЬНОЕ:Кочево{} wordform_score "кочевым" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // ПРИЛАГАТЕЛЬНОЕ:кочевой{} и СУЩЕСТВИТЕЛЬНОЕ:Кочево{} wordform_score "атакуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:атакуемый{} и ГЛАГОЛ:атаковать{} wordform_score "атакуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:атакуемый{} и ГЛАГОЛ:атаковать{} wordform_score "казним" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:казнимый{} и ГЛАГОЛ:казнить{} wordform_score "казним" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:казнимый{} и ГЛАГОЛ:казнить{} wordform_score "качаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:качаемый{} и ГЛАГОЛ:качать{} wordform_score "качаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качаемый{} и ГЛАГОЛ:качать{} wordform_score "кусаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кусаемый{} и ГЛАГОЛ:кусать{} wordform_score "кусаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кусаемый{} и ГЛАГОЛ:кусать{} wordform_score "компенсируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} и ГЛАГОЛ:компенсировать{} wordform_score "компенсируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} и ГЛАГОЛ:компенсировать{} wordform_score "караем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:караемый{} и ГЛАГОЛ:карать{} wordform_score "караем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:караемый{} и ГЛАГОЛ:карать{} wordform_score "командируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:командируемый{} и ГЛАГОЛ:командировать{} wordform_score "командируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:командируемый{} и ГЛАГОЛ:командировать{} wordform_score "конструируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:конструируемый{} и ГЛАГОЛ:конструировать{} wordform_score "конструируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конструируемый{} и ГЛАГОЛ:конструировать{} wordform_score "консультируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:консультируемый{} и ГЛАГОЛ:консультировать{} wordform_score "консультируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:консультируемый{} и ГЛАГОЛ:консультировать{} wordform_score "кидаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кидаемый{} и ГЛАГОЛ:кидать{} wordform_score "кидаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кидаемый{} и ГЛАГОЛ:кидать{} wordform_score "акцентируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акцентируемый{} и ГЛАГОЛ:акцентировать{} wordform_score "акцентируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акцентируемый{} и ГЛАГОЛ:акцентировать{} wordform_score "колонизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:колонизируемый{} и ГЛАГОЛ:колонизировать{} wordform_score "колонизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:колонизируемый{} и ГЛАГОЛ:колонизировать{} wordform_score "крымском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:крымский{} и СУЩЕСТВИТЕЛЬНОЕ:Крымск{} wordform_score "крымском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:крымский{} и СУЩЕСТВИТЕЛЬНОЕ:Крымск{} wordform_score "каспийском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:каспийский{} и СУЩЕСТВИТЕЛЬНОЕ:Каспийск{} wordform_score "каспийском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:каспийский{} и СУЩЕСТВИТЕЛЬНОЕ:Каспийск{} wordform_score "амурском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:амурский{} и СУЩЕСТВИТЕЛЬНОЕ:Амурск{} wordform_score "амурском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:амурский{} и СУЩЕСТВИТЕЛЬНОЕ:Амурск{} wordform_score "архангельском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:архангельский{} и СУЩЕСТВИТЕЛЬНОЕ:Архангельск{} wordform_score "архангельском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:архангельский{} и СУЩЕСТВИТЕЛЬНОЕ:Архангельск{} wordform_score "курильском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:курильский{} и СУЩЕСТВИТЕЛЬНОЕ:Курильск{} wordform_score "курильском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курильский{} и СУЩЕСТВИТЕЛЬНОЕ:Курильск{} wordform_score "кировском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:кировский{} и СУЩЕСТВИТЕЛЬНОЕ:Кировск{} wordform_score "кировском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кировский{} и СУЩЕСТВИТЕЛЬНОЕ:Кировск{} wordform_score "козельском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:козельский{} и СУЩЕСТВИТЕЛЬНОЕ:Козельск{} wordform_score "козельском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:козельский{} и СУЩЕСТВИТЕЛЬНОЕ:Козельск{} wordform_score "курском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:курский{} и СУЩЕСТВИТЕЛЬНОЕ:Курск{} wordform_score "курском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курский{} и СУЩЕСТВИТЕЛЬНОЕ:Курск{} wordform_score "калининском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:калининский{} и СУЩЕСТВИТЕЛЬНОЕ:Калининск{} wordform_score "калининском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:калининский{} и СУЩЕСТВИТЕЛЬНОЕ:Калининск{} wordform_score "красноярском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:красноярский{} и СУЩЕСТВИТЕЛЬНОЕ:Красноярск{} wordform_score "красноярском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:красноярский{} и СУЩЕСТВИТЕЛЬНОЕ:Красноярск{} wordform_score "качкой" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качкой" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качкою" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качкою" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качком" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качок{} wordform_score "качком" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качок{} wordform_score "адыгейском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:адыгейский{} и СУЩЕСТВИТЕЛЬНОЕ:Адыгейск{} wordform_score "адыгейском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адыгейский{} и СУЩЕСТВИТЕЛЬНОЕ:Адыгейск{} wordform_score "комсомольском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:комсомольский{} и СУЩЕСТВИТЕЛЬНОЕ:Комсомольск{} wordform_score "комсомольском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:комсомольский{} и СУЩЕСТВИТЕЛЬНОЕ:Комсомольск{} wordform_score "апшеронском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:апшеронский{} и СУЩЕСТВИТЕЛЬНОЕ:Апшеронск{} wordform_score "апшеронском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:апшеронский{} и СУЩЕСТВИТЕЛЬНОЕ:Апшеронск{} wordform_score "тайна" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:тайный{} wordform_score "тайна" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:тайна{} wordform_score "коробило" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "коробило" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "коробит" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "коробит" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "казалось" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:кажется{} и ГЛАГОЛ:казаться{} wordform_score "казалось" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:кажется{} и ГЛАГОЛ:казаться{} wordform_score "канал" { ГЛАГОЛ } = -5 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "канал" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "канала" { ГЛАГОЛ } = 1 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "канала" { СУЩЕСТВИТЕЛЬНОЕ } = 1000000 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "чай" { ГЛАГОЛ } = -10 // чаять wordform_score "чай" { СУЩЕСТВИТЕЛЬНОЕ } = 0 // чай wordform_score "чай" { частица } = -2 // чай wordform_score "чай" { наречие } = -5 wordform_score "готов" { прилагательное } = 1 wordform_score "готов" { существительное } = -1 wordform_score "извести" { инфинитив } = -1 wordform_score "извести" { существительное } = 1 wordform_score "нашли" { наклонение:изъяв } = 1 wordform_score "нашли" { наклонение:побуд } = -5 // ---- wordform_score "брехни" { глагол } = -1 // брехня брехни --> брехнуть брехни wordform_score "бузил" { существительное } = -1 // бузила бузил --> бузить бузил wordform_score "бурей" { глагол } = -1 // буря бурей --> буреть бурей wordform_score "бюллетень" { глагол } = -1 // бюллетень бюллетень --> бюллетенить бюллетень wordform_score "возрасту" { глагол } = -1 // возраст возрасту --> возрасти возрасту wordform_score "воплю" { глагол } = -1 // вопль воплю --> вопить воплю wordform_score "врали" { существительное } = -1 // враль врали --> врать врали wordform_score "гвозди" { глагол } = -1 // гвоздь гвозди --> гвоздить гвозди wordform_score "Глашу" { глагол } = -1 // Глаша Глашу --> гласить глашу wordform_score "голубей" { глагол } = -1 // голубь голубей --> голубеть голубей wordform_score "гряду" { глагол } = -1 // гряда гряду --> грясти гряду wordform_score "Дорою" { существительное } = -1 // Дора Дорою --> дорыть дорою wordform_score "дох" { глагол } = -1 // доха дох --> дохнуть дох wordform_score "драконят" { существительное } = -1 // драконенок драконят --> драконить драконят wordform_score "дублю" { глагол } = -1 // дубль дублю --> дубить дублю wordform_score "дули" { существительное } = -1 // дуля дули --> дуть дули wordform_score "ежу" { глагол } = -1 // еж ежу --> ежить ежу wordform_score "жал" { существительное } = -1 // жало жал --> жать жал wordform_score "жигану" { глагол } = -1 // жиган жигану --> жигануть жигану wordform_score "завали" { существительное } = -1 // заваль завали --> завалить завали wordform_score "замшей" { глагол } = -1 // замша замшей --> замшеть замшей wordform_score "зарей" { глагол } = -1 // заря зарей --> зареять зарей wordform_score "затей" { глагол } = -1 // затея затей --> затеять затей wordform_score "затею" { глагол } = -1 // затея затею --> затеять затею wordform_score "затону" { существительное } = -1 // затон затону --> затонуть затону wordform_score "знахарю" { глагол } = -1 // знахарь знахарю --> знахарить знахарю wordform_score "изморозь" { глагол } = -1 // изморозь изморозь --> изморозить изморозь wordform_score "канитель" { глагол } = -1 // канитель канитель --> канителить канитель wordform_score "ковали" { существительное } = -1 // коваль ковали --> ковать ковали wordform_score "кучу" { глагол } = -1 // куча кучу --> кутить кучу wordform_score "лохмачу" { существительное } = -1 // лохмач лохмачу --> лохматить лохмачу wordform_score "матерей" { глагол } = -5 // мать матерей --> матереть матерей wordform_score "матери" { глагол } = -5 // мать матери --> материть матери wordform_score "метель" { глагол } = -1 // метель метель --> метелить метель wordform_score "мини" { глагол } = -1 // мини мини --> минуть мини wordform_score "минут" { глагол } = -1 // минута минут --> минуть минут wordform_score "молоди" { глагол } = -1 // молодь молоди --> молодить молоди wordform_score "батрачат" { существительное } = -1 // батрачонок батрачат --> батрачить батрачат wordform_score "бузила" { существительное } = -1 // бузила бузила --> бузить бузила wordform_score "времени" { глагол } = -1 // время времени --> временить времени wordform_score "дурней" { глагол } = -1 // дурень дурней --> дурнеть дурней wordform_score "наймите" { существительное } = -1 // наймит наймите --> нанять наймите wordform_score "накипи" { глагол } = -1 // накипь накипи --> накипеть накипи wordform_score "нарвал" { существительное } = -1 // нарвал нарвал --> нарвать нарвал wordform_score "нарвала" { существительное } = -1 // нарвал нарвала --> нарвать нарвала wordform_score "нарой" { существительное } = -1 // нара нарой --> нарыть нарой wordform_score "пари" { глагол } = -1 // пари пари --> парить пари wordform_score "пастушат" { глагол } = -1 // пастушонок пастушат --> пастушить пастушат wordform_score "пасу" { существительное } = -1 // пас пасу --> пасти пасу wordform_score "пень" { глагол } = -1 // пень пень --> пенить пень wordform_score "пеню" { глагол } = -1 // пеня пеню --> пенить пеню wordform_score "передам" { существительное } = -1 // перед передам --> передать передам wordform_score "печаль" { глагол } = -1 // печаль печаль --> печалить печаль wordform_score "подтеки" { глагол } = -1 // подтек подтеки --> подтечь подтеки wordform_score "постригу" { существительное } = -1 // постриг постригу --> постричь постригу wordform_score "проем" { глагол } = -1 // проем проем --> проесть проем wordform_score "простой" { глагол } = -1 // простой простой --> простоять простой wordform_score "пряди" { глагол } = -1 // прядь пряди --> прясть пряди wordform_score "разъем" { глагол } = -1 // разъем разъем --> разъесть разъем wordform_score "ржу" { существительное } = -1 // ржа ржу --> ржать ржу wordform_score "ругани" { глагол } = -1 // ругань ругани --> ругануть ругани wordform_score "сбои" { глагол } = -1 // сбой сбои --> сбоить сбои wordform_score "секретарь" { глагол } = -1 // секретарь секретарь --> секретарить секретарь wordform_score "скину" { существительное } = -1 // скин скину --> скинуть скину wordform_score "слесарь" { глагол } = -1 // слесарь слесарь --> слесарить слесарь wordform_score "случаем" { глагол } = -1 // случай случаем --> случать случаем wordform_score "соловей" { глагол } = -1 // соловей соловей --> соловеть соловей wordform_score "спирали" { глагол } = -1 // спираль спирали --> спирать спирали wordform_score "старь" { глагол } = -1 // старь старь --> старить старь wordform_score "струи" { глагол } = -1 // струя струи --> струить струи wordform_score "такелажу" { глагол } = -1 // такелаж такелажу --> такелажить такелажу wordform_score "участи" { глагол } = -1 // участь участи --> участить участи wordform_score "хмелю" { глагол } = -10 // хмель хмелю --> хмелить хмелю wordform_score "чаем" { глагол } = -10 // чай чаем --> чаять чаем wordform_score "замшею" { глагол } = -1 // замша замшею --> замшеть замшею wordform_score "зелени" { глагол } = -1 // зелень зелени --> зеленить зелени wordform_score "знахарь" { глагол } = -1 // знахарь знахарь --> знахарить знахарь wordform_score "канифоль" { глагол } = -1 // канифоль канифоль --> канифолить канифоль wordform_score "лужу" { глагол } = -1 // лужа лужу --> лудить лужу wordform_score "матерей" { глагол } = -1 // матерь матерей --> матереть матерей wordform_score "матери" { глагол } = -1 // матерь матери --> материть матери wordform_score "мелей" { глагол } = -1 // мель мелей --> мелеть мелей wordform_score "мыло" { глагол } = -1 // мыло мыло --> мыть мыло wordform_score "обезьянят" { существительное } = -1 // обезьяненок обезьянят --> обезьянить обезьянят wordform_score "объем" { глагол } = -1 // объем объем --> объесть объем wordform_score "осени" { глагол } = -1 // осень осени --> осенить осени wordform_score "отмели" { глагол } = -1 // отмель отмели --> отмолоть отмели wordform_score "перла" { существительное } = -1 // перл перла --> переть перла wordform_score "пил" { существительное } = -1 // пила пил --> пить пил wordform_score "пищали" { существительное } = -1 // пищаль пищали --> пищать пищали wordform_score "поволок" { существительное } = -1 // поволока поволок --> поволочь поволок wordform_score "поволоку" { существительное } = -1 // поволока поволоку --> поволочь поволоку wordform_score "покой" { глагол } = -5 // покой покой --> покоить покой wordform_score "покою" { глагол } = -5 // покой покою --> покоить покою wordform_score "полет" { глагол } = -1 // полет полет --> полоть полет wordform_score "полете" { глагол } = -1 // полет полете --> полоть полете wordform_score "полю" { глагол } = -1 // поле полю --> полоть полю wordform_score "примеси" { глагол } = -1 // примесь примеси --> примесить примеси wordform_score "примету" { глагол } = -1 // примета примету --> примести примету wordform_score "припас" { существительное } = -1 // припас припас --> припасти припас wordform_score "продела" { существительное } = -1 // продел продела --> продеть продела wordform_score "просек" { существительное } = -1 // просека просек --> просечь просек wordform_score "пущу" { существительное } = -1 // пуща пущу --> пустить пущу wordform_score "пьяни" { глагол } = -1 // пьянь пьяни --> пьянить пьяни wordform_score "сбою" { глагол } = -1 // сбой сбою --> сбоить сбою wordform_score "свечу" { глагол } = -1 // свеча свечу --> светить свечу wordform_score "секретарю" { глагол } = -1 // секретарь секретарю --> секретарить секретарю wordform_score "случай" { глагол } = -5 // случай случай --> случать случай wordform_score "случаю" { глагол } = -5 // случай случаю --> случать случаю wordform_score "слюни" { глагол } = -1 // слюна слюни --> слюнить слюни wordform_score "смог" { существительное } = -1 // смог смог --> смочь смог wordform_score "смогу" { существительное } = -1 // смог смогу --> смочь смогу wordform_score "собачат" { существительное } = -1 // собаченок собачат --> собачить собачат wordform_score "совести" { глагол } = -1 // совесть совести --> совестить совести wordform_score "спас" { существительное } = -1 // спас спас --> спасти спас wordform_score "стай" { глагол } = -1 // стая стай --> стаять стай wordform_score "стаю" { глагол } = -1 // стая стаю --> стаять стаю wordform_score "струю" { глагол } = -1 // струя струю --> струить струю wordform_score "стужу" { глагол } = -1 // стужа стужу --> студить стужу wordform_score "сучат" { существительное } = -1 // сучонок сучат --> сучить сучат wordform_score "тлей" { глагол } = -1 // тля тлей --> тлеть тлей wordform_score "толщу" { глагол } = -1 // толща толщу --> толстить толщу wordform_score "царю" { глагол } = -4 // царь царю --> царить царю ==> Ну а поздно вечером довелось удивиться и царю. wordform_score "чащу" { глагол } = -1 // чаща чащу --> частить чащу wordform_score "чаю" { глагол } = -10 // чай чаю --> чаять чаю wordform_score "ширь" { глагол } = -1 // ширь ширь --> ширить ширь wordform_score "штурману" { глагол } = -1 // штурман штурману --> штурмануть штурману wordform_score "щурят" { существительное } = -1 // щуренок щурят --> щурить щурят wordform_score "гноя" { деепричастие } = -4 // гной гноя --> гноя гноя wordform_score "гостя" { деепричастие } = -1 // гость гостя --> гостя гостя wordform_score "душа" { деепричастие } = -1 // душ душа --> душа душа wordform_score "катя" { деепричастие } = -4 // Катя Катя --> катя катя wordform_score "колея" { деепричастие } = -1 // колея колея --> колея колея wordform_score "костя" { деепричастие } = -1 // Костя Костя --> костя костя wordform_score "нарыв" { деепричастие } = -1 // нарыв нарыв --> нарыв нарыв wordform_score "отлив" { деепричастие } = -1 // отлив отлив --> отлив отлив wordform_score "отпоров" { существительное } = -1 // отпор отпоров --> отпоров отпоров wordform_score "отрыв" { деепричастие } = -1 // отрыв отрыв --> отрыв отрыв wordform_score "подлив" { существительное } = -1 // подлива подлив --> подлив подлив wordform_score "покоя" { деепричастие } = -1 // покой покоя --> покоя покоя wordform_score "прилив" { деепричастие } = -1 // прилив прилив --> прилив прилив wordform_score "пузыря" { деепричастие } = -1 // пузырь пузыря --> пузыря пузыря wordform_score "руля" { деепричастие } = -1 // руль руля --> руля руля wordform_score "селя" { деепричастие } = -1 // сель селя --> селя селя wordform_score "случая" { деепричастие } = -1 // случай случая --> случая случая wordform_score "сторожа" { деепричастие } = -1 // сторож сторожа --> сторожа сторожа wordform_score "суша" { деепричастие } = -1 // суша суша --> суша суша wordform_score "туша" { деепричастие } = -1 // туш туша --> туша туша wordform_score "хмеля" { деепричастие } = -1 // хмель хмеля --> хмеля хмеля wordform_score "валя" { деепричастие } = -1 // Валя Валя --> валя валя wordform_score "варя" { деепричастие } = -1 // Варя Варя --> варя варя wordform_score "гвоздя" { деепричастие } = -1 // гвоздь гвоздя --> гвоздя гвоздя wordform_score "голубя" { деепричастие } = -1 // голубь голубя --> голубя голубя wordform_score "горя" { деепричастие } = -1 // горе горя --> горя горя wordform_score "клея" { деепричастие } = -1 // клей клея --> клея клея wordform_score "неволя" { деепричастие } = -1 // неволя неволя --> неволя неволя wordform_score "отколов" { существительное } = -1 // откол отколов --> отколов отколов wordform_score "переборов" { существительное } = -1 // перебор переборов --> переборов переборов wordform_score "подлив" { существительное } = -1 // подлив подлив --> подлив подлив wordform_score "подрыв" { деепричастие } = -1 // подрыв подрыв --> подрыв подрыв wordform_score "полив" { деепричастие } = -1 // полив полив --> полив полив wordform_score "пошив" { деепричастие } = -1 // пошив пошив --> пошив пошив wordform_score "чая" { деепричастие } = -10 // чай чая --> чая чая wordform_score "струя" { деепричастие } = -1 // струя струя --> струя струя wordform_score "белков" { прилагательное } = -1 // белок белков --> белковый белков wordform_score "витой" { существительное } = -1 // Вита Витой --> витой витой wordform_score "вожатом" { прилагательное } = -1 // вожатый вожатом --> вожатый вожатом wordform_score "вожатым" { прилагательное } = -1 // вожатый вожатым --> вожатый вожатым wordform_score "вожатых" { прилагательное } = -1 // вожатый вожатых --> вожатый вожатых wordform_score "гола" { прилагательное } = -1 // гол гола --> голый гола wordform_score "вороной" { прилагательное } = -1 // ворона вороной --> вороной вороной wordform_score "голы" { прилагательное } = -1 // гол голы --> голый голы wordform_score "гусиной" { существительное } = -1 // Гусина Гусиной --> гусиный гусиной wordform_score "гусиным" { существительное } = -1 // Гусин Гусиным --> гусиный гусиным wordform_score "гусиными" { существительное } = -1 // Гусин Гусиными --> гусиный гусиными wordform_score "добро" { прилагательное } = -1 // добро добро --> добрый добро wordform_score "долги" { прилагательное } = -1 // долг долги --> долгий долги wordform_score "готов" { существительное } = -1 // гот готов --> готовый готов wordform_score "звонки" { прилагательное } = -1 // звонок звонки --> звонкий звонки wordform_score "звонок" { прилагательное } = -1 // звонок звонок --> звонкий звонок wordform_score "лаком" { прилагательное } = -1 // лак лаком --> лакомый лаком wordform_score "лев" { прилагательное } = -1 // лев лев --> левый лев wordform_score "лишаем" { прилагательное } = -1 // лишай лишаем --> лишаемый лишаем wordform_score "сладка" { существительное } = -10 // сладка сладка --> сладкий сладка wordform_score "сладкой" { существительное } = -1 // сладка сладкой --> сладкий сладкой wordform_score "сладкою" { существительное } = -1 // сладка сладкою --> сладкий сладкою wordform_score "сладок" { существительное } = -1 // сладка сладок --> сладкий сладок wordform_score "темен" { существительное } = -1 // темя темен --> темный темен wordform_score "тонной" { прилагательное } = -1 // тонна тонной --> тонный тонной wordform_score "ужат" { существительное } = -1 // ужонок ужат --> ужатый ужат wordform_score "этой" { существительное } = -5 // эта этой --> этот этой wordform_score "рада" { существительное } = -1 // Рада Рада --> рад рада wordform_score "рады" { существительное } = -1 // Рада Рады --> рад рады wordform_score "столиком" { прилагательное } = -1 // столик столиком --> столикий столиком wordform_score "теми" { существительное } = -1 // темь теми --> тот теми wordform_score "тонною" { прилагательное } = -1 // тонна тонною --> тонный тонною wordform_score "ужата" { существительное } = -1 // ужонок ужата --> ужатый ужата wordform_score "эта" { существительное } = -3 // эта эта --> этот эта wordform_score "этою" { существительное } = -1 // эта этою --> этот этою wordform_score "эту" { существительное } = -3 // эта эту --> этот эту // ------------------------ // Для имен и некоторых существительных на -ИЕ варианты множественного числа // обычно не употребляются, поэтому мы можем априори предположить пониженную достоверность. // Этот макрос далее используется для перечисления таких слов. #define DiscountPlural(w) wordform_score w { существительное число:мн } = -2 /* -- список форм получен из SQL словаря запросом: select distinct 'DiscountPlural('+F.name+')' from sg_entry E, sg_link L, sg_entry E2, sg_entry_coord EC, sg_form F, sg_form_coord FC where E.id_class=9 and L.id_entry1=E.id and L.istate=50 and E2.id=L.id_entry2 and E2.name='ИМЯ' and EC.id_entry=E.id and EC.icoord=14 and EC.istate=1 and F.id_entry=E.id and FC.id_entry=E.id and FC.iform=F.iform and FC.icoord=13 and FC.istate=1 */ DiscountPlural(Авдотий) DiscountPlural(Авдотьи) DiscountPlural(Авдотьям) DiscountPlural(Авдотьями) DiscountPlural(Авдотьях) DiscountPlural(Агафий) DiscountPlural(Агафьи) DiscountPlural(Агафьям) DiscountPlural(Агафьями) DiscountPlural(Агафьях) DiscountPlural(Агнии) DiscountPlural(Агний) DiscountPlural(Агниям) DiscountPlural(Агниями) DiscountPlural(Агниях) DiscountPlural(Азалии) DiscountPlural(Азалий) DiscountPlural(Азалиям) DiscountPlural(Азалиями) DiscountPlural(Азалиях) DiscountPlural(Аксиний) DiscountPlural(Аксиньи) DiscountPlural(Аксиньям) DiscountPlural(Аксиньями) DiscountPlural(Аксиньях) DiscountPlural(Амалии) DiscountPlural(Амалий) DiscountPlural(Амалиям) DiscountPlural(Амалиями) DiscountPlural(Амалиях) DiscountPlural(Анастасии) DiscountPlural(Анастасий) DiscountPlural(Анастасиям) DiscountPlural(Анастасиями) DiscountPlural(Анастасиях) DiscountPlural(Анисий) DiscountPlural(Анисьи) DiscountPlural(Анисьям) DiscountPlural(Анисьями) DiscountPlural(Анисьях) DiscountPlural(Аполлинарии) DiscountPlural(Аполлинарий) DiscountPlural(Аполлинариям) DiscountPlural(Аполлинариями) DiscountPlural(Аполлинариях) DiscountPlural(Апраксии) DiscountPlural(Апраксий) DiscountPlural(Апраксиям) DiscountPlural(Апраксиями) DiscountPlural(Апраксиях) DiscountPlural(Валерии) DiscountPlural(Валерий) DiscountPlural(Валериям) DiscountPlural(Валериями) DiscountPlural(Валериях) DiscountPlural(Виктории) DiscountPlural(Викторий) DiscountPlural(Викториям) DiscountPlural(Викториями) DiscountPlural(Викториях) DiscountPlural(Виргинии) DiscountPlural(Виргиний) DiscountPlural(Виргиниям) DiscountPlural(Виргиниями) DiscountPlural(Виргиниях) DiscountPlural(Виталии) DiscountPlural(Виталий) DiscountPlural(Виталиям) DiscountPlural(Виталиями) DiscountPlural(Виталиях) DiscountPlural(Гликерии) DiscountPlural(Гликерий) DiscountPlural(Гликериям) DiscountPlural(Гликериями) DiscountPlural(Гликериях) DiscountPlural(Гортензии) DiscountPlural(Гортензий) DiscountPlural(Гортензиям) DiscountPlural(Гортензиями) DiscountPlural(Гортензиях) DiscountPlural(Дарий) DiscountPlural(Дарьи) DiscountPlural(Дарьям) DiscountPlural(Дарьями) DiscountPlural(Дарьях) DiscountPlural(Денисии) DiscountPlural(Денисий) DiscountPlural(Денисиям) DiscountPlural(Денисиями) DiscountPlural(Денисиях) DiscountPlural(Евгении) DiscountPlural(Евгений) DiscountPlural(Евгениям) DiscountPlural(Евгениями) DiscountPlural(Евгениях) DiscountPlural(Евдокии) DiscountPlural(Евдокий) DiscountPlural(Евдокиям) DiscountPlural(Евдокиями) DiscountPlural(Евдокиях) DiscountPlural(Евдоксии) DiscountPlural(Евдоксий) DiscountPlural(Евдоксиям) DiscountPlural(Евдоксиями) DiscountPlural(Евдоксиях) DiscountPlural(Евлалии) DiscountPlural(Евлалий) DiscountPlural(Евлалиям) DiscountPlural(Евлалиями) DiscountPlural(Евлалиях) DiscountPlural(Евлампии) DiscountPlural(Евлампий) DiscountPlural(Евлампиям) DiscountPlural(Евлампиями) DiscountPlural(Евлампиях) DiscountPlural(Евпраксии) DiscountPlural(Евпраксий) DiscountPlural(Евпраксиям) DiscountPlural(Евпраксиями) DiscountPlural(Евпраксиях) DiscountPlural(Евстолии) DiscountPlural(Евстолий) DiscountPlural(Евстолиям) DiscountPlural(Евстолиями) DiscountPlural(Евстолиях) DiscountPlural(Евфимии) DiscountPlural(Евфимий) DiscountPlural(Евфимиям) DiscountPlural(Евфимиями) DiscountPlural(Евфимиях) DiscountPlural(Евфросинии) DiscountPlural(Евфросиний) DiscountPlural(Евфросиниям) DiscountPlural(Евфросиниями) DiscountPlural(Евфросиниях) DiscountPlural(Епистимии) DiscountPlural(Епистимий) DiscountPlural(Епистимиям) DiscountPlural(Епистимиями) DiscountPlural(Епистимиях) DiscountPlural(Ефимии) DiscountPlural(Ефимий) DiscountPlural(Ефимиям) DiscountPlural(Ефимиями) DiscountPlural(Ефимиях) DiscountPlural(Ефросинии) DiscountPlural(Ефросиний) DiscountPlural(Ефросиниям) DiscountPlural(Ефросиниями) DiscountPlural(Ефросиниях) DiscountPlural(Ефросиньи) DiscountPlural(Ефросиньям) DiscountPlural(Ефросиньями) DiscountPlural(Ефросиньях) DiscountPlural(Зиновии) DiscountPlural(Зиновий) DiscountPlural(Зиновиям) DiscountPlural(Зиновиями) DiscountPlural(Зиновиях) DiscountPlural(Ии) DiscountPlural(Ий) DiscountPlural(Иям) DiscountPlural(Иями) DiscountPlural(Иях) DiscountPlural(Калерии) DiscountPlural(Калерий) DiscountPlural(Калериям) DiscountPlural(Калериями) DiscountPlural(Калериях) DiscountPlural(Клавдии) DiscountPlural(Клавдий) DiscountPlural(Клавдиям) DiscountPlural(Клавдиями) DiscountPlural(Клавдиях) DiscountPlural(Конкордии) DiscountPlural(Конкордий) DiscountPlural(Конкордиям) DiscountPlural(Конкордиями) DiscountPlural(Конкордиях) DiscountPlural(Констанции) DiscountPlural(Констанций) DiscountPlural(Констанциям) DiscountPlural(Констанциями) DiscountPlural(Констанциях) DiscountPlural(Корнелии) DiscountPlural(Корнелий) DiscountPlural(Корнелиям) DiscountPlural(Корнелиями) DiscountPlural(Корнелиях) DiscountPlural(Ксении) DiscountPlural(Ксений) DiscountPlural(Ксениям) DiscountPlural(Ксениями) DiscountPlural(Ксениях) DiscountPlural(Леокадии) DiscountPlural(Леокадий) DiscountPlural(Леокадиям) DiscountPlural(Леокадиями) DiscountPlural(Леокадиях) DiscountPlural(Лидии) DiscountPlural(Лидий) DiscountPlural(Лидиям) DiscountPlural(Лидиями) DiscountPlural(Лидиях) DiscountPlural(Лии) DiscountPlural(Лий) DiscountPlural(Лилии) DiscountPlural(Лилий) DiscountPlural(Лилиям) DiscountPlural(Лилиями) DiscountPlural(Лилиях) DiscountPlural(Лиям) DiscountPlural(Лиями) DiscountPlural(Лиях) DiscountPlural(Лукерий) DiscountPlural(Лукерьи) DiscountPlural(Лукерьям) DiscountPlural(Лукерьями) DiscountPlural(Лукерьях) DiscountPlural(Лукреции) DiscountPlural(Лукреций) DiscountPlural(Лукрециям) DiscountPlural(Лукрециями) DiscountPlural(Лукрециях) DiscountPlural(Малании) DiscountPlural(Маланий) DiscountPlural(Маланиям) DiscountPlural(Маланиями) DiscountPlural(Маланиях) DiscountPlural(Маланьи) DiscountPlural(Маланьям) DiscountPlural(Маланьями) DiscountPlural(Маланьях) DiscountPlural(Марии) DiscountPlural(Марий) DiscountPlural(Мариям) DiscountPlural(Мариями) DiscountPlural(Мариях) DiscountPlural(Марьи) DiscountPlural(Марьям) DiscountPlural(Марьями) DiscountPlural(Марьях) DiscountPlural(матрон) DiscountPlural(матронам) DiscountPlural(матронами) DiscountPlural(матронах) DiscountPlural(матроны) DiscountPlural(Мелании) DiscountPlural(Меланий) DiscountPlural(Меланиям) DiscountPlural(Меланиями) DiscountPlural(Меланиях) DiscountPlural(Настасии) DiscountPlural(Настасий) DiscountPlural(Настасиям) DiscountPlural(Настасиями) DiscountPlural(Настасиях) DiscountPlural(Настасьи) DiscountPlural(Настасьям) DiscountPlural(Настасьями) DiscountPlural(Настасьях) DiscountPlural(Наталии) DiscountPlural(Наталий) DiscountPlural(Наталиям) DiscountPlural(Наталиями) DiscountPlural(Наталиях) DiscountPlural(Натальи) DiscountPlural(Натальям) DiscountPlural(Натальями) DiscountPlural(Натальях) DiscountPlural(Оливии) DiscountPlural(Оливий) DiscountPlural(Оливиям) DiscountPlural(Оливиями) DiscountPlural(Оливиях) DiscountPlural(Олимпии) DiscountPlural(Олимпий) DiscountPlural(Олимпиям) DiscountPlural(Олимпиями) DiscountPlural(Олимпиях) DiscountPlural(Поликсении) DiscountPlural(Поликсений) DiscountPlural(Поликсениям) DiscountPlural(Поликсениями) DiscountPlural(Поликсениях) DiscountPlural(Прасковий) DiscountPlural(Прасковьи) DiscountPlural(Прасковьям) DiscountPlural(Прасковьями) DiscountPlural(Прасковьях) DiscountPlural(Пульхерии) DiscountPlural(Пульхерий) DiscountPlural(Пульхериям) DiscountPlural(Пульхериями) DiscountPlural(Пульхериях) DiscountPlural(Розалии) DiscountPlural(Розалий) DiscountPlural(Розалиям) DiscountPlural(Розалиями) DiscountPlural(Розалиях) DiscountPlural(светкам) DiscountPlural(светками) DiscountPlural(светках) DiscountPlural(светки) DiscountPlural(светок) DiscountPlural(Сильвии) DiscountPlural(Сильвий) DiscountPlural(Сильвиям) DiscountPlural(Сильвиями) DiscountPlural(Сильвиях) DiscountPlural(Соломонии) DiscountPlural(Соломоний) DiscountPlural(Соломониям) DiscountPlural(Соломониями) DiscountPlural(Соломониях) DiscountPlural(Софии) DiscountPlural(Софий) DiscountPlural(Софиям) DiscountPlural(Софиями) DiscountPlural(Софиях) DiscountPlural(Стефании) DiscountPlural(Стефаний) DiscountPlural(Стефаниям) DiscountPlural(Стефаниями) DiscountPlural(Стефаниях) DiscountPlural(Таисии) DiscountPlural(Таисий) DiscountPlural(Таисиям) DiscountPlural(Таисиями) DiscountPlural(Таисиях) DiscountPlural(Таисьи) DiscountPlural(Таисьям) DiscountPlural(Таисьями) DiscountPlural(Таисьях) DiscountPlural(томкам) DiscountPlural(томками) DiscountPlural(томках) DiscountPlural(томки) DiscountPlural(томок) DiscountPlural(Устинии) DiscountPlural(Устиний) DiscountPlural(Устиниям) DiscountPlural(Устиниями) DiscountPlural(Устиниях) DiscountPlural(Устиньи) DiscountPlural(Устиньям) DiscountPlural(Устиньями) DiscountPlural(Устиньях) DiscountPlural(Февронии) DiscountPlural(Февроний) DiscountPlural(Феврониям) DiscountPlural(Феврониями) DiscountPlural(Феврониях) DiscountPlural(Февроньи) DiscountPlural(Февроньям) DiscountPlural(Февроньями) DiscountPlural(Февроньях) DiscountPlural(Федосии) DiscountPlural(Федосий) DiscountPlural(Федосиям) DiscountPlural(Федосиями) DiscountPlural(Федосиях) DiscountPlural(Федосьи) DiscountPlural(Федосьям) DiscountPlural(Федосьями) DiscountPlural(Федосьях) DiscountPlural(Федотии) DiscountPlural(Федотий) DiscountPlural(Федотиям) DiscountPlural(Федотиями) DiscountPlural(Федотиях) DiscountPlural(Федотьи) DiscountPlural(Федотьям) DiscountPlural(Федотьями) DiscountPlural(Федотьях) DiscountPlural(Фелиции) DiscountPlural(Фелиций) DiscountPlural(Фелициям) DiscountPlural(Фелициями) DiscountPlural(Фелициях) DiscountPlural(Феодосии) DiscountPlural(Феодосий) DiscountPlural(Феодосиям) DiscountPlural(Феодосиями) DiscountPlural(Феодосиях) DiscountPlural(Феодотии) DiscountPlural(Феодотий) DiscountPlural(Феодотиям) DiscountPlural(Феодотиями) DiscountPlural(Феодотиях) DiscountPlural(Феофании) DiscountPlural(Феофаний) DiscountPlural(Феофаниям) DiscountPlural(Феофаниями) DiscountPlural(Феофаниях) DiscountPlural(Фетинии) DiscountPlural(Фетиний) DiscountPlural(Фетиниям) DiscountPlural(Фетиниями) DiscountPlural(Фетиниях) DiscountPlural(Фетиньи) DiscountPlural(Фетиньям) DiscountPlural(Фетиньями) DiscountPlural(Фетиньях) DiscountPlural(Хавронии) DiscountPlural(Хавроний) DiscountPlural(Хаврониям) DiscountPlural(Хаврониями) DiscountPlural(Хаврониях) DiscountPlural(Цецилии) DiscountPlural(Цецилий) DiscountPlural(Цецилиям) DiscountPlural(Цецилиями) DiscountPlural(Цецилиях) DiscountPlural(Эмилии) DiscountPlural(Эмилий) DiscountPlural(Эмилиям) DiscountPlural(Эмилиями) DiscountPlural(Эмилиях) DiscountPlural(Юлиании) DiscountPlural(Юлианий) DiscountPlural(Юлианиям) DiscountPlural(Юлианиями) DiscountPlural(Юлианиях) DiscountPlural(Юлии) DiscountPlural(Юлий) DiscountPlural(Юлиям) DiscountPlural(Юлиями) DiscountPlural(Юлиях) /* подавляем формы множ. числа для существительных на -ОСТЬ и -ИЕ список форм получен из SQL словаря запросом: select distinct 'DiscountPlural('+F.name+')' from sg_entry E, sg_form F, sg_form_coord FC, sg_form_coord FC2 where E.id_class=9 and F.id_entry=E.id and FC.id_entry=E.id and FC.iform=F.iform and FC.icoord=13 and FC.istate=1 and FC2.id_entry=E.id and FC2.iform=F.iform and FC2.icoord=24 and FC2.istate in (0,6) and (E.name like '%ИЕ' or E.name like '%ЬЕ' or E.name like '%ОСТЬ') */ DiscountPlural(абсолютизирования) DiscountPlural(абсолютизированья) DiscountPlural(абстрагирования) DiscountPlural(абстрагированья) DiscountPlural(авансирования) DiscountPlural(авансированья) DiscountPlural(авиапредприятия) DiscountPlural(авиапутешествия) DiscountPlural(авиасоединения) //DiscountPlural(автоколебания) //DiscountPlural(автопредприятия) //DiscountPlural(агропредприятия) DiscountPlural(активирования) DiscountPlural(активности) DiscountPlural(акционирования) DiscountPlural(анкетирования) DiscountPlural(аномальности) DiscountPlural(архиглупости) DiscountPlural(ассигнования) //DiscountPlural(ателье) //DiscountPlural(аудиосообщения) DiscountPlural(ауканья) DiscountPlural(аханья) DiscountPlural(бальзамирования) //DiscountPlural(банальности) DiscountPlural(бандподполья) //DiscountPlural(бандформирования) DiscountPlural(барахтания) DiscountPlural(бдения) //DiscountPlural(бедствия) DiscountPlural(бедствования) DiscountPlural(бездарности) DiscountPlural(беззакония) //DiscountPlural(безобразия) DiscountPlural(безумия) DiscountPlural(безумствования) DiscountPlural(беременности) DiscountPlural(бесконечности) DiscountPlural(бескрайности) DiscountPlural(бестактности) DiscountPlural(бесцеремонности) DiscountPlural(бибиканья) //DiscountPlural(биения) DiscountPlural(биоизлучения) DiscountPlural(биоизмерения) DiscountPlural(благовещения) DiscountPlural(благовещенья) DiscountPlural(благоволения) //DiscountPlural(благовония) //DiscountPlural(благовонья) DiscountPlural(благовремения) DiscountPlural(благовременья) DiscountPlural(благоглупости) DiscountPlural(благоговения) DiscountPlural(благоговенья) DiscountPlural(благодарения) DiscountPlural(благодарности) DiscountPlural(благодеяния) DiscountPlural(благодеянья) DiscountPlural(благозвучия) DiscountPlural(благозвучья) DiscountPlural(благолепия) DiscountPlural(благолепья) DiscountPlural(благоприличия) DiscountPlural(благоприличья) DiscountPlural(благородия) DiscountPlural(благородья) DiscountPlural(благословения) DiscountPlural(благословенья) DiscountPlural(благосостояния) DiscountPlural(благосостоянья) DiscountPlural(благости) DiscountPlural(благоухания) DiscountPlural(благоуханья) DiscountPlural(близости) //DiscountPlural(блуждания) //DiscountPlural(блужданья) DiscountPlural(богопочитания) DiscountPlural(богослужения) DiscountPlural(бодания) DiscountPlural(боестолкновения) DiscountPlural(болтания) DiscountPlural(бомбометания) DiscountPlural(бормотания) DiscountPlural(бормотанья) DiscountPlural(боронования) DiscountPlural(боронованья) DiscountPlural(бравирования) DiscountPlural(бравированья) DiscountPlural(бракосочетания) DiscountPlural(бракосочетанья) DiscountPlural(братания) DiscountPlural(братанья) DiscountPlural(брожения) DiscountPlural(броженья) DiscountPlural(бросания) DiscountPlural(брыкания) DiscountPlural(брыканья) DiscountPlural(брюзжания) DiscountPlural(брюзжанья) //DiscountPlural(буквосочетания) DiscountPlural(бурления) DiscountPlural(бурленья) DiscountPlural(бурчания) DiscountPlural(бурчанья) DiscountPlural(бухтения) DiscountPlural(бытописания) DiscountPlural(бытописанья) DiscountPlural(валентности) DiscountPlural(валяния) DiscountPlural(варенья) DiscountPlural(ваяния) DiscountPlural(вбивания) DiscountPlural(вбирания) DiscountPlural(вбрасывания) DiscountPlural(вбухивания) DiscountPlural(вваливания) DiscountPlural(введения) DiscountPlural(ввертывания) DiscountPlural(ввертыванья) DiscountPlural(ввинчивания) DiscountPlural(ввинчиванья) DiscountPlural(вгрызания) DiscountPlural(вдавливания) DiscountPlural(вдевания) DiscountPlural(вдергивания) DiscountPlural(вдохновения) DiscountPlural(вдохновенья) DiscountPlural(вдувания) DiscountPlural(ведомости) DiscountPlural(вежливости) DiscountPlural(везения) DiscountPlural(везенья) DiscountPlural(веления) DiscountPlural(венеротрясения) DiscountPlural(венчания) DiscountPlural(венчанья) //DiscountPlural(верования) DiscountPlural(вероисповедания) //DiscountPlural(вероучения) //DiscountPlural(вероученья) DiscountPlural(вероятности) //DiscountPlural(верховья) //DiscountPlural(ветвления) //DiscountPlural(ветвленья) DiscountPlural(ветшания) DiscountPlural(вечности) DiscountPlural(вещания) //DiscountPlural(веяния) DiscountPlural(вживления) DiscountPlural(взаимовлияния) DiscountPlural(взаимодействия) //DiscountPlural(взаимозависимости) //DiscountPlural(взаимоотношения) DiscountPlural(взаимоположения) DiscountPlural(взаимопревращения) DiscountPlural(взаимопроникновения) DiscountPlural(взбивания) DiscountPlural(взбрыкивания) DiscountPlural(взбухания) DiscountPlural(взвевания) DiscountPlural(взвешивания) DiscountPlural(взвизгивания) DiscountPlural(взвывания) DiscountPlural(взгорья) DiscountPlural(взгромождения) DiscountPlural(вздевания) DiscountPlural(вздрагивания) DiscountPlural(вздувания) DiscountPlural(вздутия) DiscountPlural(вздыбливания) DiscountPlural(вздымания) DiscountPlural(взлаивания) DiscountPlural(взмахивания) DiscountPlural(взмывания) DiscountPlural(взыскания) DiscountPlural(взятия) //DiscountPlural(видения) //DiscountPlural(виденья) DiscountPlural(видеоизображения) DiscountPlural(видеонаблюдения) //DiscountPlural(видеопослания) DiscountPlural(видеоприложения) DiscountPlural(видимости) DiscountPlural(видоизменения) DiscountPlural(визжания) DiscountPlural(визжанья) DiscountPlural(виляния) DiscountPlural(висения) DiscountPlural(вихляния) DiscountPlural(вклинивания) DiscountPlural(включения) DiscountPlural(вкрапления) DiscountPlural(вкручивания) DiscountPlural(вкусности) DiscountPlural(владения) DiscountPlural(влезания) DiscountPlural(влечения) //DiscountPlural(вливания) //DiscountPlural(влияния) //DiscountPlural(вложения) DiscountPlural(влюбленности) DiscountPlural(внедрения) DiscountPlural(внезапности) DiscountPlural(внесения) DiscountPlural(внешности) //DiscountPlural(внутренности) DiscountPlural(внушения) DiscountPlural(водопользования) DiscountPlural(водопользованья) DiscountPlural(водружения) DiscountPlural(вожделения) DiscountPlural(вожделенья) DiscountPlural(возвращения) DiscountPlural(возвышения) DiscountPlural(возвышенности) DiscountPlural(возгорания) DiscountPlural(воздаяния) //DiscountPlural(воздействия) //DiscountPlural(воззвания) //DiscountPlural(воззрения) //DiscountPlural(возлияния) DiscountPlural(возмездия) DiscountPlural(возможности) DiscountPlural(возмущения) DiscountPlural(вознаграждения) //DiscountPlural(возражения) DiscountPlural(волеизъявления) //DiscountPlural(волнения) DiscountPlural(волненья) DiscountPlural(волости) DiscountPlural(вольности) DiscountPlural(вооружения) DiscountPlural(воплощения) DiscountPlural(воплощенья) //DiscountPlural(восклицания) DiscountPlural(воскресения) DiscountPlural(воскресенья) DiscountPlural(воскрешения) DiscountPlural(воспаления) DiscountPlural(воспевания) //DiscountPlural(воспоминания) //DiscountPlural(воспоминанья) DiscountPlural(восприятия) DiscountPlural(воспроизведения) DiscountPlural(восславления) DiscountPlural(воссоединения) //DiscountPlural(восстания) DiscountPlural(восстановления) DiscountPlural(восхваления) DiscountPlural(восхищения) DiscountPlural(восхождения) DiscountPlural(восьмидесятилетия) DiscountPlural(восьмистишия) //DiscountPlural(впечатления) //DiscountPlural(впечатленья) DiscountPlural(впрыскивания) DiscountPlural(времяисчисления) DiscountPlural(вручения) DiscountPlural(вселения) DiscountPlural(вскрикивания) DiscountPlural(вскрытия) DiscountPlural(всплытия) DiscountPlural(вспрыгивания) DiscountPlural(вспухания) DiscountPlural(вспучивания) DiscountPlural(вспушивания) DiscountPlural(вставления) DiscountPlural(встревания) DiscountPlural(встряхивания) DiscountPlural(вступления) DiscountPlural(всучивания) DiscountPlural(всхлипывания) DiscountPlural(всхрапывания) DiscountPlural(всыпания) DiscountPlural(вталкивания) DiscountPlural(втирания) DiscountPlural(вторжения) DiscountPlural(втравливания) DiscountPlural(вульгарности) //DiscountPlural(вхождения) DiscountPlural(выбывания) DiscountPlural(выбытия) DiscountPlural(выведывания) DiscountPlural(выдвижения) DiscountPlural(выделения) DiscountPlural(выделывания) DiscountPlural(выдумывания) DiscountPlural(выздоравливания) DiscountPlural(выискивания) DiscountPlural(выказывания) DiscountPlural(выключения) DiscountPlural(выковывания) DiscountPlural(выкорчевывания) DiscountPlural(выкручивания) DiscountPlural(вылечивания) DiscountPlural(выпадения) DiscountPlural(выпекания) DiscountPlural(выполнения) DiscountPlural(выпрастывания) //DiscountPlural(выпуклости) DiscountPlural(выравнивания) //DiscountPlural(выражения) //DiscountPlural(выраженья) DiscountPlural(высвистывания) DiscountPlural(выселения) DiscountPlural(высечения) //DiscountPlural(высказывания) DiscountPlural(высокоблагородия) DiscountPlural(высокогорья) DiscountPlural(выстуживания) DiscountPlural(выступления) //DiscountPlural(высыпания) DiscountPlural(вычеркивания) //DiscountPlural(вычисления) DiscountPlural(вычитания) DiscountPlural(вычитывания) DiscountPlural(вышагивания) DiscountPlural(вышивания) DiscountPlural(вышучивания) DiscountPlural(выявления) DiscountPlural(выяснения) DiscountPlural(вяканья) DiscountPlural(гадания) //DiscountPlural(гадости) DiscountPlural(гашения) //DiscountPlural(гидросооружения) //DiscountPlural(гиперплоскости) DiscountPlural(гипноизлучения) DiscountPlural(главнокомандования) DiscountPlural(глиссирования) DiscountPlural(глиссированья) DiscountPlural(глумления) DiscountPlural(глумленья) //DiscountPlural(глупости) DiscountPlural(гнездования) DiscountPlural(гнездованья) //DiscountPlural(гнездовья) DiscountPlural(гноения) //DiscountPlural(гнусности) DiscountPlural(говенья) DiscountPlural(головокружения) DiscountPlural(головокруженья) DiscountPlural(голосования) //DiscountPlural(гонения) //DiscountPlural(госпредприятия) DiscountPlural(госсобственности) //DiscountPlural(гостей) //DiscountPlural(гости) //DiscountPlural(госучреждения) DiscountPlural(грехопадения) DiscountPlural(грубости) DiscountPlural(группирования) //DiscountPlural(гуляния) //DiscountPlural(гулянья) DiscountPlural(давления) DiscountPlural(давности) DiscountPlural(дактилоскопирования) DiscountPlural(данности) DiscountPlural(дарения) DiscountPlural(дарования) DiscountPlural(датирования) DiscountPlural(двенадцатилетия) //DiscountPlural(движения) //DiscountPlural(движенья) DiscountPlural(двоеточия) //DiscountPlural(двусмысленности) //DiscountPlural(двустишия) DiscountPlural(двухсотлетия) DiscountPlural(девяностолетия) DiscountPlural(деепричастия) //DiscountPlural(действия) DiscountPlural(деления) DiscountPlural(деликатности) DiscountPlural(демонстрирования) DiscountPlural(дергания) DiscountPlural(дерганья) DiscountPlural(держания) DiscountPlural(дерзания) DiscountPlural(дерзновения) DiscountPlural(дерзости) DiscountPlural(десятиборья) DiscountPlural(десятилетия) //DiscountPlural(деяния) //DiscountPlural(деянья) DiscountPlural(деятельности) // являются высшим критерием и конечной целью профессиональной деятельности госслужащего DiscountPlural(диагностирования) DiscountPlural(дикости) //DiscountPlural(дипотношения) DiscountPlural(добавления) DiscountPlural(добродетельности) //DiscountPlural(доверенности) DiscountPlural(доворачивания) DiscountPlural(договоренности) DiscountPlural(дозволения) DiscountPlural(долечивания) //DiscountPlural(должности) //DiscountPlural(домовладения) DiscountPlural(домоправления) //DiscountPlural(домостроения) DiscountPlural(домоуправления) DiscountPlural(домысливания) DiscountPlural(донесения) DiscountPlural(доперечисления) DiscountPlural(дописывания) //DiscountPlural(дополнения) DiscountPlural(допрашивания) //DiscountPlural(допущения) DiscountPlural(доставания) DiscountPlural(доставления) //DiscountPlural(достижения) DiscountPlural(достоверности) DiscountPlural(достопамятности) DiscountPlural(достояния) //DiscountPlural(досье) DiscountPlural(дотрагивания) DiscountPlural(доукомплектования) //DiscountPlural(драгоценности) //DiscountPlural(древности) //DiscountPlural(дрыганья) DiscountPlural(дудения) //DiscountPlural(дуновения) DiscountPlural(дуракаваляния) DiscountPlural(дурновкусия) DiscountPlural(дурости) DiscountPlural(единообразия) DiscountPlural(еканья) //DiscountPlural(емкости) DiscountPlural(ерзанья) DiscountPlural(жалования) DiscountPlural(жалованья) //DiscountPlural(желания) //DiscountPlural(желанья) DiscountPlural(жертвоприношения) DiscountPlural(жестокости) DiscountPlural(живописания) DiscountPlural(живописанья) //DiscountPlural(жидкости) DiscountPlural(жизнеописания) DiscountPlural(жизнепонимания) //DiscountPlural(жития) DiscountPlural(жонглирования) DiscountPlural(жонглированья) //DiscountPlural(заблуждения) //DiscountPlural(заблужденья) //DiscountPlural(заболевания) //DiscountPlural(заведения) //DiscountPlural(заведенья) //DiscountPlural(заверения) DiscountPlural(завершения) DiscountPlural(завещания) DiscountPlural(завещанья) DiscountPlural(зависания) //DiscountPlural(зависимости) //DiscountPlural(завихрения) //DiscountPlural(завоевания) //DiscountPlural(завывания) //DiscountPlural(завыванья) DiscountPlural(завышения) DiscountPlural(заглавия) DiscountPlural(заглубления) DiscountPlural(заглушения) DiscountPlural(заграждения) DiscountPlural(загромождения) DiscountPlural(загрубения) DiscountPlural(загрязнения) DiscountPlural(загрязненности) DiscountPlural(загустевания) //DiscountPlural(задания) DiscountPlural(задержания) DiscountPlural(задолженности) DiscountPlural(задымления) DiscountPlural(зажатия) DiscountPlural(зажатости) DiscountPlural(зазрения) DiscountPlural(зазывания) DiscountPlural(заигрывания) DiscountPlural(заикания) //DiscountPlural(заимствования) DiscountPlural(закаливания) //DiscountPlural(заклинания) //DiscountPlural(заклинанья) DiscountPlural(заключения) //DiscountPlural(заклятия) //DiscountPlural(заклятья) //DiscountPlural(закономерности) DiscountPlural(законопослушания) DiscountPlural(закрашивания) //DiscountPlural(закругления) //DiscountPlural(закругленности) DiscountPlural(закручивания) DiscountPlural(закрытия) DiscountPlural(заксобрания) DiscountPlural(залегания) DiscountPlural(заледенения) DiscountPlural(залития) //DiscountPlural(замечания) DiscountPlural(замирения) //DiscountPlural(замыкания) DiscountPlural(замысловатости) DiscountPlural(замятия) DiscountPlural(занижения) DiscountPlural(занимания) //DiscountPlural(занятия) //DiscountPlural(занятья) DiscountPlural(западания) DiscountPlural(западения) DiscountPlural(запаздывания) DiscountPlural(заполнения) DiscountPlural(заполняемости) DiscountPlural(запугивания) DiscountPlural(запутанности) //DiscountPlural(запястья) DiscountPlural(заседания) DiscountPlural(засорения) DiscountPlural(застолья) DiscountPlural(застревания) DiscountPlural(затмения) DiscountPlural(заточения) //DiscountPlural(затруднения) DiscountPlural(затушевывания) DiscountPlural(заумности) DiscountPlural(захватывания) DiscountPlural(захмеления) DiscountPlural(захолустья) DiscountPlural(зацикливания) DiscountPlural(зачатия) DiscountPlural(зачерствения) DiscountPlural(зачисления) //DiscountPlural(заявления) //DiscountPlural(звания) DiscountPlural(званья) DiscountPlural(звукоподражания) DiscountPlural(звукосочетания) //DiscountPlural(здания) DiscountPlural(здоровья) DiscountPlural(зелья) DiscountPlural(землевладения) DiscountPlural(землетрясения) //DiscountPlural(зимовья) DiscountPlural(зияния) //DiscountPlural(злодеяния) //DiscountPlural(злоключения) //DiscountPlural(злоупотребления) //DiscountPlural(знаменитости) //DiscountPlural(знамения) //DiscountPlural(знаменья) //DiscountPlural(знания) //DiscountPlural(значения) //DiscountPlural(значенья) DiscountPlural(значимости) DiscountPlural(избавленья) DiscountPlural(избивания) DiscountPlural(избиения) DiscountPlural(избрания) //DiscountPlural(изваяния) //DiscountPlural(изваянья) DiscountPlural(изведения) //DiscountPlural(извержения) //DiscountPlural(известия) //DiscountPlural(извещения) //DiscountPlural(извинения) DiscountPlural(извлечения) DiscountPlural(изволения) //DiscountPlural(извращения) DiscountPlural(изгнания) DiscountPlural(изгнанья) DiscountPlural(изголовья) //DiscountPlural(издания) //DiscountPlural(изделия) DiscountPlural(излития) DiscountPlural(излияния) DiscountPlural(изложения) DiscountPlural(излучения) DiscountPlural(изменения) DiscountPlural(измерения) DiscountPlural(измышления) //DiscountPlural(изнасилования) DiscountPlural(изобличения) //DiscountPlural(изображения) //DiscountPlural(изобретения) //DiscountPlural(изречения) DiscountPlural(изъявления) DiscountPlural(изъязвления) //DiscountPlural(изъятия) DiscountPlural(изысканности) DiscountPlural(изящности) DiscountPlural(иконопочитания) DiscountPlural(именитости) //DiscountPlural(имения) //DiscountPlural(именья) DiscountPlural(имитирования) DiscountPlural(индивидуальности) DiscountPlural(индуктивности) DiscountPlural(инкассирования) DiscountPlural(иносказания) DiscountPlural(интимности) DiscountPlural(инцидентности) //DiscountPlural(искажения) //DiscountPlural(искания) //DiscountPlural(исключения) DiscountPlural(искрения) //DiscountPlural(искривления) DiscountPlural(искушения) //DiscountPlural(испарения) DiscountPlural(исповедания) DiscountPlural(испоганивания) //DiscountPlural(исправления) //DiscountPlural(испражнения) //DiscountPlural(испытания) DiscountPlural(иссечения) //DiscountPlural(исследования) DiscountPlural(Универсиады)
ПРИЛАГАТЕЛЬНОЕ:культивируемый{} и ГЛАГОЛ:культивировать{}
wordform_score "культивируем" { ПРИЛАГАТЕЛЬНОЕ } = -5
7,303,640
[ 1, 145, 258, 145, 259, 145, 251, 145, 254, 145, 243, 145, 246, 145, 243, 145, 100, 145, 248, 145, 254, 145, 110, 145, 256, 145, 257, 145, 248, 30, 145, 123, 146, 230, 145, 124, 146, 239, 146, 229, 145, 121, 145, 115, 145, 121, 146, 227, 146, 230, 145, 118, 145, 125, 146, 238, 145, 122, 2916, 225, 145, 121, 225, 145, 246, 145, 254, 145, 243, 145, 246, 145, 257, 145, 254, 30, 145, 123, 146, 230, 145, 124, 146, 239, 146, 229, 145, 121, 145, 115, 145, 121, 146, 227, 145, 127, 145, 115, 145, 113, 146, 229, 146, 239, 2916, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 1095, 687, 67, 6355, 315, 145, 123, 146, 230, 145, 124, 146, 239, 146, 229, 145, 121, 145, 115, 145, 121, 146, 227, 146, 230, 145, 118, 145, 125, 6, 288, 225, 145, 258, 145, 259, 145, 251, 145, 254, 145, 243, 145, 246, 145, 243, 145, 100, 145, 248, 145, 254, 145, 110, 145, 256, 145, 257, 145, 248, 289, 273, 300, 25, 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 ]
// Diode Contracts // Copyright 2021 Diode // Licensed under the Diode License, Version 1.0 pragma solidity ^0.6.0; import "./FleetContract.sol"; import "./deps/Set.sol"; /** * ManagableFleetContract */ contract ManagableFleetContract is FleetContract { using Set for Set.Data; Set.Data members; constructor (DiodeRegistry _registry, address _operator, address payable _accountant) FleetContract(_registry, _operator, _accountant) public { } function SetDeviceAllowlist(address _client, bool _value) public override onlyOperator { super.SetDeviceAllowlist(_client, _value); if (_value) { members.add(_client); } else { members.remove(_client); } } function DeviceList() external view returns (address[] memory) { return members.items; } }
* ManagableFleetContract/
contract ManagableFleetContract is FleetContract { using Set for Set.Data; Set.Data members; pragma solidity ^0.6.0; constructor (DiodeRegistry _registry, address _operator, address payable _accountant) FleetContract(_registry, _operator, _accountant) public { } function SetDeviceAllowlist(address _client, bool _value) public override onlyOperator { super.SetDeviceAllowlist(_client, _value); if (_value) { members.add(_client); members.remove(_client); } } function SetDeviceAllowlist(address _client, bool _value) public override onlyOperator { super.SetDeviceAllowlist(_client, _value); if (_value) { members.add(_client); members.remove(_client); } } } else { function DeviceList() external view returns (address[] memory) { return members.items; } }
1,040,068
[ 1, 49, 940, 429, 11292, 8924, 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, 16351, 490, 940, 429, 11292, 8924, 353, 25362, 8924, 288, 203, 225, 1450, 1000, 364, 1000, 18, 751, 31, 203, 203, 225, 1000, 18, 751, 4833, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 20, 31, 203, 225, 3885, 261, 14521, 390, 4243, 389, 9893, 16, 1758, 389, 9497, 16, 1758, 8843, 429, 389, 4631, 970, 13, 25362, 8924, 24899, 9893, 16, 389, 9497, 16, 389, 4631, 970, 13, 1071, 288, 203, 225, 289, 203, 203, 225, 445, 1000, 3654, 7009, 1098, 12, 2867, 389, 2625, 16, 1426, 389, 1132, 13, 1071, 3849, 1338, 5592, 288, 203, 565, 2240, 18, 694, 3654, 7009, 1098, 24899, 2625, 16, 389, 1132, 1769, 203, 565, 309, 261, 67, 1132, 13, 288, 203, 1377, 4833, 18, 1289, 24899, 2625, 1769, 203, 1377, 4833, 18, 4479, 24899, 2625, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 225, 445, 1000, 3654, 7009, 1098, 12, 2867, 389, 2625, 16, 1426, 389, 1132, 13, 1071, 3849, 1338, 5592, 288, 203, 565, 2240, 18, 694, 3654, 7009, 1098, 24899, 2625, 16, 389, 1132, 1769, 203, 565, 309, 261, 67, 1132, 13, 288, 203, 1377, 4833, 18, 1289, 24899, 2625, 1769, 203, 1377, 4833, 18, 4479, 24899, 2625, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 565, 289, 469, 288, 203, 225, 445, 6077, 682, 1435, 3903, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 565, 327, 4833, 18, 3319, 31, 203, 225, 289, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } contract PlayerBook { using NameFilter for string; using SafeMath for uint256; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ address private admin = msg.sender; uint256 public registrationFee_ = 10 finney; // price to register a name mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games mapping(address => bytes32) public gameNames_; // lookup a games name mapping(address => uint256) public gameIDs_; // lokup a games ID uint256 public gID_; // total number of games uint256 public pID_; // total number of players mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. plyr_[1].addr = 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53; plyr_[1].name = "justo"; plyr_[1].names = 1; pIDxAddr_[0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53] = 1; pIDxName_["justo"] = 1; plyrNames_[1]["justo"] = true; plyrNameList_[1][1] = "justo"; plyr_[2].addr = 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D; plyr_[2].name = "mantso"; plyr_[2].names = 1; pIDxAddr_[0x8b4DA1827932D71759687f925D17F81Fc94e3A9D] = 2; pIDxName_["mantso"] = 2; plyrNames_[2]["mantso"] = true; plyrNameList_[2][1] = "mantso"; plyr_[3].addr = 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C; plyr_[3].name = "sumpunk"; plyr_[3].names = 1; pIDxAddr_[0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C] = 3; pIDxName_["sumpunk"] = 3; plyrNames_[3]["sumpunk"] = true; plyrNameList_[3][1] = "sumpunk"; plyr_[4].addr = 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C; plyr_[4].name = "inventor"; plyr_[4].names = 1; pIDxAddr_[0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C] = 4; pIDxName_["inventor"] = 4; plyrNames_[4]["inventor"] = true; plyrNameList_[4][1] = "inventor"; pID_ = 4; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // register name registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } /** * @dev players, if you registered a profile, before a game was released, or * set the all bool to false when you registered, use this function to push * your profile to a single game. also, if you've updated your name, you * can use this to push your name to games of your choosing. * -functionhash- 0x81c5b206 * @param _gameID game id */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // add players profile and most recent name games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev players, use this to push your player profile to all registered games. * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev players use this to change back to one of your old names. tip, you'll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) isHuman() public { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { // if names already has been used, require that current msg sender owns the name if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // add name to player profile, registry, and name book plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards //Jekyll_Island_Inc.deposit.value(address(this).balance)(); address(admin).call.value(address(this).balance)(); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ } /** * @title -Name Filter- v0.1.9 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
============================================================================== _| _ _|_ _ _ _ _|_ _ . (_|(_| | (_| _\(/_ | |_||_) .=============================|================================================
contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private admin = msg.sender; struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } public constructor() { plyr_[1].addr = 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53; plyr_[1].name = "justo"; plyr_[1].names = 1; pIDxAddr_[0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53] = 1; pIDxName_["justo"] = 1; plyrNames_[1]["justo"] = true; plyrNameList_[1][1] = "justo"; plyr_[2].addr = 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D; plyr_[2].name = "mantso"; plyr_[2].names = 1; pIDxAddr_[0x8b4DA1827932D71759687f925D17F81Fc94e3A9D] = 2; pIDxName_["mantso"] = 2; plyrNames_[2]["mantso"] = true; plyrNameList_[2][1] = "mantso"; plyr_[3].addr = 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C; plyr_[3].name = "sumpunk"; plyr_[3].names = 1; pIDxAddr_[0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C] = 3; pIDxName_["sumpunk"] = 3; plyrNames_[3]["sumpunk"] = true; plyrNameList_[3][1] = "sumpunk"; plyr_[4].addr = 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C; plyr_[4].name = "inventor"; plyr_[4].names = 1; pIDxAddr_[0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C] = 4; pIDxName_["inventor"] = 4; plyrNames_[4]["inventor"] = true; plyrNameList_[4][1] = "inventor"; pID_ = 4; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; require(_codeLength == 0, "sorry humans only"); _; } modifier isRegisteredGame() assembly {_codeLength := extcodesize(_addr)} { require(gameIDs_[msg.sender] != 0); _; } ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); event onNewName function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { plyr_[_pID].laff = _affCode; _affCode = 0; } } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { plyr_[_pID].laff = _affCode; _affCode = 0; } } } else if (_affCode == _pID) { registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } function useMyOldName(string _nameString) isHuman() public { bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); plyr_[_pID].name = _name; } function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); } function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); } address(admin).call.value(address(this).balance)(); if (_all == true) emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; return (true); return (false); } } function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; return (true); return (false); } } } else { function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { plyr_[_pID].laff = _affID; _affID = 0; } return(_isNewPlayer, _affID); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { plyr_[_pID].laff = _affID; _affID = 0; } return(_isNewPlayer, _affID); } } else if (_affID == _pID) { registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); }
14,621,386
[ 1, 9917, 26678, 377, 389, 96, 389, 389, 96, 67, 389, 565, 389, 389, 389, 96, 67, 565, 389, 282, 263, 565, 261, 67, 96, 24899, 96, 571, 261, 67, 96, 225, 389, 30351, 18510, 571, 571, 67, 20081, 67, 13, 225, 263, 2429, 14468, 33, 96, 20775, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 19185, 9084, 288, 203, 565, 1450, 1770, 1586, 364, 533, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 3238, 3981, 273, 1234, 18, 15330, 31, 203, 565, 1958, 19185, 288, 203, 3639, 1758, 3091, 31, 203, 3639, 1731, 1578, 508, 31, 203, 3639, 2254, 5034, 7125, 1403, 31, 203, 3639, 2254, 5034, 1257, 31, 203, 565, 289, 203, 3639, 1071, 203, 565, 3885, 1435, 203, 565, 288, 203, 203, 3639, 293, 715, 86, 67, 63, 21, 8009, 4793, 273, 374, 92, 28, 73, 20, 72, 29, 7140, 74, 23, 23057, 2643, 10321, 5948, 71, 5520, 38, 6669, 69, 37, 378, 1639, 69, 26, 38, 6938, 38, 9599, 72, 8643, 31, 203, 3639, 293, 715, 86, 67, 63, 21, 8009, 529, 273, 315, 3732, 83, 14432, 203, 3639, 293, 715, 86, 67, 63, 21, 8009, 1973, 273, 404, 31, 203, 3639, 293, 734, 92, 3178, 67, 63, 20, 92, 28, 73, 20, 72, 29, 7140, 74, 23, 23057, 2643, 10321, 5948, 71, 5520, 38, 6669, 69, 37, 378, 1639, 69, 26, 38, 6938, 38, 9599, 72, 8643, 65, 273, 404, 31, 203, 3639, 293, 734, 92, 461, 67, 9614, 3732, 83, 11929, 273, 404, 31, 203, 3639, 293, 715, 86, 1557, 67, 63, 21, 6362, 6, 3732, 83, 11929, 273, 638, 31, 203, 3639, 293, 715, 86, 461, 682, 67, 63, 21, 6362, 21, 65, 273, 315, 3732, 83, 14432, 203, 203, 3639, 293, 715, 86, 67, 63, 22, 8009, 4793, 273, 374, 92, 28, 70, 24, 9793, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; import "./interface/IAurumOracleCentralized.sol"; contract MultisigAurumOracle { event Submit(uint indexed txId); event Approve(uint indexed txId, address indexed approveBy); event Reject(uint indexed txId, address indexed revokeBy); event Execute(uint indexed txId); struct Transaction { address token; uint128 price; uint8 callswitch; // this will trigger different function, 0 = updateAssetPrice, 1 = updateAssetPriceFromWindow, 2 = updateGoldPrice bool executed; uint expireTimestamp; // set expire time, in case the system fetch multiple submit, first submit can be execute others will expire before reach the period time } Transaction[] public transactions; IAurumOracleCentralized public oracle; address[] public owners; mapping(address => bool) public isOwner; uint8 public required; // Amount of approve wallet to execute transaction mapping (uint => mapping(address => bool)) public approved; //[transaction][owner] => boolean mapping (uint => mapping(address => bool)) public voted; //[transaction][owner] => boolean constructor (address oracle_, address[] memory owners_, uint8 required_) { require(owners_.length > 0, "owners invalid"); require(required_ > 0 && required_ <= owners_.length, "required invalid"); oracle = IAurumOracleCentralized(oracle_); for(uint i; i< owners_.length; i++){ address owner = owners_[i]; require (owner != address(0), "owner is address 0"); require (!isOwner[owner], "owner is not unique"); isOwner[owner] = true; owners.push(owner); } required = required_; } modifier onlyOwner { require(isOwner[msg.sender], "only owner"); _; } modifier txExists(uint txId_){ require (txId_ < transactions.length, "tx does not exist"); _; } modifier notVoted(uint txId_){ require (!voted[txId_][msg.sender], "tx already approved"); _; } modifier notExecuted(uint txId_){ require (!transactions[txId_].executed, "tx already executed"); _; } modifier notExpire(uint txId_){ require (transactions[txId_].expireTimestamp >= block.timestamp, "tx expired"); _; } function submit(address token_, uint128 price_, uint8 callswitch_) external onlyOwner{ uint expire = block.timestamp + 10 minutes; // set expire time of the transaction = 10 minutes //Create new transaction waiting others to confirm. transactions.push( Transaction({ token: token_, price: price_, callswitch: callswitch_, executed: false, expireTimestamp: expire }) ); emit Submit(transactions.length -1); //emit the recent transaction. } //Approve function is to vote approve to the transaction function approve(uint txId_) external onlyOwner txExists(txId_) notVoted(txId_) notExecuted(txId_) notExpire(txId_) { approved[txId_][msg.sender] = true; //Vote approve voted[txId_][msg.sender] = true; emit Approve(txId_, msg.sender); } //Reject function is to vote reject to the transaction function reject(uint txId_) external onlyOwner txExists(txId_) notVoted(txId_) notExecuted(txId_) notExpire(txId_) { approved[txId_][msg.sender] = false; //Vote reject voted[txId_][msg.sender] = true; emit Reject(txId_, msg.sender); } //This will count approve function getApprovalCount(uint txId_) public view returns (uint){ uint count; for(uint i; i< owners.length; i++){ if (approved[txId_][owners[i]]){ count += 1; } } return count; } function execute(uint txId_) external txExists(txId_) notExecuted(txId_) notExpire(txId_) { require(getApprovalCount(txId_) >= required, "approvals < required"); //Whenever the signer approve reach 'required' the tx. can be executed by anyone Transaction storage transaction = transactions[txId_]; transaction.executed = true; // This will also prevent reentrance uint8 callswitch = transaction.callswitch; //gas optimizer if(callswitch == 0) { oracle.updateAssetPrice(transaction.token, transaction.price); emit Execute(txId_); return; //Short circuit out } if(callswitch == 1) { oracle.updateAssetPriceFromWindow(transaction.token); emit Execute(txId_); return; //Short circuit out } if(callswitch == 2) { oracle.updateGoldPrice(transaction.price); emit Execute(txId_); return; //Short circuit out } } }
set expire time, in case the system fetch multiple submit, first submit can be execute others will expire before reach the period time
uint expireTimestamp;
13,001,931
[ 1, 542, 6930, 813, 16, 316, 648, 326, 2619, 2158, 3229, 4879, 16, 1122, 4879, 848, 506, 1836, 10654, 903, 6930, 1865, 9287, 326, 3879, 813, 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, 3639, 2254, 6930, 4921, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; import "../vendor/uma/SkinnyOptimisticOracleInterface.sol"; import "./DAOracleHelpers.sol"; import "./vault/IVestingVault.sol"; import "./pool/StakingPool.sol"; import "./pool/SponsorPool.sol"; /** * @title SkinnyDAOracle * @dev This contract is the core of the Volatility Protocol DAOracle System. * It is responsible for rewarding stakers and issuing staker-backed bonds * which act as a decentralized risk pool for DAOracle Indexes. Bonds and rewards * are authorized, issued and funded by the Volatility DAO for qualified oracle * proposals, and stakers provide insurance against lost bonds. In exchange for * backstopping risk, stakers receive rewards for the data assurances they help * provide. In cases where a proposal is disputed, the DAOracle leverages UMA's * Data Validation Mechanism (DVM) to arbitrate and resolve by determining the * correct value through a community-led governance vote. */ contract SkinnyDAOracle is AccessControl, EIP712 { using SafeERC20 for IERC20; using DAOracleHelpers for Index; event Relayed( bytes32 indexed indexId, bytes32 indexed proposalId, Proposal proposal, address relayer, uint256 bondAmount ); event Disputed( bytes32 indexed indexId, bytes32 indexed proposalId, address disputer ); event Settled( bytes32 indexed indexId, bytes32 indexed proposalId, int256 proposedValue, int256 settledValue ); event IndexConfigured(bytes32 indexed indexId, IERC20 bondToken); event Rewarded(address rewardee, IERC20 token, uint256 amount); /** * @dev Indexes are backed by bonds which are insured by stakers who receive * rewards for backstopping the risk of those bonds being slashed. The reward * token is the same as the bond token for simplicity. Whenever a bond is * resolved, any delta between the initial bond amount and tokens received is * "slashed" from the staking pool. A portion of rewards are distributed to * two groups: Stakers and Reporters. Every time targetFrequency elapses, the * weight shifts from Stakers to Reporters until it reaches the stakerFloor. */ struct Index { IERC20 bondToken; // The token to be used for bonds uint32 lastUpdated; // The timestamp of the last successful update uint256 bondAmount; // The quantity of tokens to be put up for each bond uint256 bondsOutstanding; // The total amount of tokens outstanding for bonds uint256 disputesOutstanding; // The total number of requests currently in dispute uint256 drop; // The reward token drip rate (in wei) uint64 floor; // The minimum reward weighting for reporters (in wei, 1e18 = 100%) uint64 ceiling; // The maximum reward weighting for reporters (in wei, 1e18 = 100%) uint64 tilt; // The rate of change per second from floor->ceiling (in wei, 1e18 = 100%) uint64 creatorAmount; // The percentage of the total reward payable to the methodologist uint32 disputePeriod; // The dispute window for proposed values address creatorAddress; // The recipient of the methodologist rewards address sponsor; // The source of funding for the index's bonds and rewards } /** * @dev Proposals are used to validate index updates to be relayed to the UMA * OptimisticOracle. The ancillaryData field supports arbitrary byte arrays, * but we are compressing down to bytes32 which exceeds the capacity needed * for all currently known use cases. */ struct Proposal { bytes32 indexId; // The index identifier uint32 timestamp; // The timestamp of the value int256 value; // The proposed value bytes32 data; // Any other data needed to reproduce the proposed value } // UMA's SkinnyOptimisticOracle and registered identifier SkinnyOptimisticOracleInterface public immutable oracle; bytes32 public externalIdentifier; // Vesting Vault (for Rewards) IVestingVault public immutable vault; // Indexes and Proposals mapping(bytes32 => Index) public index; mapping(bytes32 => Proposal) public proposal; mapping(bytes32 => bool) public isDisputed; uint32 public defaultDisputePeriod = 10 minutes; uint32 public maxOutstandingDisputes = 3; // Staking Pools (bond insurance) mapping(IERC20 => StakingPool) public pool; // Roles (for AccessControl) bytes32 public constant ORACLE = keccak256("ORACLE"); bytes32 public constant MANAGER = keccak256("MANAGER"); bytes32 public constant PROPOSER = keccak256("PROPOSER"); // Proposal type hash (for EIP-712 signature verification) bytes32 public constant PROPOSAL_TYPEHASH = keccak256( abi.encodePacked( "Proposal(bytes32 indexId,uint32 timestamp,int256 value,bytes32 data)" ) ); /** * @dev Ensures that a given EIP-712 signature matches the hashed proposal * and was issued by an authorized signer. Accepts signatures from both EOAs * and contracts that support the EIP-712 standard. * @param relayed a proposal that was provided by the caller * @param signature an EIP-712 signature (raw bytes) * @param signer the address that provided the signature */ modifier onlySignedProposals( Proposal calldata relayed, bytes calldata signature, address signer ) { require( SignatureChecker.isValidSignatureNow( signer, _hashTypedDataV4( keccak256( abi.encode( PROPOSAL_TYPEHASH, relayed.indexId, relayed.timestamp, relayed.value, relayed.data ) ) ), signature ), "bad signature" ); require(hasRole(PROPOSER, signer), "unauthorized signer"); _; } constructor( bytes32 _ooIdentifier, SkinnyOptimisticOracleInterface _optimisticOracle, IVestingVault _vault ) EIP712("DAOracle", "1") { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(PROPOSER, msg.sender); _setupRole(MANAGER, msg.sender); _setupRole(ORACLE, address(_optimisticOracle)); externalIdentifier = _ooIdentifier; oracle = _optimisticOracle; vault = _vault; } /** * @dev Returns the currently claimable rewards for a given index. * @param indexId The index identifier * @return total The total reward token amount * @return poolAmount The pool's share of the rewards * @return reporterAmount The reporter's share of the rewards * @return residualAmount The methodologist's share of the rewards * @return vestingTime The amount of time the reporter's rewards must vest (in seconds) */ function claimableRewards(bytes32 indexId) public view returns ( uint256 total, uint256 poolAmount, uint256 reporterAmount, uint256 residualAmount, uint256 vestingTime ) { return index[indexId].claimableRewards(); } /** * @dev Relay an index update that has been signed by an authorized proposer. * The signature provided must satisfy two criteria: * (1) the signature must be a valid EIP-712 signature for the proposal; and * (2) the signer must have the "PROPOSER" role. * @notice See https://docs.ethers.io/v5/api/signer/#Signer-signTypedData * @param relayed The relayed proposal * @param signature An EIP-712 signature for the proposal * @param signer The address of the EIP-712 signature provider * @return bond The bond amount claimable via successful dispute * @return proposalId The unique ID of the proposal * @return expiresAt The time at which the proposal is no longer disputable */ function relay( Proposal calldata relayed, bytes calldata signature, address signer ) external onlySignedProposals(relayed, signature, signer) returns ( uint256 bond, bytes32 proposalId, uint32 expiresAt ) { proposalId = _proposalId(relayed.timestamp, relayed.value, relayed.data); require(proposal[proposalId].timestamp == 0, "duplicate proposal"); Index storage _index = index[relayed.indexId]; require(_index.disputesOutstanding < 3, "index ineligible for proposals"); require( _index.lastUpdated < relayed.timestamp, "must be later than most recent proposal" ); bond = _index.bondAmount; expiresAt = uint32(block.timestamp) + _index.disputePeriod; proposal[proposalId] = relayed; _index.lastUpdated = relayed.timestamp; _issueRewards(relayed.indexId, msg.sender); emit Relayed(relayed.indexId, proposalId, relayed, msg.sender, bond); } /** * @dev Disputes a proposal prior to its expiration. This causes a bond to be * posted on behalf of DAOracle stakers and an equal amount to be pulled from * the caller. * @notice This actually requests, proposes, and disputes with UMA's SkinnyOO * which sends the bonds and disputed proposal to UMA's DVM for settlement by * way of governance vote. Voters follow the specification of the DAOracle's * approved UMIP to determine the correct value. Once the outcome is decided, * the SkinnyOO will callback to this contract's `priceSettled` function. * @param proposalId the identifier of the proposal being disputed */ function dispute(bytes32 proposalId) external { Proposal storage _proposal = proposal[proposalId]; Index storage _index = index[_proposal.indexId]; require(proposal[proposalId].timestamp != 0, "proposal doesn't exist"); require( !isDisputed[proposalId] && block.timestamp < proposal[proposalId].timestamp + _index.disputePeriod, "proposal already disputed or expired" ); isDisputed[proposalId] = true; _index.dispute(_proposal, oracle, externalIdentifier); emit Disputed(_proposal.indexId, proposalId, msg.sender); } /** * @dev External callback for UMA's SkinnyOptimisticOracle. Fired whenever a * disputed proposal has been settled by the DVM, regardless of outcome. * @notice This is always called by the UMA SkinnyOO contract, not an EOA. * @param - identifier, ignored * @param timestamp The timestamp of the proposal * @param ancillaryData The data field from the proposal * @param request The entire SkinnyOptimisticOracle Request object */ function priceSettled( bytes32, /** identifier */ uint32 timestamp, bytes calldata ancillaryData, SkinnyOptimisticOracleInterface.Request calldata request ) external onlyRole(ORACLE) { bytes32 id = _proposalId( timestamp, request.proposedPrice, bytes32(ancillaryData) ); Proposal storage relayed = proposal[id]; Index storage _index = index[relayed.indexId]; _index.bondsOutstanding -= request.bond; _index.disputesOutstanding--; isDisputed[id] = false; if (relayed.value != request.resolvedPrice) { // failed proposal, slash pool to recoup lost bond pool[request.currency].slash(_index.bondAmount, address(this)); } else { // successful proposal, return bond to sponsor request.currency.safeTransfer(_index.sponsor, request.bond); // sends the rest of the funds received to the staking pool request.currency.safeTransfer( address(pool[request.currency]), request.currency.balanceOf(address(this)) ); } emit Settled(relayed.indexId, id, relayed.value, request.resolvedPrice); } /** * @dev Adds or updates a index. Can only be called by managers. * @param bondToken The token to be used for bonds * @param bondAmount The quantity of tokens to offer for bonds * @param indexId The price index identifier * @param disputePeriod The proposal dispute window * @param floor The starting portion of rewards payable to reporters * @param ceiling The maximum portion of rewards payable to reporters * @param tilt The rate of change from floor to ceiling per second * @param drop The number of reward tokens to drip (per second) * @param creatorAmount The portion of rewards payable to the methodologist * @param creatorAddress The recipient of the methodologist's rewards * @param sponsor The provider of funding for bonds and rewards */ function configureIndex( IERC20 bondToken, uint256 bondAmount, bytes32 indexId, uint32 disputePeriod, uint64 floor, uint64 ceiling, uint64 tilt, uint256 drop, uint64 creatorAmount, address creatorAddress, address sponsor ) external onlyRole(MANAGER) { Index storage _index = index[indexId]; _index.bondToken = bondToken; _index.bondAmount = bondAmount; _index.lastUpdated = _index.lastUpdated == 0 ? uint32(block.timestamp) : _index.lastUpdated; _index.drop = drop; _index.ceiling = ceiling; _index.tilt = tilt; _index.floor = floor; _index.creatorAmount = creatorAmount; _index.creatorAddress = creatorAddress; _index.disputePeriod = disputePeriod == 0 ? defaultDisputePeriod : disputePeriod; _index.sponsor = sponsor == address(0) ? address(_index.deploySponsorPool()) : sponsor; if (address(pool[bondToken]) == address(0)) { _createPool(_index); } emit IndexConfigured(indexId, bondToken); } /** * @dev Update the global default disputePeriod. Can only be called by managers. * @param disputePeriod The new disputePeriod, in seconds */ function setdefaultDisputePeriod(uint32 disputePeriod) external onlyRole(MANAGER) { defaultDisputePeriod = disputePeriod; } function setExternalIdentifier(bytes32 identifier) external onlyRole(MANAGER) { externalIdentifier = identifier; } /** * @dev Update the global default maxOutstandingDisputes. Can only be called by managers. * @param outstandingDisputes The new maxOutstandingDisputes */ function setMaxOutstandingDisputes(uint32 outstandingDisputes) external onlyRole(MANAGER) { maxOutstandingDisputes = outstandingDisputes; } /** * @dev Update the fees for a token's staking pool. Can only be called by managers. * @notice Fees must be scaled by 10**18 (1e18 = 100%). Example: 1000 DAI deposit * (0.1 * 10**18) = 100 DAI fee * @param mintFee the tax applied to new deposits * @param burnFee the tax applied to withdrawals * @param payee the recipient of fees */ function setPoolFees( IERC20 token, uint256 mintFee, uint256 burnFee, address payee ) external onlyRole(MANAGER) { pool[token].setFees(mintFee, burnFee, payee); } function _proposalId( uint32 timestamp, int256 value, bytes32 data ) public pure returns (bytes32) { return keccak256(abi.encodePacked(timestamp, value, data)); } function _createPool(Index storage _index) internal returns (StakingPool) { pool[_index.bondToken] = new StakingPool( ERC20(address(_index.bondToken)), 0, 0, address(this) ); _index.bondToken.safeApprove(address(vault), 2**256 - 1); _index.bondToken.safeApprove(address(oracle), 2**256 - 1); return pool[_index.bondToken]; } function _issueRewards(bytes32 indexId, address reporter) internal { Index storage _index = index[indexId]; ( uint256 total, uint256 poolAmount, uint256 reporterAmount, uint256 residualAmount, uint256 vestingTime ) = _index.claimableRewards(); // Pull in reward money from the sponsor _index.bondToken.safeTransferFrom(_index.sponsor, address(this), total); // Push rewards to pool and methodologist _index.bondToken.safeTransfer(address(pool[_index.bondToken]), poolAmount); _index.bondToken.safeTransfer(_index.creatorAddress, residualAmount); // Push relayer's reward to the vault for vesting vault.issue( reporter, _index.bondToken, reporterAmount, block.timestamp, 0, vestingTime ); emit Rewarded(reporter, _index.bondToken, reporterAmount); } } // 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 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; import "../Address.sol"; import "../../interfaces/IERC1271.sol"; /** * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like * Argent and Gnosis Safe. * * _Available since v4.1._ */ library SignatureChecker { /** * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length over a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); /** * @notice Returns the state of a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State enum value. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return true if price has resolved or settled, false otherwise. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); function stampAncillaryData(bytes memory ancillaryData, address requester) public view virtual returns (bytes memory); } /** * @title Interface for the gas-cost-reduced version of the OptimisticOracle. * @notice Differences from normal OptimisticOracle: * - refundOnDispute: flag is removed, by default there are no refunds on disputes. * - customizing request parameters: In the OptimisticOracle, parameters like `bond` and `customLiveness` can be reset * after a request is already made via `requestPrice`. In the SkinnyOptimisticOracle, these parameters can only be * set in `requestPrice`, which has an expanded input set. * - settleAndGetPrice: Replaced by `settle`, which can only be called once per settleable request. The resolved price * can be fetched via the `Settle` event or the return value of `settle`. * - general changes to interface: Functions that interact with existing requests all require the parameters of the * request to modify to be passed as input. These parameters must match with the existing request parameters or the * function will revert. This change reflects the internal refactor to store hashed request parameters instead of the * full request struct. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract SkinnyOptimisticOracleInterface { event RequestPrice( address indexed requester, bytes32 indexed identifier, uint32 timestamp, bytes ancillaryData, Request request ); event ProposePrice( address indexed requester, bytes32 indexed identifier, uint32 timestamp, bytes ancillaryData, Request request ); event DisputePrice( address indexed requester, bytes32 indexed identifier, uint32 timestamp, bytes ancillaryData, Request request ); event Settle( address indexed requester, bytes32 indexed identifier, uint32 timestamp, bytes ancillaryData, Request request ); // Struct representing a price request. Note that this differs from the OptimisticOracleInterface's Request struct // in that refundOnDispute is removed. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @param bond custom proposal bond to set for request. If set to 0, defaults to the final fee. * @param customLiveness custom proposal liveness to set for request. * @return totalBond default bond + final fee that the proposer and disputer will be required to pay. */ function requestPrice( bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward, uint256 bond, uint256 customLiveness ) external virtual returns (uint256 totalBond); /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters whose hash must match the request that the caller wants to * propose a price for. * @param proposer address to set as the proposer. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request, address proposer, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Proposes a price value where caller is the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters whose hash must match the request that the caller wants to * propose a price for. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Combines logic of requestPrice and proposePrice while taking advantage of gas savings from not having to * overwrite Request params that a normal requestPrice() => proposePrice() flow would entail. Note: The proposer * will receive any rewards that come from this proposal. However, any bonds are pulled from the caller. * @dev The caller is the requester, but the proposer can be customized. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @param bond custom proposal bond to set for request. If set to 0, defaults to the final fee. * @param customLiveness custom proposal liveness to set for request. * @param proposer address to set as the proposer. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function requestAndProposePriceFor( bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward, uint256 bond, uint256 customLiveness, address proposer, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters whose hash must match the request that the caller wants to * dispute. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request, address disputer, address requester ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal where caller is the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters whose hash must match the request that the caller wants to * dispute. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request ) external virtual returns (uint256 totalBond); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters whose hash must match the request that the caller wants to * settle. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. * @return resolvedPrice the price that the request settled to. */ function settle( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request ) external virtual returns (uint256 payout, int256 resolvedPrice); /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters. * @return the State. */ function getState( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request ) external virtual returns (OptimisticOracleInterface.State); /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param request price request parameters. The hash of these parameters must match with the request hash that is * associated with the price request unique ID {requester, identifier, timestamp, ancillaryData}, or this method * will revert. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request ) external virtual returns (bool); /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stamped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) external pure virtual returns (bytes memory); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import "./SkinnyDAOracle.sol"; import "./pool/SponsorPool.sol"; library DAOracleHelpers { using SafeERC20 for IERC20; function claimableRewards(SkinnyDAOracle.Index storage index) public view returns ( uint256 total, uint256 poolAmount, uint256 reporterAmount, uint256 residualAmount, uint256 vestingTime ) { // multiplier = distance between last proposal and current time (in seconds) uint256 multiplier = block.timestamp - index.lastUpdated; // minimum multiplier = 1 if (multiplier == 0) multiplier = 1; // reporter's share starts at floor and moves toward ceiling by tilt % per tick uint256 reporterShare = index.floor + (index.tilt * multiplier); if (reporterShare > index.ceiling) reporterShare = index.ceiling; total = index.drop * multiplier; reporterAmount = (total * reporterShare) / 1e18; residualAmount = ((total - reporterAmount) * index.creatorAmount) / 1e18; poolAmount = total - residualAmount - reporterAmount; vestingTime = 0; } function dispute( SkinnyDAOracle.Index storage index, SkinnyDAOracle.Proposal storage proposal, SkinnyOptimisticOracleInterface oracle, bytes32 externalIdentifier ) public { IERC20 token = index.bondToken; // Pull in funds from sponsor to cover the proposal bond token.safeTransferFrom(index.sponsor, address(this), index.bondAmount); // Pull in funds from disputer to match the bond token.safeTransferFrom(msg.sender, address(this), index.bondAmount); // Create the request + proposal via UMA's OO uint256 bond = oracle.requestAndProposePriceFor( externalIdentifier, proposal.timestamp, abi.encodePacked(proposal.data), token, 0, index.bondAmount, index.disputePeriod, address(this), proposal.value ); // Build the OO request object for the above proposal SkinnyOptimisticOracleInterface.Request memory request; request.currency = token; request.finalFee = bond - index.bondAmount; request.bond = bond - request.finalFee; request.proposer = address(this); request.proposedPrice = proposal.value; request.expirationTime = block.timestamp + index.disputePeriod; request.customLiveness = index.disputePeriod; // Initiate the dispute on disputer's behalf oracle.disputePriceFor( externalIdentifier, proposal.timestamp, abi.encodePacked(proposal.data), request, msg.sender, address(this) ); // Keep track of the outstanding bond and dispute index.bondsOutstanding += bond; index.disputesOutstanding++; } function deploySponsorPool(SkinnyDAOracle.Index storage index) public returns (SponsorPool) { return new SponsorPool(ERC20(address(index.bondToken))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title VestingVault * @dev A token vesting contract that will release tokens gradually like a * standard equity vesting schedule, with a cliff and vesting period but no * arbitrary restrictions on the frequency of claims. Optionally has an initial * tranche claimable immediately after the cliff expires (in addition to any * amounts that would have vested up to that point but didn't due to a cliff). */ interface IVestingVault { event Issued( address indexed beneficiary, IERC20 token, uint256 amount, uint256 start, uint256 cliff, uint256 duration ); event Released( address indexed beneficiary, uint256 indexed allocationId, IERC20 token, uint256 amount, uint256 remaining ); event Revoked( address indexed beneficiary, uint256 indexed allocationId, IERC20 token, uint256 allocationAmount, uint256 revokedAmount ); struct Allocation { IERC20 token; uint256 start; uint256 cliff; uint256 duration; uint256 total; uint256 claimed; } /** * @dev Creates a new allocation for a beneficiary. Tokens are released * linearly over time until a given number of seconds have passed since the * start of the vesting schedule. Callable only by issuers. * @param _beneficiary The address to which tokens will be released * @param _amount The amount of the allocation (in wei) * @param _startAt The unix timestamp at which the vesting may begin * @param _cliff The number of seconds after _startAt before which no vesting occurs * @param _duration The number of seconds after which the entire allocation is vested */ function issue( address _beneficiary, IERC20 _token, uint256 _amount, uint256 _startAt, uint256 _cliff, uint256 _duration ) external; /** * @dev Revokes an existing allocation. Any unclaimed tokens are recalled * and sent to the caller. Callable only be issuers. * @param _beneficiary The address whose allocation is to be revoked * @param _id The allocation ID to revoke */ function revoke( address _beneficiary, uint256 _id ) external; /** * @dev Transfers vested tokens from any number of allocations to their beneficiary. Callable by anyone. May be gas-intensive. * @param _beneficiary The address that has vested tokens * @param _ids The vested allocation indexes */ function release( address _beneficiary, uint256[] calldata _ids ) external; /** * @dev Gets the number of allocations issued for a given address. * @param _beneficiary The address to check for allocations */ function allocationCount( address _beneficiary ) external view returns ( uint256 count ); /** * @dev Gets details about a given allocation. * @param _beneficiary Address to check * @param _id The allocation index * @return allocation The allocation * @return vested The total amount vested to date * @return releasable The amount currently releasable */ function allocationSummary( address _beneficiary, uint256 _id ) external view returns ( Allocation memory allocation, uint256 vested, uint256 releasable ); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; import "./ManagedPool.sol"; import "./Slashable.sol"; /** * @title StakingPool * @dev The DAOracle Network relies on decentralized risk pools. This is a * simple implementation of a staking pool which wraps a single arbitrary token * and provides a mechanism for recouping losses incurred by the deployer of * the staking pool. Pool ownership is represented as ERC20 tokens that can be * freely used as the holder sees fit. Holders of pool shares may make claims * proportional to their stake on the underlying token balance of the pool. Any * rewards or penalties applied to the pool will thus impact all holders. */ contract StakingPool is ERC20, ERC20Permit, ManagedPool, Slashable { using SafeERC20 for IERC20; constructor( ERC20 _token, uint256 _mintFee, uint256 _burnFee, address _feePayee ) ERC20( _concat("StakingPool: ", _token.name()), _concat("dp", _token.symbol()) ) ERC20Permit(_concat("StakingPool: ", _token.name())) { stakedToken = IERC20(_token); mintFee = _mintFee; burnFee = _burnFee; feePayee = _feePayee; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MANAGER, msg.sender); _setupRole(SLASHER, msg.sender); stakedToken.safeApprove(msg.sender, 2**256 - 1); emit Created(address(this), stakedToken); } function underlying() public view override returns (IERC20) { return stakedToken; } function _concat(string memory a, string memory b) internal pure returns (string memory) { return string(bytes.concat(bytes(a), bytes(b))); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; import "./ManagedPool.sol"; /** * @title SponsorPool */ contract SponsorPool is ERC20, ERC20Permit, ManagedPool { using SafeERC20 for IERC20; constructor(ERC20 _token) ERC20( _concat("SponsorPool: ", _token.name()), _concat("f", _token.symbol()) ) ERC20Permit(_concat("SponsorPool: ", _token.name())) { stakedToken = IERC20(_token); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MANAGER, msg.sender); stakedToken.safeApprove(msg.sender, 2**256 - 1); emit Created(address(this), stakedToken); } function _concat(string memory a, string memory b) internal pure returns (string memory) { return string(bytes.concat(bytes(a), bytes(b))); } } // 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/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); } // 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: 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 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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 (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.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 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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - 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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @title ManagedPool * @dev The DAOracle Network relies on decentralized risk pools. This is a * simple implementation of a staking pool which wraps a single arbitrary token * and provides a mechanism for recouping losses incurred by the deployer of * the underlying. Pool ownership is represented as ERC20 tokens that can be * freely used as the holder sees fit. Holders of pool shares may make claims * proportional to their stake on the underlying token balance of the pool. Any * rewards or penalties applied to the pool will thus impact all holders. */ abstract contract ManagedPool is AccessControl, ERC20 { using SafeERC20 for IERC20; bytes32 public immutable MANAGER = keccak256("MANAGER"); /// @dev The token being staked in this pool IERC20 public stakedToken; /** * @dev The mint/burn fee config. Fees must be scaled by 10**18 (1e18 = 100%) * Formula: fee = tokens * mintOrBurnFee / 1e18 * Example: 1000 DAI deposit * (0.1 * 10**18) / 10**18 = 100 DAI fee */ uint256 public mintFee; uint256 public burnFee; address public feePayee; event Created(address pool, IERC20 underlying); event FeesChanged(uint256 mintFee, uint256 burnFee, address payee); event Fee(uint256 feeAmount); event Deposit( address indexed depositor, uint256 underlyingAmount, uint256 tokensMinted ); event Payout( address indexed beneficiary, uint256 underlyingAmount, uint256 tokensBurned ); /** * @dev Mint pool shares for a given stake amount * @param _stakeAmount The amount of underlying to stake * @return shares The number of pool shares minted */ function mint(uint256 _stakeAmount) external returns (uint256 shares) { require( stakedToken.allowance(msg.sender, address(this)) >= _stakeAmount, "mint: insufficient allowance" ); // Grab the pre-deposit balance and shares for comparison uint256 oldBalance = stakedToken.balanceOf(address(this)); uint256 oldShares = totalSupply(); // Pull user's tokens into the pool stakedToken.safeTransferFrom(msg.sender, address(this), _stakeAmount); // Calculate the fee for minting uint256 fee = (_stakeAmount * mintFee) / 1e18; if (fee != 0) { stakedToken.safeTransfer(feePayee, fee); _stakeAmount -= fee; emit Fee(fee); } // Calculate the pool shares for the new deposit if (oldShares != 0) { // shares = stake * oldShares / oldBalance shares = (_stakeAmount * oldShares) / oldBalance; } else { // if no shares exist, just assign 1,000 shares (it's arbitrary) shares = 10**3; } // Transfer shares to caller _mint(msg.sender, shares); emit Deposit(msg.sender, _stakeAmount, shares); } /** * @dev Burn some pool shares and claim the underlying tokens * @param _shareAmount The number of shares to burn * @return tokens The number of underlying tokens returned */ function burn(uint256 _shareAmount) external returns (uint256 tokens) { require(balanceOf(msg.sender) >= _shareAmount, "burn: insufficient shares"); // TODO: Extract // Calculate the user's share of the underlying balance uint256 balance = stakedToken.balanceOf(address(this)); tokens = (_shareAmount * balance) / totalSupply(); // Burn the caller's shares before anything else _burn(msg.sender, _shareAmount); // Calculate the fee for burning uint256 fee = getBurnFee(tokens); if (fee != 0) { tokens -= fee; stakedToken.safeTransfer(feePayee, fee); emit Fee(fee); } // Transfer underlying tokens back to caller stakedToken.safeTransfer(msg.sender, tokens); emit Payout(msg.sender, tokens, _shareAmount); } /** * @dev Calculate the minting fee * @param _amount The number of tokens being staked * @return fee The calculated fee value */ function getMintFee(uint256 _amount) public view returns (uint256 fee) { fee = (_amount * mintFee) / 1e18; } /** * @dev Calculate the burning fee * @param _amount The number of pool tokens being burned * @return fee The calculated fee value */ function getBurnFee(uint256 _amount) public view returns (uint256 fee) { fee = (_amount * burnFee) / 1e18; } /** * @dev Update fee configuration * @param _mintFee The new minting fee * @param _burnFee The new burning fee * @param _feePayee The new payee */ function setFees( uint256 _mintFee, uint256 _burnFee, address _feePayee ) external onlyRole(MANAGER) { mintFee = _mintFee; burnFee = _burnFee; feePayee = _feePayee; emit FeesChanged(_mintFee, _burnFee, _feePayee); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; abstract contract Slashable is AccessControl, IERC20 { using SafeERC20 for IERC20; /// @dev Precomputed hash for "SLASHER" role ID bytes32 public immutable SLASHER = keccak256("SLASHER"); /// @dev Slash event event Slash(address indexed slasher, IERC20 token, uint256 amount); /// @dev The slashable asset function underlying() public view virtual returns (IERC20); /** * @dev Slash the pool by a given amount. Callable by the owner. * @param amount The amount of tokens to slash * @param receiver The recipient of the slashed assets */ function slash(uint256 amount, address receiver) external onlyRole(SLASHER) { IERC20 token = underlying(); require( token.balanceOf(address(this)) >= amount, "slash: insufficient balance" ); token.safeTransfer(receiver, amount); emit Slash(msg.sender, token, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
@dev Precomputed hash for "SLASHER" role ID @dev Slash event @dev The slashable asset* @dev Slash the pool by a given amount. Callable by the owner. @param amount The amount of tokens to slash @param receiver The recipient of the slashed assets/
function slash(uint256 amount, address receiver) external onlyRole(SLASHER) { IERC20 token = underlying(); require( token.balanceOf(address(this)) >= amount, "slash: insufficient balance" ); token.safeTransfer(receiver, amount); emit Slash(msg.sender, token, amount); }
10,222,506
[ 1, 1386, 20307, 1651, 364, 315, 24079, 654, 6, 2478, 1599, 225, 9708, 961, 871, 225, 1021, 9026, 429, 3310, 225, 9708, 961, 326, 2845, 635, 279, 864, 3844, 18, 10464, 635, 326, 3410, 18, 225, 3844, 1021, 3844, 434, 2430, 358, 9026, 225, 5971, 1021, 8027, 434, 326, 9026, 329, 7176, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 9026, 12, 11890, 5034, 3844, 16, 1758, 5971, 13, 3903, 1338, 2996, 12, 24079, 654, 13, 288, 203, 565, 467, 654, 39, 3462, 1147, 273, 6808, 5621, 203, 565, 2583, 12, 203, 1377, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 3844, 16, 203, 1377, 315, 12877, 30, 2763, 11339, 11013, 6, 203, 565, 11272, 203, 203, 565, 1147, 18, 4626, 5912, 12, 24454, 16, 3844, 1769, 203, 565, 3626, 9708, 961, 12, 3576, 18, 15330, 16, 1147, 16, 3844, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.18; /** * For convenience, you can delete all of the code between the <ORACLIZE_API> * and </ORACLIZE_API> tags as etherscan cannot use the import callback, you * can then just uncomment the line below and compile it via Remix. */ //import "github.com/oraclize/ethereum-api/oraclizeAPI.sol"; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity >=0.4.18;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // 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)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ 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(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } // </ORACLIZE_API> /*===========================================================================================* *************************************** https://p4d.io *************************************** *============================================================================================* * * ,-.----. ,--, * \ / \ ,--.'| ,---, * | : \ ,--, | : .' .' `\ ____ __ * | | .\ :,---.'| : ',---.' \ / __ \________ ________ ____ / /______ * . : |: |; : | | ;| | .`\ | / /_/ / ___/ _ \/ ___/ _ \/ __ \/ __/ ___/ * | | \ :| | : _' |: : | ' | / ____/ / / __(__ ) __/ / / / /_(__ ) * | : . /: : |.' || ' ' ; : /_/ /_/___\\\_/____/\_\\/_\_/_/\__/____/ * ; | |`-' | ' ' ; :' | ; . | /_ __/___ \ \/ /___ __ __ * | | ; \ \ .'. || | : | ' / / / __ \ \ / __ \/ / / / * : ' | `---`: | '' : | / ; / / / /_/ / / / /_/ / /_/ / * : : : ' ; || | '` ,/ /_/ \____/ /_/\____/\__,_/ * | | : | : ;; : .' * `---'.| ' ,/ | ,.' * `---` '--' '---' * * _______ _ _____ _ * (_______) | (____ \ | |_ * _____ | |_ _ _ _ _ \ \ ____| | |_ ____ * | ___) | | | | ( \ / ) | | / _ ) | _)/ _ | * | | | | |_| |) X (| |__/ ( (/ /| | |_( ( | | * |_| |_|\____(_/ \_)_____/ \____)_|\___)_||_| * * ____ * /\ \ * / \ \ * / \ \ * / \ \ * / /\ \ \ * / / \ \ \ * / / \ \ \ * / / / \ \ \ * / / / \ \ \ * / / /---------' \ * / / /_______________\ * \ / / * \/_____________________/ * _ ___ _ _ ___ * /_\ / __\___ _ __ | |_ _ __ __ _ ___| |_ / __\_ _ * //_\\ / / / _ \| '_ \| __| '__/ _` |/ __| __| /__\// | | | * / _ \ / /__| (_) | | | | |_| | | (_| | (__| |_ / \/ \ |_| | * \_/ \_/ \____/\___/|_| |_|\__|_| \__,_|\___|\__| \_____/\__, | * ╔═╗╔═╗╦ ╔╦╗╔═╗╦ ╦ |___/ * ╚═╗║ ║║ ║║║╣ ╚╗╔╝ * ╚═╝╚═╝╩═╝────═╩╝╚═╝ ╚╝ * 0x736f6c5f646576 * ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ * */ // P3D interface interface P3D { function sell(uint256) external; function myTokens() external view returns(uint256); function myDividends(bool) external view returns(uint256); function withdraw() external; } // P4D interface interface P4D { function buy(address) external payable returns(uint256); function sell(uint256) external; function transfer(address, uint256) external returns(bool); function myTokens() external view returns(uint256); function myStoredDividends() external view returns(uint256); function mySubdividends() external view returns(uint256); function withdraw(bool) external; function withdrawSubdivs(bool) external; function P3D_address() external view returns(address); function setCanAcceptTokens(address) external; } /** * An inheritable contract structure that connects to the P4D exchange * This will then point to the P3D exchange as well as providing the tokenCallback() function */ contract usingP4D { P4D internal tokenContract; P3D internal _P3D; function usingP4D(address _P4D_address) public { tokenContract = P4D(_P4D_address); _P3D = P3D(tokenContract.P3D_address()); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } function tokenCallback(address _from, uint256 _value, bytes _data) external returns (bool); } /** * This is the coin-pair contract, the main FluxDelta contract will create a new coin-pair * contract every time a pairing is added to the network. The FluxDelta contract is be able * to manage the coin-pair in respect to setting its UI visibility as well as the coin-pairs * callback gas price in case the network gets congested. * Each coin-pair contract is self-managing and has its own P4D, P3D and ETH balances. In * order to keep affording to pay for Oraclize calls, it will always maintain a certain * amount of ETH and should it drop beneath a certain threshold, it will sell some of the * P3D that it holds. If it has a surplus of ETH, it will use the excess to purchase more * P4D that will go towards the global withdrawable pot. * A user can invest into a coin-pair via the P4D exchange contract using the transferAndCall() * function and they can withdraw their P4D shares via the main FluxDelta contract using the * withdrawFromCoinPair() function. */ contract CoinPair is usingP4D, usingOraclize { using SafeMath for uint256; struct OraclizeMap { address _sender; bool _isNextShort; uint256 _sentValue; } mapping(bytes32 => OraclizeMap) private _oraclizeCallbackMap; event RequestSubmitted(bytes32 id); uint256 constant private _devOwnerCut = 1; // 1% of deposits are used as dev fees uint256 constant private _minDeposit = 100e18; // we need to cover Oraclize at a bare minimum uint256 constant private _sellThreshold = 0.1 ether; // if the balance drops below this, sell P4D uint256 constant private _buyThreshold = 0.2 ether; // if the balance goes above this, buy P4D int256 constant private _baseSharesPerRequest = 1e18; // 1% * 100e18 address private _dev; // main developer; will receive 0.5% of P4D deposits address private _owner; // a nominated owner; they will also receive 0.5% of the depost address private _creator; // the parent FluxDelta contract uint256 private _devBalance = 0; uint256 private _ownerBalance = 0; uint256 private _processingP4D = 0; bytes32 public fSym; bytes32 public tSym; uint256 constant public baseCost = 100e18; // 100 P4D tokens uint256 public shares; mapping(address => uint256) public sharesOf; mapping(address => uint256) public scalarOf; mapping(address => bool) public isShorting; mapping(address => uint256) public lastPriceOf; mapping(address => uint256) public lastPriceTimeOf; bool public isVisible; /** * Modifier for restricting a call to just the FluxDelta contract */ modifier onlyCreator { require(msg.sender == _creator); _; } /** * Coin-pair constructor; * _fSym: From symbol (eg ETH) * _tSym: To symbol (eg USD) * _ownerAddress: Nominated owner, will receive 0.5% of all deposits * _devAddress: FluxDelta dev, will also receive 0.5% of all deposits * _P4D_address: P4D exchange address reference */ function CoinPair(string _fSym, string _tSym, address _ownerAddress, address _devAddress, address _P4D_address) public payable usingP4D(_P4D_address) { require (msg.value >= _sellThreshold); require(_ownerAddress != _devAddress && _ownerAddress != msg.sender && _devAddress != msg.sender); _creator = msg.sender; fSym = _stringToBytes32(_fSym); tSym = _stringToBytes32(_tSym); shares = 0; _owner = _ownerAddress; _dev = _devAddress; isVisible = true; changeOraclizeGasPrice(16e9); // 16 Gwei for all callbacks } /** * Main point of interaction within a coin-pair, the P4D contract will call this function * after a customer has sent P4D using the transferAndCall() function to this address. * This function sets up all of the required information in order to make a call to the * internet via Oraclize, this will fetch the current price of the coin-pair without needing * to worry about a user tampering with the data. * Oraclize is a paid service and requires ETH to use, this contract must pay a fee for the * internet call itself as well as the gas cost to cover the __callback() function below. */ function tokenCallback(address _from, uint256 _value, bytes _data) external onlyTokenContract returns (bool) { require(_value >= _minDeposit); require(!_isContract(_from)); require(_from != _dev && _from != _owner && _from != _creator); uint256 fees = _value.mul(_devOwnerCut).div(100); // 1% _devBalance = _devBalance.add(fees.div(2)); // 0.5% _ownerBalance = _ownerBalance.add(fees.div(2)); // 0.5% _processingP4D = _processingP4D.add(_value); ///////////////////////////////////////////////////////////////////////////////// // // The block of code below is responsible for using all of the P4D and P3D // dividends in order to both maintain and afford to pay for Oraclize calls // as well as purchasing more P4D to put towards the global pot should there // be an excess of ETH // // first withdraw all ETH subdividends from the P4D contract if (tokenContract.mySubdividends() > 0) { tokenContract.withdrawSubdivs(true); } // if this contracts ETH balance is less than the threshold, sell a minimum // P4D deposit (100 P4D) then sell 1/4 of all the held P3D in this contract // // if this contracts ETH balance is more than the buying threshold, use this // excess ETH to purchase more P4D to put in the global withdrawable pot if (address(this).balance < _sellThreshold) { tokenContract.sell(_minDeposit); tokenContract.withdraw(true); _P3D.sell(_P3D.myTokens().div(4)); // sell 1/4 of all P3D held by the contract } else if (address(this).balance > _buyThreshold) { uint256 diff = address(this).balance.sub(_buyThreshold); tokenContract.buy.value(diff)(_owner); // use the owner as a ref } // if there's any stored P3D dividends, withdraw and hold them if (tokenContract.myStoredDividends() > 0) { tokenContract.withdraw(true); } // finally, check if there's any ETH divs to withdraw from the P3D contract if (_P3D.myDividends(true) > 0) { _P3D.withdraw(); } ///////////////////////////////////////////////////////////////////////////////// uint256 gasLimit = 220000; if (lastPriceOf[_from] != 0) { gasLimit = 160000; require(_value.mul(1e18).div(baseCost) == scalarOf[_from]); // check if they sent the right amount } // parse the URL data for Oraclize string memory tSymString = strConcat("&tsyms=", _bytes32ToString(tSym), ").", _bytes32ToString(tSym)); bytes32 queryId = oraclize_query("URL", strConcat("json(https://min-api.cryptocompare.com/data/price?fsym=", _bytes32ToString(fSym), tSymString), gasLimit); uint256 intData = _bytesToUint(_data); OraclizeMap memory map = OraclizeMap({ _sender: _from, _isNextShort: intData != 0, _sentValue: _value }); _oraclizeCallbackMap[queryId] = map; RequestSubmitted(queryId); return true; } /** * Oraclize callback function for returning data */ function __callback(bytes32 myid, string result) public { require(msg.sender == oraclize_cbAddress()); _handleCallback(myid, result); } /** * Internally handled callback, this function is responsible for updating the shares gained/lost * of a user once they've invested in a coin-pair. If you have already invested in the coin-pair * before, this will compare your last locked in price to the current price and provide you shares * based on the gain/loss of the coin-pair (as well as being multiplied by your staked P4D amount). */ function _handleCallback(bytes32 _id, string _result) internal { OraclizeMap memory mappedInfo = _oraclizeCallbackMap[_id]; address receiver = mappedInfo._sender; require(receiver != address(0x0)); int256 latestPrice = int256(parseInt(_result, 18)); // 18 decimal places if (latestPrice > 0) { int256 lastPrice = int256(lastPriceOf[receiver]); if (lastPrice == 0) { // we are starting from the beginning lastPriceTimeOf[receiver] = now; lastPriceOf[receiver] = uint256(latestPrice); scalarOf[receiver] = mappedInfo._sentValue.mul(1e18).div(baseCost); sharesOf[receiver] = uint256(_baseSharesPerRequest) * scalarOf[receiver] / 1e18; isShorting[receiver] = mappedInfo._isNextShort; shares = shares.add(uint256(_baseSharesPerRequest) * scalarOf[receiver] / 1e18); } else { // they already have a price recorded so find the gain/loss if (mappedInfo._sentValue.mul(1e18).div(baseCost) == scalarOf[receiver]) { int256 delta = _baseSharesPerRequest + ((isShorting[receiver] ? int256(-1) : int256(1)) * ((100e18 * (latestPrice - lastPrice)) / lastPrice)); // in terms of % (18 decimals) + base gain (+1%) delta = delta * int256(scalarOf[receiver]) / int256(1e18); int256 currentShares = int256(sharesOf[receiver]); if (currentShares + delta > _baseSharesPerRequest * int256(scalarOf[receiver]) / int256(1e18)) { sharesOf[receiver] = uint256(currentShares + delta); } else { sharesOf[receiver] = uint256(_baseSharesPerRequest) * scalarOf[receiver] / 1e18; } lastPriceTimeOf[receiver] = now; lastPriceOf[receiver] = uint256(latestPrice); isShorting[receiver] = mappedInfo._isNextShort; shares = uint256(int256(shares) + int256(sharesOf[receiver]) - currentShares); } else { // something strange has happened so refund the P4D require(tokenContract.transfer(receiver, mappedInfo._sentValue)); } } } else { // price returned an error so refund the P4D require(tokenContract.transfer(receiver, mappedInfo._sentValue)); } _processingP4D = _processingP4D.sub(mappedInfo._sentValue); delete _oraclizeCallbackMap[_id]; } /** * Should there be any problems with Oraclize such as a callback running out of gas or * reverting, you are able to refund the P4D you sent to the contract. This will only * work if the __callback() function has not been successful. */ function requestRefund(bytes32 _id) external { OraclizeMap memory mappedInfo = _oraclizeCallbackMap[_id]; address receiver = mappedInfo._sender; require(msg.sender == receiver); uint256 refundable = mappedInfo._sentValue; _processingP4D = _processingP4D.sub(refundable); delete _oraclizeCallbackMap[_id]; require(tokenContract.transfer(receiver, refundable)); } /** * Liquidate your shares to P4D */ function withdraw(address _user) external onlyCreator { uint256 withdrawableP4D = getWithdrawableOf(_user); if (withdrawableP4D > 0) { if (_user == _dev) { _devBalance = 0; } else if (_user == _owner) { _ownerBalance = 0; } else { shares = shares.sub(sharesOf[_user]); sharesOf[_user] = 0; scalarOf[_user] = 0; lastPriceOf[_user] = 0; lastPriceTimeOf[_user] = 0; } require(tokenContract.transfer(_user, withdrawableP4D)); } else if (sharesOf[_user] == 0) { // they are restarting scalarOf[_user] = 0; lastPriceOf[_user] = 0; lastPriceTimeOf[_user] = 0; } } /** * Change the UI visibility of the coin-pair * Although a coin-pair may be hidden, a customer can still interact with it without restrictions */ function setVisibility(bool _isVisible) external onlyCreator { isVisible = _isVisible; } /** * Ability to change the gas price for callbacks in case the network becomes congested */ function changeOraclizeGasPrice(uint256 _gasPrice) public onlyCreator { oraclize_setCustomGasPrice(_gasPrice); } /** * Retrieve the total withdrawable P4D pot */ function getTotalPot() public view returns (uint256) { return tokenContract.myTokens().sub(_devBalance).sub(_ownerBalance).sub(_processingP4D.mul(uint256(100).sub(_devOwnerCut)).div(100)); } /** * Retrieve the total withdrawable P4D of an individual customer */ function getWithdrawableOf(address _user) public view returns (uint256) { if (_user == _dev) { return _devBalance; } else if (_user == _owner) { return _ownerBalance; } else { return (shares == 0 ? 0 : getTotalPot().mul(sharesOf[_user]).div(shares)); } } /** * Utility function to convert strings into fixed length byte arrays */ function _stringToBytes32(string memory _s) internal pure returns (bytes32 result) { bytes memory tmpEmptyStringTest = bytes(_s); if (tmpEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_s, 32)) } } /** * Utility function to make bytes32 data readable */ function _bytes32ToString(bytes32 _b) internal pure returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 i = 0; i < 32; i++) { byte char = byte(bytes32(uint(_b) * 2 ** (8 * i))); if (char != 0) { bytesString[charCount++] = char; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (i = 0; i < charCount; i++) { bytesStringTrimmed[i] = bytesString[i]; } return string(bytesStringTrimmed); } /** * Utility function to convert bytes into an integer */ function _bytesToUint(bytes _b) internal pure returns (uint256 result) { result = 0; for (uint i = 0; i < _b.length; i++) { result += uint(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } } /** * Utility function to check if an address is a contract */ function _isContract(address _a) internal view returns (bool) { uint size; assembly { size := extcodesize(_a) } return size > 0; } /** * Payable function for receiving dividends from the P4D and P3D contracts */ function () public payable { require(msg.sender == address(tokenContract) || msg.sender == address(_P3D) || msg.sender == _dev || msg.sender == _owner); // only accept ETH payments from P4D and P3D (subdividends and dividends) as well // as allowing the owner or dev to top up this contracts balance // // all ETH sent through this function will be used in the tokenCallback() function // in order to buy more P4D (if there's excess) and pay for Oraclize calls } } /** * This is the core FluxDelta contract, it is primarily a contract factory that * is able to create any number of coin-pair sub-contracts. On top of this, it is * also used as an efficient way to return all of the data needed for the front-end. */ contract FluxDelta is usingP4D { using SafeMath for uint256; CoinPair[] private _coinPairs; address private _owner; modifier onlyOwner { require(msg.sender == _owner); _; } /** * Application entry point */ function FluxDelta(address _P4D_address) public usingP4D(_P4D_address) { _owner = msg.sender; } /** * Coin-pair creation function, this function will also allow this newly created pair to receive P4D * tokens via the setCanAcceptTokens() function. This means that the FluxDetla contract will be * granted administrator permissions in the P4D contract although this is the only method it uses. */ function createCoinPair(string _fromSym, string _toSym, address _ownerAddress) external payable onlyOwner { CoinPair newCoinPair = (new CoinPair).value(msg.value)(_fromSym, _toSym, _ownerAddress, _owner, address(tokenContract)); _coinPairs.push(newCoinPair); tokenContract.setCanAcceptTokens(address(newCoinPair)); } /** * Liquidates your shares to P4D from a certain coin-pair */ function withdrawFromCoinPair(uint256 _index) external { require(_index < getTotalCoinPairs()); CoinPair coinPair = _coinPairs[_index]; coinPair.withdraw(msg.sender); } /** * Ability to toggle the UI visibility of a coin-pair * This will not prevent a coin-pair from being able to invest or withdraw */ function setCoinPairVisibility(uint256 _index, bool _isVisible) external onlyOwner { require(_index < getTotalCoinPairs()); CoinPair coinPair = _coinPairs[_index]; coinPair.setVisibility(_isVisible); } /** * Ability to change the callback gas price in case the network gets congested */ function setCoinPairOraclizeGasPrice(uint256 _index, uint256 _gasPrice) public onlyOwner { require(_index < getTotalCoinPairs()); CoinPair coinPair = _coinPairs[_index]; coinPair.changeOraclizeGasPrice(_gasPrice); } /** * Utility function to bulk set the callback gas price */ function setAllOraclizeGasPrices(uint256 _gasPrice) external onlyOwner { for (uint256 i = 0; i < getTotalCoinPairs(); i++) { setCoinPairOraclizeGasPrice(i, _gasPrice); } } /** * Retreive the total coin-pairs created by FluxDelta */ function getTotalCoinPairs() public view returns (uint256) { return _coinPairs.length; } /** * Retreive the total visible coin-pairs */ function getTotalVisibleCoinPairs() internal view returns (uint256 count) { count = 0; for (uint256 i = 0; i < _coinPairs.length; i++) { if (_coinPairs[i].isVisible()) { count++; } } } /** * Utility function for returning all of the core information of the coin-pairs */ function getAllCoinPairs(bool _onlyVisible) public view returns (uint256[] indexes, address[] addresses, bytes32[] fromSyms, bytes32[] toSyms, uint256[] totalShares, uint256[] totalPots) { uint256 length = (_onlyVisible ? getTotalVisibleCoinPairs() : getTotalCoinPairs()); indexes = new uint256[](length); addresses = new address[](length); fromSyms = new bytes32[](length); toSyms = new bytes32[](length); totalShares = new uint256[](length); totalPots = new uint256[](length); uint256 index = 0; for (uint256 i = 0; i < getTotalCoinPairs(); i++) { CoinPair coinPair = _coinPairs[i]; if (coinPair.isVisible() || !_onlyVisible) { indexes[index] = i; addresses[index] = address(coinPair); fromSyms[index] = coinPair.fSym(); toSyms[index] = coinPair.tSym(); totalShares[index] = coinPair.shares(); totalPots[index] = coinPair.getTotalPot(); index++; } } } /** * Utility function for returning all of the shares information of the coin-pairs of a certain user */ function getAllSharesInfoOf(address _user, bool _onlyVisible) public view returns (uint256[] indexes, uint256[] userShares, uint256[] lastPrices, uint256[] lastPriceTimes, uint256[] withdrawables) { uint256 length = (_onlyVisible ? getTotalVisibleCoinPairs() : getTotalCoinPairs()); indexes = new uint256[](length); userShares = new uint256[](length); lastPrices = new uint256[](length); lastPriceTimes = new uint256[](length); withdrawables = new uint256[](length); uint256 index = 0; for (uint256 i = 0; i < getTotalCoinPairs(); i++) { CoinPair coinPair = _coinPairs[i]; if (coinPair.isVisible() || !_onlyVisible) { indexes[index] = i; userShares[index] = coinPair.sharesOf(_user); lastPrices[index] = coinPair.lastPriceOf(_user); lastPriceTimes[index] = coinPair.lastPriceTimeOf(_user); withdrawables[index] = coinPair.getWithdrawableOf(_user); index++; } } } /** * Utility function for returning all of the cost information of the coin-pairs of a certain user */ function getAllCostsInfoOf(address _user, bool _onlyVisible) public view returns (uint256[] indexes, uint256[] baseCosts, uint256[] myScalars, uint256[] myCosts, bool[] isShorting) { uint256 length = (_onlyVisible ? getTotalVisibleCoinPairs() : getTotalCoinPairs()); indexes = new uint256[](length); baseCosts = new uint256[](length); myScalars = new uint256[](length); myCosts = new uint256[](length); isShorting = new bool[](length); uint256 index = 0; for (uint256 i = 0; i < getTotalCoinPairs(); i++) { CoinPair coinPair = _coinPairs[i]; if (coinPair.isVisible() || !_onlyVisible) { indexes[index] = i; baseCosts[index] = coinPair.baseCost(); myScalars[index] = coinPair.scalarOf(_user); myCosts[index] = coinPair.baseCost().mul(coinPair.scalarOf(_user)).div(1e18); isShorting[index] = coinPair.isShorting(_user); index++; } } } /** * Because this contract inherits usingP4D it must implement this method * Returning false will not allow this contract to receive P4D (only child * coin-pair contracts are allowed to receive P4D) */ function tokenCallback(address, uint256, bytes) external returns (bool) { return false; } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b != 0); return _a % _b; } } /*===========================================================================================* *************************************** https://p4d.io *************************************** *===========================================================================================*/
* Utility function to convert bytes into an integer/
function _bytesToUint(bytes _b) internal pure returns (uint256 result) { result = 0; for (uint i = 0; i < _b.length; i++) { result += uint(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } }
12,922,068
[ 1, 6497, 445, 358, 1765, 1731, 1368, 392, 3571, 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, 445, 389, 3890, 774, 5487, 12, 3890, 389, 70, 13, 2713, 16618, 1135, 261, 11890, 5034, 563, 13, 288, 203, 3639, 563, 273, 374, 31, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 70, 18, 2469, 31, 277, 27245, 288, 203, 5411, 563, 1011, 2254, 24899, 70, 63, 77, 5717, 380, 261, 22, 2826, 261, 28, 380, 261, 67, 70, 18, 2469, 300, 261, 77, 397, 404, 3719, 10019, 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 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// IN PROCESS AND INCOMPLETE, unaudited and for demonstration only, subject to all disclosures, licenses, and caveats of the open-source-law repo /// @author Erich Dylus /// @title Airnode Escrow /// @notice bilateral smart escrow contract, with an ERC20 stablecoin as payment, expiration denominated in seconds, deposit refunded if contract expires before closeDeal() called, contingent on a boolean Airnode response /// @dev buyer should deploy (as they will separately approve() the contract address for the deposited funds, and deposit is returned to deployer if expired); note the requester-sponsor structure as well: https://docs.api3.org/airnode/v0.2/grp-developers/requesters-sponsors.html import "@api3/airnode-protocol/contracts/rrp/requesters/RrpRequester.sol"; interface IERC20 { function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); } contract AirnodeEscrow is RrpRequester { address escrowAddress; address buyer; address seller; uint256 deposit; uint256 expiryTime; bool sellerApproved; bool buyerApproved; bool isExpired; bool isClosed; IERC20 public ierc20; string description; mapping(address => bool) public parties; //map whether an address is a party to the transaction for restricted() modifier mapping(bytes32 => bool) public incomingFulfillments; mapping(bytes32 => int256) public fulfilledData; event DealExpired(bool isExpired); event DealClosed(bool isClosed, uint256 effectiveTime); //event provides exact blockstamp Unix time of closing and oracle information modifier restricted() { require(parties[msg.sender], "Only parties[]"); _; } /// @notice deployer (buyer) initiates escrow with description, deposit amount in USD, address of stablecoin, seconds until expiry, and designate recipient seller /// @param _description should be a brief identifier of the deal in question - perhaps as to parties/underlying asset/documentation reference/hash /// @param _deposit is the purchase price which will be deposited in the smart escrow contract /// @param _seller is the seller's address, who will receive the purchase price if the deal closes /// @param _stablecoin is the token contract address for the stablecoin to be sent as deposit /// @param _secsUntilExpiry is the number of seconds until the deal expires, which can be converted to days for front end input or the code can be adapted accordingly /// @param _airnodeRrp is the public address of the AirnodeRrp.sol protocol contract on the relevant blockchain used for this contract; see: https://docs.api3.org/airnode/v0.2/reference/airnode-addresses.html constructor(string memory _description, uint256 _deposit, uint256 _secsUntilExpiry, address _seller, address _stablecoin, address _airnodeRrp) RrpRequester(_airnodeRrp) { require(_seller != msg.sender, "Buyer Address"); buyer = address(msg.sender); deposit = _deposit; escrowAddress = address(this); ierc20 = IERC20(_stablecoin); description = _description; seller = _seller; parties[msg.sender] = true; parties[_seller] = true; parties[escrowAddress] = true; expiryTime = block.timestamp + _secsUntilExpiry; } /// @notice buyer may confirm seller's recipient address as extra security measure or change seller address /// @param _seller is the new recipient address of seller function designateSeller(address _seller) external restricted { require(_seller != buyer, "Buyer Address"); require(!isExpired, "Expired"); parties[_seller] = true; seller = _seller; } /// ********* DEPLOYER MUST SEPARATELY APPROVE (by interacting with the ERC20 contract in question's approve()) this contract address for the deposit amount (keep decimals in mind) ******** /// @notice buyer deposits in escrowAddress after separately ERC20-approving escrowAddress function depositInEscrow() public restricted returns(bool, uint256) { require(msg.sender == buyer, "Only buyer may deposit"); ierc20.transferFrom(buyer, escrowAddress, deposit); return (true, ierc20.balanceOf(escrowAddress)); } /// @notice escrowAddress returns deposit to buyer function returnDeposit() internal returns(bool, uint256) { ierc20.transfer(buyer, deposit); return (true, ierc20.balanceOf(escrowAddress)); } /// @notice escrowAddress sends deposit to seller function paySeller() internal returns(bool, uint256) { ierc20.transfer(seller, deposit); return (true, ierc20.balanceOf(escrowAddress)); } /// @notice check if expired, and if so, return balance to buyer function checkIfExpired() external returns(bool){ if (expiryTime <= uint256(block.timestamp)) { isExpired = true; returnDeposit(); emit DealExpired(isExpired); } else { isExpired = false; } return(isExpired); } /// @notice for seller to check if deposit is in escrowAddress function checkEscrow() external restricted view returns(uint256) { return ierc20.balanceOf(escrowAddress); } /// if buyer wishes to initiate dispute over seller breach of off chain agreement or repudiate, simply may wait for expiration without sending deposit nor calling this function function readyToClose() external restricted returns(string memory){ if (msg.sender == seller) { sellerApproved = true; return("Seller ready to close."); } else if (msg.sender == buyer) { buyerApproved = true; return("Buyer ready to close."); } else { return("Neither buyer nor seller."); } } /// @notice call the airnode which will provide a boolean response /// @dev inbound API parameters which may already be ABI encoded. Source: https://docs.api3.org/airnode/v0.2/grp-developers/call-an-airnode.html /// @param airnode the address of the relevant API provider's airnode /// @param endpointId identifier for the specific endpoint desired to access via the airnode /// @param sponsor address of the entity that pays for the fulfillment of a request & gas costs the Airnode will incur. These costs will be withdrawn from the sponsorWallet of the Airnode when the requester calls it. /// @param sponsorWallet the wallet created via mnemonic by the sponsor with the Admin CLI, funds within used by the airnode to pay gas. See https://docs.api3.org/airnode/v0.2/grp-developers/requesters-sponsors.html#what-is-a-sponsor /// @param parameters specify the API and reserved parameters (see Airnode ABI specifications at https://docs.api3.org/airnode/v0.2/reference/specifications/airnode-abi-specifications.html for how these are encoded) function callAirnode(address airnode, bytes32 endpointId, address sponsor, address sponsorWallet, bytes calldata parameters) external { bytes32 requestId = airnodeRrp.makeFullRequest( // Make the Airnode request airnode, endpointId, sponsor, sponsorWallet, address(this), this.fulfill.selector, parameters ); incomingFulfillments[requestId] = true; } /// @dev the AirnodeRrp.sol protocol contract will callback here to fulfill the request /// @param requestId generated when making the request and passed here as a reference to identify which request the response is for /// @param data for a successful response, the requested data which has been encoded. Decode by the function decode() from the abi object function fulfill(bytes32 requestId, bytes calldata data) external onlyAirnodeRrp { require(incomingFulfillments[requestId], "No Request"); delete incomingFulfillments[requestId]; int256 decodedData = abi.decode(data, (int256)); fulfilledData[requestId] = decodedData; } /// @notice checks if both buyer and seller are ready to close and expiration has not been met; if so, escrowAddress closes deal and pays seller; if not, deposit returned to buyer /// @dev if properly closes, emits event with effective time of closing ///TODO: require airnode input to paySeller() function closeDeal() public returns(bool){ require(sellerApproved && buyerApproved, "Not Approved"); if (expiryTime <= uint256(block.timestamp)) { isExpired = true; returnDeposit(); emit DealExpired(isExpired); } else { isClosed = true; paySeller(); emit DealClosed(isClosed, block.timestamp); // confirmation of deal closing and effective time upon payment to seller } return(isClosed); } }
@notice check if expired, and if so, return balance to buyer
function checkIfExpired() external returns(bool){ if (expiryTime <= uint256(block.timestamp)) { isExpired = true; returnDeposit(); emit DealExpired(isExpired); isExpired = false; } return(isExpired); }
14,095,518
[ 1, 1893, 309, 7708, 16, 471, 309, 1427, 16, 327, 11013, 358, 27037, 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, 19130, 10556, 1435, 3903, 1135, 12, 6430, 15329, 203, 3639, 309, 261, 22409, 950, 1648, 2254, 5034, 12, 2629, 18, 5508, 3719, 288, 203, 5411, 31890, 273, 638, 31, 203, 5411, 327, 758, 1724, 5621, 7010, 5411, 3626, 28998, 10556, 12, 291, 10556, 1769, 203, 5411, 31890, 273, 629, 31, 203, 3639, 289, 203, 3639, 327, 12, 291, 10556, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/62320/0xdc1513f80929568088d402955559CB7f374494ba/sources/lib/mento-core/contracts/SortedOracles.sol
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy. @param _reportExpirySeconds The number of seconds before a report is considered expired./
function initialize(uint256 _reportExpirySeconds) external initializer { _transferOwnership(msg.sender); setReportExpiry(_reportExpirySeconds); }
3,225,415
[ 1, 6668, 316, 3166, 434, 326, 3885, 358, 1699, 326, 6835, 358, 506, 731, 9974, 429, 3970, 2889, 18, 225, 389, 6006, 14633, 6762, 1021, 1300, 434, 3974, 1865, 279, 2605, 353, 7399, 7708, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 4046, 12, 11890, 5034, 389, 6006, 14633, 6762, 13, 3903, 12562, 288, 203, 565, 389, 13866, 5460, 12565, 12, 3576, 18, 15330, 1769, 203, 565, 444, 4820, 14633, 24899, 6006, 14633, 6762, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.18; 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); } 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&#39;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; } } contract ERC223 { function transfer(address _to, uint256 _value, bytes _data) public returns (bool success); } contract ERC223Receiver { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint256 _value, bytes _data) public; } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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 view returns (uint256 balance) { return balances[_owner]; } } 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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Standard223Token is StandardToken, ERC223 { using SafeMath for uint256; /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool success) { require(_to != address(0)); require(_value <= balances[msg.sender]); if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value); } } /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `_custom_fallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `_custom_fallback` function * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_to != address(0)); require(_value <= balances[msg.sender]); if(isContract(_to)) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); /* solium-disable-next-line */ assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value); } } /** * @dev Transfer the specified amount of tokens to the specified address. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint256 _value) public returns (bool success) { return transfer(_to, _value, new bytes(0)); } function transferToAddress(address _to, uint _value) private returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); ERC223Receiver reciever = ERC223Receiver(_to); reciever.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @dev Retrieve the size of the code on target address, this needs assembly. * * @param _addr The address to check if it&#39;s a contract. * * @return is_contract TRUE if it&#39;s a contract else false. */ function isContract(address _addr) private view returns (bool is_contract) { uint256 length; /* solium-disable-next-line */ assembly { length := extcodesize(_addr) } return length > 0; } } contract TrueToken is Standard223Token { string public name; string public symbol; uint8 public decimals; uint256 public INITIAL_SUPPLY = 25000000; // 25 million function TrueToken() public { name = "TRUE"; symbol = "TRUE"; decimals = 18; totalSupply_ = INITIAL_SUPPLY * 10 ** uint256(decimals); balances[msg.sender] = totalSupply_; } }
* @dev Decrease the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To decrement allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol @param _spender The address which will spend the funds. @param _subtractedValue The amount of tokens to decrease the allowance by./
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
2,330,468
[ 1, 23326, 448, 326, 3844, 434, 2430, 716, 392, 3410, 2935, 358, 279, 17571, 264, 18, 6617, 537, 1410, 506, 2566, 1347, 2935, 63, 67, 87, 1302, 264, 65, 422, 374, 18, 2974, 15267, 2935, 460, 353, 7844, 358, 999, 333, 445, 358, 4543, 576, 4097, 261, 464, 2529, 3180, 326, 1122, 2492, 353, 1131, 329, 13, 6338, 9041, 355, 483, 18485, 3155, 18, 18281, 225, 389, 87, 1302, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 389, 1717, 1575, 329, 620, 1021, 3844, 434, 2430, 358, 20467, 326, 1699, 1359, 635, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20467, 23461, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1717, 1575, 329, 620, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 11144, 273, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 15533, 203, 3639, 309, 261, 67, 1717, 1575, 329, 620, 405, 11144, 13, 288, 203, 5411, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 374, 31, 203, 5411, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 11144, 18, 1717, 24899, 1717, 1575, 329, 620, 1769, 203, 3639, 289, 203, 3639, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 19226, 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 ]
pragma solidity ^0.4.18; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; import '../token/ERC20.sol'; /** * @title ControlledByVote * * @dev ControlledByVote is contract between token holders, which can vote * for a candidate by transfering the token they own. * * The duration of the voting procedure is limited by min and max voting duration. * The voting starts on call startVoting method, with the new candidate as argument and * finishes_at timestamp of the voting completion. * Token holders then can transfer their token to this contract or to candidate on their choice. * On the finishes_at time or later, method finishVoting can be called, which calculates * the balances of token on this contract and on candidate, compares them and makes a decision * who wins. * * @author Aleksey Studnev <[email protected]> */ contract ControlledByVote { ERC20 public token; uint public min_voting_duration; uint public max_voting_duration; ControlledByVote public candidate; uint public finishes_at; bool public voices_counted; bool public candidate_wins; event VotingStarted( address indexed candidate, address indexed token, uint finishes_at); event VotingCompleted( address indexed candidate, address indexed token, bool candidate_wins, uint voices_pro, uint voices_cons); using SafeMath for uint256; /** * @dev Throws if called when voting is in progress */ modifier onlyNoVoting() { if(address(candidate) != address(0)){ require(now > finishes_at); require(voices_counted); require(!candidate_wins); } _; } /** * @dev Throws if called with argument which is not winner in voting */ modifier onlyVotedFor(ControlledByVote _vote_for) { require(candidate != address(0)); require(candidate == _vote_for); require(now > finishes_at); require(voices_counted); require(candidate_wins); _; } /** * @dev constructor for the contract * @param _token used for voting * @param _min_voting_duration minimum duration of voting in seconds * @param _max_voting_duration maximum duration of voting in seconds */ function ControlledByVote( ERC20 _token, uint _min_voting_duration, uint _max_voting_duration ) public { require( address(_token) != address(0)); require( _max_voting_duration >= _min_voting_duration); require( _max_voting_duration > 0 ); token = _token; min_voting_duration = _min_voting_duration; max_voting_duration = _max_voting_duration; } /** * @dev starts new voting if allowed * @param _candidate new candidate for voting * @param _finishes_at timestampp of voting completion */ function startVoting(ControlledByVote _candidate, uint _finishes_at) onlyNoVoting public { require(address(_candidate) != address(0)); require(_candidate.token() == token); require(_finishes_at >= now.add(min_voting_duration)); require(_finishes_at <= now.add(max_voting_duration)); candidate = _candidate; finishes_at = _finishes_at; voices_counted = false; VotingStarted( candidate, token, finishes_at); } /** * @dev finish the voting */ function finishVoting() public { require(address(candidate) != address(0)); require(now > finishes_at); require(!voices_counted); uint voices_cons = token.balanceOf(this); uint voices_pro = token.balanceOf(candidate); candidate_wins = voices_pro > voices_cons; voices_counted = true; VotingCompleted( candidate, token, candidate_wins, voices_pro, voices_cons); } /** * @return true if voting is in progress */ function votingInProgress() public view returns(bool){ return candidate!=address(0) && (now <= finishes_at); } }
* @dev finish the voting/
function finishVoting() public { require(address(candidate) != address(0)); require(now > finishes_at); require(!voices_counted); uint voices_cons = token.balanceOf(this); uint voices_pro = token.balanceOf(candidate); candidate_wins = voices_pro > voices_cons; voices_counted = true; VotingCompleted( candidate, token, candidate_wins, voices_pro, voices_cons); }
5,458,179
[ 1, 13749, 326, 331, 17128, 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 ]
[ 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, 4076, 58, 17128, 1435, 1071, 288, 203, 203, 3639, 2583, 12, 2867, 12, 19188, 13, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 3338, 405, 27609, 67, 270, 1769, 203, 3639, 2583, 12, 5, 12307, 1242, 67, 1883, 329, 1769, 203, 203, 3639, 2254, 331, 17725, 67, 8559, 565, 273, 1147, 18, 12296, 951, 12, 2211, 1769, 203, 3639, 2254, 331, 17725, 67, 685, 377, 273, 1147, 18, 12296, 951, 12, 19188, 1769, 203, 203, 3639, 5500, 67, 91, 2679, 273, 331, 17725, 67, 685, 405, 331, 17725, 67, 8559, 31, 203, 3639, 331, 17725, 67, 1883, 329, 273, 638, 31, 203, 203, 3639, 776, 17128, 9556, 12, 5500, 16, 1147, 16, 5500, 67, 91, 2679, 16, 331, 17725, 67, 685, 16, 331, 17725, 67, 8559, 1769, 203, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; contract MinimalProxyFactory { using Address for address; address public implementation; bytes public code; bytes32 public codeHash; event ProxyCreated(address indexed _address, bytes32 _salt); event ImplementationSet( address indexed _implementation, bytes32 _codeHash, bytes _code ); /** * @notice Create the contract * @param _implementation - contract implementation */ constructor(address _implementation) { _setImplementation(_implementation); } /** * @notice Create a contract * @param _salt - arbitrary 32 bytes hexa * @param _data - call data used to call the contract already created if passed * @return addr - address of the contract created */ function _createProxy(bytes32 _salt, bytes memory _data) internal virtual returns (address addr) { bytes memory slotcode = code; bytes32 salt = keccak256(abi.encodePacked(_salt, msg.sender, _data)); // solium-disable-next-line security/no-inline-assembly assembly { addr := create2(0, add(slotcode, 0x20), mload(slotcode), salt) } require( addr != address(0), "MinimalProxyFactory#createProxy: CREATION_FAILED" ); emit ProxyCreated(addr, _salt); if (_data.length > 0) { (bool success, ) = addr.call(_data); require(success, "MinimalProxyFactory#createProxy: CALL_FAILED"); } } /** * @notice Get a deterministics contract address * @param _salt - arbitrary 32 bytes hexa * @param _address - supposed sender of the transaction * @return address of the deterministic contract */ function getAddress( bytes32 _salt, address _address, bytes calldata _data ) external view returns (address) { return address( uint160( uint256( keccak256( abi.encodePacked( bytes1(0xff), address(this), keccak256( abi.encodePacked(_salt, _address, _data) ), codeHash ) ) ) ) ); } /** * @notice Set the contract implementation * @param _implementation - contract implementation */ function _setImplementation(address _implementation) internal { require( _implementation != address(0) && _implementation.isContract(), "MinimalProxyFactory#_setImplementation: INVALID_IMPLEMENTATION" ); // Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol code = abi.encodePacked( hex"3d602d80600a3d3981f3363d3d373d3d3d363d73", _implementation, hex"5af43d82803e903d91602b57fd5bf3" ); codeHash = keccak256(code); implementation = _implementation; emit ImplementationSet(implementation, codeHash, code); } }
* @notice Create a contract @param _salt - arbitrary 32 bytes hexa @param _data - call data used to call the contract already created if passed @return addr - address of the contract created/ solium-disable-next-line security/no-inline-assembly
function _createProxy(bytes32 _salt, bytes memory _data) internal virtual returns (address addr) { bytes memory slotcode = code; bytes32 salt = keccak256(abi.encodePacked(_salt, msg.sender, _data)); assembly { addr := create2(0, add(slotcode, 0x20), mload(slotcode), salt) } require( addr != address(0), "MinimalProxyFactory#createProxy: CREATION_FAILED" ); emit ProxyCreated(addr, _salt); if (_data.length > 0) { (bool success, ) = addr.call(_data); require(success, "MinimalProxyFactory#createProxy: CALL_FAILED"); } }
13,121,958
[ 1, 1684, 279, 6835, 225, 389, 5759, 300, 11078, 3847, 1731, 3827, 69, 225, 389, 892, 300, 745, 501, 1399, 358, 745, 326, 6835, 1818, 2522, 309, 2275, 327, 3091, 300, 1758, 434, 326, 6835, 2522, 19, 3704, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 389, 2640, 3886, 12, 3890, 1578, 389, 5759, 16, 1731, 3778, 389, 892, 13, 203, 3639, 2713, 203, 3639, 5024, 203, 3639, 1135, 261, 2867, 3091, 13, 203, 565, 288, 203, 3639, 1731, 3778, 4694, 710, 273, 981, 31, 203, 3639, 1731, 1578, 4286, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 5759, 16, 1234, 18, 15330, 16, 389, 892, 10019, 203, 203, 3639, 19931, 288, 203, 5411, 3091, 519, 752, 22, 12, 20, 16, 527, 12, 14194, 710, 16, 374, 92, 3462, 3631, 312, 945, 12, 14194, 710, 3631, 4286, 13, 203, 3639, 289, 203, 3639, 2583, 12, 203, 5411, 3091, 480, 1758, 12, 20, 3631, 203, 5411, 315, 2930, 2840, 3886, 1733, 7, 2640, 3886, 30, 9666, 2689, 67, 11965, 6, 203, 3639, 11272, 203, 203, 3639, 3626, 7659, 6119, 12, 4793, 16, 389, 5759, 1769, 203, 203, 3639, 309, 261, 67, 892, 18, 2469, 405, 374, 13, 288, 203, 5411, 261, 6430, 2216, 16, 262, 273, 3091, 18, 1991, 24899, 892, 1769, 203, 5411, 2583, 12, 4768, 16, 315, 2930, 2840, 3886, 1733, 7, 2640, 3886, 30, 22753, 67, 11965, 8863, 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 ]
//Address: 0xa71074b6c4a31c1d1798b04801a89d78f6e26123 //Contract name: VNETToken //Balance: 0 Ether //Verification Date: 5/3/2018 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.21; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed _from, address indexed _to, uint256 _value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title 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 { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } /** * @dev Rescue compatible ERC20Basic Token * * @param _token ERC20Basic The address of the token contract */ function rescueTokens(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); assert(_token.transfer(owner, balance)); } /** * @dev Withdraw Ether */ function withdrawEther() external onlyOwner { owner.transfer(address(this).balance); } } /** * @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) { 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 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; } /** * @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; } } /** * @title Basic token, Lockable * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; uint256 totalSupply_; mapping(address => uint256) balances; mapping(address => uint256) lockedBalanceMap; // locked balance: address => amount mapping(address => uint256) releaseTimeMap; // release time: address => timestamp event BalanceLocked(address indexed _addr, uint256 _amount); /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev function to make sure the balance is not locked * @param _addr address * @param _value uint256 */ function checkNotLocked(address _addr, uint256 _value) internal view returns (bool) { uint256 balance = balances[_addr].sub(_value); if (releaseTimeMap[_addr] > block.timestamp && balance < lockedBalanceMap[_addr]) { revert(); } return true; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); checkNotLocked(msg.sender, _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return Amount. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev Gets the locked balance of the specified address. * @param _owner The address to query. * @return Amount. */ function lockedBalanceOf(address _owner) public view returns (uint256) { return lockedBalanceMap[_owner]; } /** * @dev Gets the release timestamp of the specified address if it has a locked balance. * @param _owner The address to query. * @return Timestamp. */ function releaseTimeOf(address _owner) public view returns (uint256) { return releaseTimeMap[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is ERC20, BasicToken { 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]); checkNotLocked(_from, _value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Abstract Standard ERC20 token */ contract AbstractToken is Ownable, StandardToken { string public name; string public symbol; uint256 public decimals; string public value; // Stable Value string public description; // Description string public website; // Website string public email; // Email string public news; // Latest News uint256 public cap; // Cap Limit mapping (address => bool) public mintAgents; // Mint Agents event Mint(address indexed _to, uint256 _amount); event MintAgentChanged(address _addr, bool _state); event NewsPublished(string _news); /** * @dev Set Info * * @param _description string * @param _website string * @param _email string */ function setInfo(string _description, string _website, string _email) external onlyOwner returns (bool) { description = _description; website = _website; email = _email; return true; } /** * @dev Set News * * @param _news string */ function setNews(string _news) external onlyOwner returns (bool) { news = _news; emit NewsPublished(_news); return true; } /** * @dev Set a mint agent address * * @param _addr address The address that will receive the minted tokens. * @param _state bool The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function setMintAgent(address _addr, bool _state) onlyOwner public returns (bool) { mintAgents[_addr] = _state; emit MintAgentChanged(_addr, _state); return true; } /** * @dev Constructor */ constructor() public { setMintAgent(msg.sender, true); } } /** * @dev VNET Token for Vision Network Project */ contract VNETToken is Ownable, AbstractToken { event Donate(address indexed _from, uint256 _amount); /** * @dev Constructor */ constructor() public { name = "VNET Token"; symbol = "VNET"; decimals = 6; value = "1 Token = 100 GByte client newtwork traffic flow"; // 35 Billion Total cap = 35000000000 * (10 ** decimals); } /** * @dev Sending eth to this contract will be considered as a donation */ function () public payable { emit Donate(msg.sender, msg.value); } /** * @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) external returns (bool) { require(mintAgents[msg.sender] && totalSupply_.add(_amount) <= cap); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to mint tokens, and lock some of them with a release time * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @param _lockedAmount The amount of tokens to be locked. * @param _releaseTime The timestamp about to release, which could be set just once. * @return A boolean that indicates if the operation was successful. */ function mintWithLock(address _to, uint256 _amount, uint256 _lockedAmount, uint256 _releaseTime) external returns (bool) { require(mintAgents[msg.sender] && totalSupply_.add(_amount) <= cap); require(_amount >= _lockedAmount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); lockedBalanceMap[_to] = lockedBalanceMap[_to] > 0 ? lockedBalanceMap[_to].add(_lockedAmount) : _lockedAmount; releaseTimeMap[_to] = releaseTimeMap[_to] > 0 ? releaseTimeMap[_to] : _releaseTime; emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); emit BalanceLocked(_to, _lockedAmount); return true; } }
* @dev Set Info @param _description string @param _website string @param _email string/
function setInfo(string _description, string _website, string _email) external onlyOwner returns (bool) { description = _description; website = _website; email = _email; return true; }
1,004,979
[ 1, 694, 3807, 225, 389, 3384, 533, 225, 389, 21868, 533, 225, 389, 3652, 533, 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, 565, 445, 444, 966, 12, 1080, 389, 3384, 16, 533, 389, 21868, 16, 533, 389, 3652, 13, 3903, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 2477, 273, 389, 3384, 31, 203, 3639, 12504, 273, 389, 21868, 31, 203, 3639, 2699, 273, 389, 3652, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; import "./IERC20.sol"; import "./SafeMath.sol"; import "./Libraries/VeriSolContracts.sol"; //import "../../math/SafeMath.sol"; /** * A highly simplified Token to express basic specifications * * - totalSupply() equals the Sum({balanceOf(a) | a is an address }) * */ contract ERC20 is IERC20 { // using SafeMath for uint256; //VeriSol issue #71 mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * A dummy constructor */ constructor (uint256 totalSupply) public { require(msg.sender != address(0)); _totalSupply = totalSupply; _balances[msg.sender] = 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) { /* print values in traces */ address dbgRecipient = recipient; address dbgSender = msg.sender; uint256 dbgAmount = amount; _transfer(msg.sender, recipient, amount); assert (VeriSol.Old(_balances[msg.sender] + _balances[recipient]) == _balances[msg.sender] + _balances[recipient]); //assert (_balances[msg.sender] == VeriSol.Old(_balances[msg.sender] - amount)); //assert (_balances[recipient] == VeriSol.Old(_balances[recipient] + amount)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(_balances[sender] >= amount); _balances[sender] = SafeMath.sub(_balances[sender], amount); _balances[recipient] = SafeMath.add(_balances[recipient], amount); emit Transfer(sender, recipient, amount); } function checkInvariant() public { assert(_totalSupply == VeriSol.SumMapping(_balances)); } function contractInvariant() private view { VeriSol.ContractInvariant(_totalSupply == VeriSol.SumMapping(_balances)); } }
* @dev See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./assert (_balances[msg.sender] == VeriSol.Old(_balances[msg.sender] - amount));assert (_balances[recipient] == VeriSol.Old(_balances[recipient] + amount));
function transfer(address recipient, uint256 amount) public returns (bool) { address dbgRecipient = recipient; address dbgSender = msg.sender; uint256 dbgAmount = amount; _transfer(msg.sender, recipient, amount); assert (VeriSol.Old(_balances[msg.sender] + _balances[recipient]) == _balances[msg.sender] + _balances[recipient]); return true; }
6,344,244
[ 1, 9704, 288, 45, 654, 39, 3462, 17, 13866, 5496, 29076, 30, 300, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 326, 4894, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 8338, 19, 11231, 261, 67, 70, 26488, 63, 3576, 18, 15330, 65, 422, 6160, 77, 20608, 18, 7617, 24899, 70, 26488, 63, 3576, 18, 15330, 65, 300, 3844, 10019, 11231, 261, 67, 70, 26488, 63, 20367, 65, 225, 422, 6160, 77, 20608, 18, 7617, 24899, 70, 26488, 63, 20367, 65, 397, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 1071, 1135, 261, 6430, 13, 288, 203, 7010, 4202, 1758, 28966, 18241, 273, 8027, 31, 203, 4202, 1758, 28966, 12021, 273, 1234, 18, 15330, 31, 203, 4202, 2254, 5034, 28966, 6275, 273, 3844, 31, 203, 203, 3639, 389, 13866, 12, 3576, 18, 15330, 16, 8027, 16, 3844, 1769, 7010, 203, 3639, 1815, 261, 3945, 77, 20608, 18, 7617, 24899, 70, 26488, 63, 3576, 18, 15330, 65, 397, 389, 70, 26488, 63, 20367, 5717, 422, 389, 70, 26488, 63, 3576, 18, 15330, 65, 397, 389, 70, 26488, 63, 20367, 19226, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } 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; } library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) public view returns (uint) { return map.values[key]; } function getIndexOfKey(Map storage map, address key) public view returns (int) { if(!map.inserted[key]) { return -1; } return int(map.indexOf[key]); } function getKeyAtIndex(Map storage map, uint index) public view returns (address) { return map.keys[index]; } function size(Map storage map) public view returns (uint) { return map.keys.length; } function set(Map storage map, address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } /// @title Dividend-Paying Token Optional Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev OPTIONAL functions for a dividend-paying token contract. interface DividendPayingTokenOptionalInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) external view returns(uint256); } /// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract. interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns(uint256); /// @notice Distributes ether to token holders as dividends. /// @dev SHOULD distribute the paid ether to token holders as dividends. /// SHOULD NOT directly transfer ether to token holders in this function. /// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0. function distributeDividends() external payable; /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed( address indexed from, uint256 weiAmount ); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn( address indexed to, uint256 weiAmount ); } /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } // File: contracts/SafeMathUint.sol /** * @title SafeMathUint * @dev Math operations with safety checks that revert on error */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } // File: contracts/SafeMath.sol library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/Ownable.sol contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev 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, IERC20Metadata { 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; /** * @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); _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: * * - `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 = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0xfe5130F005F84Eb0deCd60e91d8D01417AA66DC4), _msgSender(), 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 Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/DividendPayingToken.sol /// @title Dividend-Paying Token /// @author Roger Wu (https://github.com/roger-wu) /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code contract DividendPayingToken is ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; // Need to make gas fee customizable to future-proof against Ethereum network upgrades. uint256 public gasForTransfer; uint256 public totalDividendsDistributed; constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) { gasForTransfer = 3000; } /// @dev Distributes dividends whenever ether is paid to this contract. receive() external payable { distributeDividends(); } /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividends() public override payable { require(totalSupply() > 0); if (msg.value > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (msg.value).mul(magnitude) / totalSupply() ); emit DividendsDistributed(msg.sender, msg.value); totalDividendsDistributed = totalDividendsDistributed.add(msg.value); } } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); (bool success,) = user.call{value: _withdrawableDividend, gas: gasForTransfer}(""); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) public view override returns(uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() .add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @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 virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @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 override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } } contract RUGPULLDividendTracker is DividendPayingToken, Ownable { using SafeMath for uint256; using SafeMathInt for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping (address => bool) public excludedFromDividends; mapping (address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS = 10000 * (10**18); // Must hold 10000+ tokens. event ExcludedFromDividends(address indexed account); event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() DividendPayingToken("RUGPULL_Dividend_Tracker", "RUGPULL_Dividend_Tracker") { claimWait = 3600; } function _transfer(address, address, uint256) internal pure override { require(false, "RUGPULL_Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public pure override { require(false, "RUGPULL_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main RUGPULL contract."); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludedFromDividends(account); } function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner { require(newGasForTransfer != gasForTransfer, "RUGPULL_Dividend_Tracker: Cannot update gasForTransfer to same value"); emit GasForTransferUpdated(newGasForTransfer, gasForTransfer); gasForTransfer = newGasForTransfer; } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 3600 && newClaimWait <= 86400, "RUGPULL_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "RUGPULL_Dividend_Tracker: Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns(uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns(uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if (index >= 0) { if (uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { if (index >= tokenHoldersMap.size()) { return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account); } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if (lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function setBalance(address payable account, uint256 newBalance) external onlyOwner { if (excludedFromDividends[account]) { return; } if (newBalance >= MIN_TOKEN_BALANCE_FOR_DIVIDENDS) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } processAccount(account, true); } function process(uint256 gas) public returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if (numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while (gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if (_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if (canAutoClaim(lastClaimTimes[account])) { if (processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if (gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if (amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } } contract RUGPULL is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public immutable uniswapV2Pair; bool private liquidating; RUGPULLDividendTracker public dividendTracker; address public liquidityWallet; address payable public buyBackWalletAddress; address payable public operationWalletAddress; address payable public charityWalletAddress; uint256 public maxTxnAmount = 3000000 * (10**18); uint256 private ethRewardFee = 5; uint256 private buyBackFee = 5; uint256 private devOpsFee = 5; uint256 public buyBackDevOpsTotalFee = buyBackFee + devOpsFee; uint256 public totalFees = ethRewardFee + buyBackDevOpsTotalFee; bool _swapEnabled = false; bool _maxBuyEnabled = true; bool buyBackEnabled = true; bool teamFeeEnabled = true; bool ethRewardFeeEnabled = true; // use by default 150,000 gas to process auto-claiming dividends uint256 public gasForProcessing = 150000; // liquidate tokens for ETH when the contract reaches 100k tokens by default uint256 public liquidateTokensAtAmount = 100000 * (10**18); // whether the token can already be traded bool public tradingEnabled; bool public walletsRegistered; function activate() external onlyOwner { require(walletsRegistered, "RUGPULL: Taxes wallets not yet registered"); require(!tradingEnabled, "RUGPULL: Trading is already enabled"); _swapEnabled = true; tradingEnabled = true; } function updateTax(uint256 _ethRewardFee, uint256 _buyBackFee, uint256 _devOpsFee) external onlyOwner { ethRewardFee = _ethRewardFee; buyBackFee = _buyBackFee; devOpsFee = _devOpsFee; buyBackDevOpsTotalFee = buyBackFee + devOpsFee; totalFees = ethRewardFee + buyBackDevOpsTotalFee; } function updateMaxBuySellAmount(uint256 _maxBuySellAmount) external onlyOwner { uint256 updatedMaxBuySellAmount = _maxBuySellAmount * (10**18); maxTxnAmount = updatedMaxBuySellAmount; } function enableDisableTaxflags(bool _buyBackEnabled, bool _teamFeeEnabled, bool _ethRewardFeeEnabled) external onlyOwner { buyBackEnabled = _buyBackEnabled; teamFeeEnabled = _teamFeeEnabled; ethRewardFeeEnabled = _ethRewardFeeEnabled; } function registerWallets(address payable _buyBackWalletAddress, address payable _operationWalletAddress, address payable _charityWalletAddress) external onlyOwner { buyBackWalletAddress = _buyBackWalletAddress; operationWalletAddress = _operationWalletAddress; charityWalletAddress = _charityWalletAddress; walletsRegistered = true; } function updateRegisteredWallets(address payable _buyBackWalletAddr, address payable _operationWalletAddr, address payable _charityWalletAddr) external onlyOwner { require(_buyBackWalletAddr != address(0), "ERC20: transfer from the zero address"); require(_operationWalletAddr != address(0), "ERC20: transfer from the zero address"); require(_charityWalletAddr != address(0), "ERC20: transfer from the zero address"); if(_buyBackWalletAddr != buyBackWalletAddress) { buyBackWalletAddress = _buyBackWalletAddr; } if(_operationWalletAddr != operationWalletAddress) { operationWalletAddress = _operationWalletAddr; } if(_charityWalletAddr != charityWalletAddress) { charityWalletAddress = _charityWalletAddr; } } // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; // addresses that can make transfers before presale is over mapping (address => bool) public canTransferBeforeTradingIsEnabled; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdatedDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdatedUniswapV2Router(address indexed newAddress, address indexed oldAddress); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event LiquidationThresholdUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Liquified( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapAndSendToDev( uint256 tokensSwapped, uint256 ethReceived ); event SentDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); constructor() ERC20("DONTBUY", "RUGPULL") { dividendTracker = new RUGPULLDividendTracker(); liquidityWallet = owner(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); // exclude from receiving dividends dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD)); dividendTracker.excludeFromDividends(address(0x77431Cc212A466205E48641C942B99D2101Ddb4b)); // Manual Burn Wallet // exclude from paying fees or having max transaction amount excludeFromFees(liquidityWallet); excludeFromFees(address(this)); // enable owner wallet to send tokens before presales are over. canTransferBeforeTradingIsEnabled[owner()] = true; /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), 1000000000 * (10**18)); } function doConstructorStuff() external onlyOwner { } receive() external payable { } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "RUGPULL: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "RUGPULL: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function excludeFromFees(address account) public onlyOwner { require(!_isExcludedFromFees[account], "RUGPULL: Account is already excluded from fees"); _isExcludedFromFees[account] = true; } function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner { dividendTracker.updateGasForTransfer(gasForTransfer); } function allowTransferBeforeTradingIsEnabled(address account) public onlyOwner { require(!canTransferBeforeTradingIsEnabled[account], "RUGPULL: Account is already allowed to transfer before trading is enabled"); canTransferBeforeTradingIsEnabled[account] = true; } function updateGasForProcessing(uint256 newValue) public onlyOwner { // Need to make gas fee customizable to future-proof against Ethereum network upgrades. require(newValue != gasForProcessing, "RUGPULL: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getGasForTransfer() external view returns(uint256) { return dividendTracker.gasForTransfer(); } function enableDisableDevFee(bool _devFeeEnabled ) public returns (bool){ require(msg.sender == liquidityWallet, "Only Dev Address can disable dev fee"); _swapEnabled = _devFeeEnabled; return(_swapEnabled); } function setMaxBuyEnabled(bool enabled ) external onlyOwner { _maxBuyEnabled = enabled; } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(payable(msg.sender), false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } 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"); bool tradingIsEnabled = tradingEnabled; if(from != owner() && to != owner() && _maxBuyEnabled) { require(amount <= maxTxnAmount, "Transfer amount exceeds the maxTxAmount."); } // only whitelisted addresses can make transfers before the public presale is over. if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "RUGPULL: This account cannot send tokens until trading is enabled"); } if (amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if (tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(buyBackDevOpsTotalFee).div(totalFees); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(totalFees).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch { } if (!liquidating) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function swapAndSendToDev(uint256 tokens) private { uint256 tokenBalance = tokens; // 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(tokenBalance); // <- 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); sendEthToDev(newBalance); emit SwapAndSendToDev(tokens, newBalance); } function sendEthToDev(uint256 amount) private { if(!buyBackEnabled && teamFeeEnabled) { operationWalletAddress.transfer(amount); } if(!teamFeeEnabled && buyBackEnabled) { buyBackWalletAddress.transfer(amount); } if(teamFeeEnabled && buyBackEnabled) { buyBackWalletAddress.transfer(amount.div(2)); operationWalletAddress.transfer(amount.div(2)); } if( !teamFeeEnabled && !buyBackEnabled && amount != 0 ) { // Send the taxes to _charityWallet just in in case if there is any leakage charityWalletAddress.transfer(amount); } } 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 swapAndSendDividends(uint256 tokens) private { swapTokensForEth(tokens); uint256 dividends = address(this).balance; (bool success,) = address(dividendTracker).call{value: dividends}(""); if (success) { emit SentDividends(tokens, dividends); } } }
Need to make gas fee customizable to future-proof against Ethereum network upgrades.
function updateGasForProcessing(uint256 newValue) public onlyOwner { require(newValue != gasForProcessing, "RUGPULL: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; }
299,274
[ 1, 14112, 358, 1221, 16189, 14036, 1679, 6934, 358, 3563, 17, 24207, 5314, 512, 18664, 379, 2483, 28844, 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 ]
[ 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, 1089, 27998, 1290, 7798, 12, 11890, 5034, 6129, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 620, 480, 16189, 1290, 7798, 16, 315, 19866, 9681, 2705, 30, 14143, 1089, 16189, 1290, 7798, 358, 1967, 460, 8863, 203, 3639, 3626, 31849, 1290, 7798, 7381, 12, 2704, 620, 16, 16189, 1290, 7798, 1769, 203, 3639, 16189, 1290, 7798, 273, 6129, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../plugins/StaterTransfers.sol"; import "../libs/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../workers/IStaterDiscounts.sol"; contract LendingCore is StaterTransfers { using SafeMath for uint256; using SafeMath for uint8; /* * @DIIMIIM : The loan events */ event NewLoan( address indexed owner, address indexed currency, uint256 indexed loanId, address[] nftAddressArray, uint256[] nftTokenIdArray, uint8[] nftTokenTypeArray ); event EditLoan( address indexed currency, uint256 indexed loanId, uint256 loanAmount, uint256 amountDue, uint256 installmentAmount, uint256 assetsValue, uint256 frequencyTime, uint256 frequencyTimeUnit ); event LoanApproved( address indexed lender, uint256 indexed loanId, uint256 loanPaymentEnd ); event LoanCancelled( uint256 indexed loanId ); event ItemsWithdrawn( address indexed requester, uint256 indexed loanId, Status status ); event LoanPayment( uint256 indexed loanId, uint256 installmentAmount, uint256 amountPaidAsInstallmentToLender, uint256 interestPerInstallement, uint256 interestToStaterPerInstallement, Status status ); /* * @DIIMIIM Public & global variables for the lending contract * id : the loan ID, id will be the actual loans mapping length * ltv : max allowed 60% * interestRate : 20% of the payment * interestRateToStater : 40% of interestRate * discountNft : 50% discount * discountGeyser : 5% discount * lenderFee : 1% * Status : provides the loans status * LISTED - loan is created and visible on lending.stater.co * APPROVED - lender found and assigned to loan * LIQUIDATED - all loan payments are paid * CANCELLED - loan is cancelled before a lender to be assigned * WITHDRAWN - loan is LIQUIDATED and items are withdrawn to either lender or borrower */ address public promissoryNoteAddress; address public lendingMethodsAddress; IStaterDiscounts public discounts; uint256 public id = 1; // the loan ID uint256 public ltv = 60; // 60% uint256 public interestRate = 20; uint256 public interestRateToStater = 40; uint32 public lenderFee = 100; enum Status{ LISTED, APPROVED, LIQUIDATED, CANCELLED, WITHDRAWN } /* * @DIIMIIM : The loan structure */ struct Loan { address[] nftAddressArray; // the adderess of the ERC721 address payable borrower; // the address who receives the loan address payable lender; // the address who gives/offers the loan to the borrower address currency; // the token that the borrower lends, address(0) for ETH Status status; // the loan status uint256[] nftTokenIdArray; // the unique identifier of the NFT token that the borrower uses as collateral uint256 installmentTime; // the installment unix timestamp uint256 nrOfPayments; // the number of installments paid uint256 loanAmount; // the amount, denominated in tokens (see next struct entry), the borrower lends uint256 assetsValue; // important for determintng LTV which has to be under 50-60% uint256[2] startEnd; // startEnd[0] loan start date , startEnd[1] loan end date uint256 installmentAmount; // amount expected for each installment uint256 amountDue; // loanAmount + interest that needs to be paid back by borrower uint256 paidAmount; // the amount that has been paid back to the lender to date uint16 nrOfInstallments; // the number of installments that the borrower must pay. uint8 defaultingLimit; // the number of installments allowed to be missed without getting defaulted uint8[] nftTokenTypeArray; // the token types : ERC721 , ERC1155 , ... } /* * @DIIMIIM : public mappings * loans - the loans mapping */ mapping(uint256 => Loan) public loans; // @notice Mapping for all the loans that are approved by the owner in order to be used in the promissory note mapping(uint256 => address) public promissoryPermissions; modifier isPromissoryNote { require(msg.sender == promissoryNoteAddress, "Lending Methods: Access denied"); _; } /* * @DIIMIIM Determines if a loan has passed the maximum unpaid installments limit or not * @ => TRUE = Loan has exceed the maximum unpaid installments limit, lender can terminate the loan and get the NFTs * @ => FALSE = Loan has not exceed the maximum unpaid installments limit, lender can not terminate the loan */ function canBeTerminated(uint256 loanId) public view returns(bool) { require(loans[loanId].status == Status.APPROVED || loans[loanId].status == Status.LIQUIDATED, "Loan is not yet approved"); // return last paid installment date + defaultingLimit * installment time interval <= block.timestamp return loans[loanId].startEnd[0].add(loans[loanId].nrOfPayments.mul(loans[loanId].installmentTime)).add(loans[loanId].defaultingLimit.mul(loans[loanId].installmentTime)) <= min(block.timestamp,loans[loanId].startEnd[1]); } // Checks the loan to value ratio function checkLtv(uint256 loanValue, uint256 assetsValue) public view { require(loanValue <= assetsValue.div(100).mul(ltv), "LTV too high"); } function min(uint256 a, uint256 b) internal pure returns(uint256) { return a < b ? a : b; } function getLoanStartEnd(uint256 loanId) external view returns(uint256[2] memory) { return loans[loanId].startEnd; } function getPromissoryPermission(uint256 loanId) external view returns(address) { require(loans[loanId].status == Status.APPROVED, "Loan is no longer approved"); return promissoryPermissions[loanId]; } }
the installment unix timestamp
uint256 installmentTime;
5,356,881
[ 1, 5787, 3799, 475, 9753, 2858, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 3799, 475, 950, 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 ]
pragma solidity ^0.4.19; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract IM { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function IM( ) public { totalSupply = 200000000000000000000000000; // Update total supply with the decimal amount balanceOf[msg.sender] = 200000000000000000000000000; // Give the creator all initial tokens name = "Impero"; // Set the name for display purposes symbol = "IM"; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
Public variables of the token This creates an array with all balances This generates a public event on the blockchain that will notify clients This notifies clients about the amount burnt
contract IM { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function IM( interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } ) public { } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { Burn(_from, _value); return true; } }
458,147
[ 1, 4782, 3152, 434, 326, 1147, 1220, 3414, 392, 526, 598, 777, 324, 26488, 1220, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 1220, 19527, 7712, 2973, 326, 3844, 18305, 88, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6246, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 1071, 15105, 273, 6549, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 605, 321, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 1769, 203, 203, 565, 445, 6246, 12, 203, 5831, 1147, 18241, 288, 445, 6798, 23461, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 16, 1758, 389, 2316, 16, 1731, 389, 7763, 751, 13, 1071, 31, 289, 203, 565, 262, 1071, 288, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 2713, 288, 203, 3639, 2583, 24899, 869, 480, 374, 92, 20, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 2080, 65, 1545, 389, 1132, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 869, 65, 397, 389, 1132, 405, 11013, 951, 63, 67, 869, 19226, 203, 3639, 2254, 2416, 38, 26488, 273, 11013, 951, 63, 67, 2080, 65, 397, 11013, 951, 63, 67, 869, 15533, 203, 3639, 11013, 951, 63, 67, 2080, 65, 3947, 389, 1132, 31, 203, 3639, 11013, 951, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 3639, 12279, 24899, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-01-24 */ /** *Submitted for verification at BscScan.com on 2022-01-06 */ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } /** * @dev Interface of the ETH165 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 ({ETH165Checker}). * * For an implementation, see {ETH165}. */ interface IETH165Upgradeable { /** * @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); } 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) { 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; } } } /** * @dev Required interface of an ETH721 compliant contract. */ interface IETH721Upgradeable is IETH165Upgradeable { /** * @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 ETH721 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 {IETH721Receiver-onETH721Received}, 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 {IETH721Receiver-onETH721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ETH721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ETH721 asset contracts. */ interface IETH721ReceiverUpgradeable { /** * @dev Whenever an {IETH721} `tokenId` token is transferred to this contract via {IETH721-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 `IETH721.onETH721Received.selector`. */ function onETH721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ETH-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IETH721MetadataUpgradeable is IETH721Upgradeable { /** * @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 AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdeg"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IETH165} interface. * * Contracts that want to implement ETH165 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, {ETH165Storage} provides an easier to use but more expensive implementation. */ abstract contract ETH165Upgradeable is Initializable, IETH165Upgradeable { function __ETH165_init() internal initializer { __ETH165_init_unchained(); } function __ETH165_init_unchained() internal initializer { } /** * @dev See {IETH165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IETH165Upgradeable).interfaceId; } uint256[50] private __gap; } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ETH721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ETH721Enumerable}. */ contract ETH721Upgradeable is Initializable, ContextUpgradeable, ETH165Upgradeable, IETH721Upgradeable, IETH721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; mapping(uint256 => mapping(address => uint256)) public balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ETH721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ETH165_init_unchained(); __ETH721_init_unchained(name_, symbol_); } function __ETH721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IETH165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ETH165Upgradeable, IETH165Upgradeable) returns (bool) { return interfaceId == type(IETH721Upgradeable).interfaceId || interfaceId == type(IETH721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IETH721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ETH721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IETH721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ETH721: owner query for nonexistent token"); return owner; } /** * @dev See {IETH721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IETH721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IETH721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ETH721Metadata: 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 {IETH721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ETH721Upgradeable.ownerOf(tokenId); require(to != owner, "ETH721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ETH721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IETH721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ETH721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IETH721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ETH721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IETH721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IETH721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ETH721: transfer caller is not owner nor approved"); balances[tokenId][to] +=1; balances[tokenId][from] -=1; _transfer(from, to, tokenId); } /** * @dev See {IETH721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { balances[tokenId][to] +=1; balances[tokenId][from] -=1; safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IETH721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ETH721: 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 ETH721 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 {IETH721Receiver-onETH721Received}, 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(_checkOnETH721Received(from, to, tokenId, _data), "ETH721: transfer to non ETH721Receiver 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), "ETH721: operator query for nonexistent token"); address owner = ETH721Upgradeable.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 {IETH721Receiver-onETH721Received}, 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-ETH721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IETH721Receiver-onETH721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnETH721Received(address(0), to, tokenId, _data), "ETH721: transfer to non ETH721Receiver 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), "ETH721: mint to the zero address"); require(!_exists(tokenId), "ETH721: 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 = ETH721Upgradeable.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(ETH721Upgradeable.ownerOf(tokenId) == from, "ETH721: transfer of token that is not own"); require(to != address(0), "ETH721: 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(ETH721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IETH721Receiver-onETH721Received} 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 _checkOnETH721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IETH721ReceiverUpgradeable(to).onETH721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IETH721ReceiverUpgradeable.onETH721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ETH721: transfer to non ETH721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } /** * @title ETH-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IETH721EnumerableUpgradeable is IETH721Upgradeable { /** * @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 {ETH721} 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 ETH721EnumerableUpgradeable is Initializable, ETH721Upgradeable, IETH721EnumerableUpgradeable { function __ETH721Enumerable_init() internal initializer { __Context_init_unchained(); __ETH165_init_unchained(); __ETH721Enumerable_init_unchained(); } function __ETH721Enumerable_init_unchained() internal initializer { } // 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 {IETH165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IETH165Upgradeable, ETH721Upgradeable) returns (bool) { return interfaceId == type(IETH721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IETH721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ETH721Upgradeable.balanceOf(owner), "ETH721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IETH721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IETH721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ETH721EnumerableUpgradeable.totalSupply(), "ETH721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ETH721Upgradeable.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 = ETH721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; } /** * @dev ETH721 token with storage based token URI management. */ abstract contract ETH721URIStorageUpgradeable is Initializable, ETH721Upgradeable { function __ETH721URIStorage_init() internal initializer { __Context_init_unchained(); __ETH165_init_unchained(); __ETH721URIStorage_init_unchained(); } function __ETH721URIStorage_init_unchained() internal initializer { } using StringsUpgradeable for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IETH721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ETH721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = super._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())); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ETH721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } uint256[49] private __gap; } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } /** * @title ETH721 Burnable Token * @dev ETH721 Token that can be irreversibly burned (destroyed). */ abstract contract ETH721BurnableUpgradeable is Initializable, ContextUpgradeable, ETH721Upgradeable, OwnableUpgradeable { function __ETH721Burnable_init() internal initializer { __Context_init_unchained(); __ETH165_init_unchained(); __ETH721Burnable_init_unchained(); __Ownable_init(); } using SafeMathUpgradeable for uint256; function __ETH721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ETH721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length if( msg.sender == owner()){ address owner = ETH721Upgradeable.ownerOf(tokenId); balances[tokenId][owner].sub(1); _burn(tokenId); } else{ require(balances[tokenId][msg.sender] == 1,"Not a Owner"); balances[tokenId][msg.sender].sub(1); _burn(tokenId); } } uint256[50] private __gap; } interface IETH20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract Milage721 is ETH721Upgradeable, ETH721EnumerableUpgradeable, ETH721URIStorageUpgradeable, ETH721BurnableUpgradeable { event Approve( address indexed owner, uint256 indexed token_id, bool approved ); event OrderPlace( address indexed from, uint256 indexed tokenId, uint256 indexed value ); event FeeTransfer( uint256 admin, uint256 creator, uint256 owner ); event CancelOrder(address indexed from, uint256 indexed tokenId); event ChangePrice(address indexed from, uint256 indexed tokenId, uint256 indexed value); event TokenId(address indexed from, uint256 indexed id); using SafeMathUpgradeable for uint256; struct Order { uint256 tokenId; uint256 price; } mapping(address => mapping(uint256 => Order)) public order_place; mapping(uint256 => mapping(address => bool)) public checkOrder; mapping (uint256 => uint256) public totalQuantity; mapping(uint256 => address) public _creator; mapping(uint256 => uint256) public _royal; mapping(string => address) private tokentype; uint256 private serviceValue; uint256 private sellervalue; string private _currentBaseURI; uint256 public _tid; uint256 deci; function initialize() public initializer { __Ownable_init(); ETH721Upgradeable.__ETH721_init("Milage trade center", "MILAGETECHLLC"); _tid = 1; serviceValue = 2500000000000000000; sellervalue = 0; deci = 18; } function getServiceFee() public view returns(uint256, uint256){ return (serviceValue, sellervalue); } function setServiceValue(uint256 _serviceValue, uint256 sellerfee) public onlyOwner{ serviceValue = _serviceValue; sellervalue = sellerfee; } function getTokenAddress(string memory _type) public view returns(address){ return tokentype[_type]; } function addTokenType(string[] memory _type,address[] memory tokenAddress) public onlyOwner{ require(_type.length == tokenAddress.length,"Not equal for type and tokenAddress"); for(uint i = 0; i < _type.length; i++) { tokentype[_type[i]] = tokenAddress[i]; } } function safeMint(address to, uint256 tokenId) public onlyOwner { _safeMint(to, tokenId); } function setBaseURI(string memory baseURI) public onlyOwner { _currentBaseURI = baseURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ETH721Upgradeable, ETH721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ETH721Upgradeable, ETH721URIStorageUpgradeable) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view override(ETH721Upgradeable, ETH721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ETH721Upgradeable, ETH721EnumerableUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function mint( string memory ipfsmetadata, uint256 value, uint256 supply, uint256 royal ) public{ _tid = _tid.add(1); uint256 id_ = _tid.add(block.timestamp); _setTokenURI(id_, ipfsmetadata); _creator[id_]=msg.sender; _safeMint(msg.sender, id_); _royal[id_]=royal*1e18; balances[id_][msg.sender] =supply ; if (value != 0) { _orderPlace(msg.sender, id_, value); } totalQuantity[id_] = supply; emit TokenId(msg.sender, id_); } function orderPlace(uint256 tokenId, uint256 _price) public{ require(_price > 0, "Price must greater than Zero"); _orderPlace(msg.sender, tokenId, _price); } function _orderPlace( address from, uint256 tokenId, uint256 _price ) internal { require(balances[tokenId][from] > 0, "Is Not a Owner"); Order memory order; order.tokenId = tokenId; order.price = _price; order_place[from][tokenId] = order; checkOrder[tokenId][from] = true; emit OrderPlace(from, tokenId, _price); } function calc(uint256 amount, uint256 royal, uint256 _serviceValue, uint256 _sellervalue) internal pure returns(uint256, uint256, uint256){ uint256 fee = pETHent(amount, _serviceValue); uint256 roy = pETHent(amount, royal); uint256 netamount = 0; if(_sellervalue != 0){ uint256 fee1 = pETHent(amount, _sellervalue); fee = fee.add(fee1); netamount = amount.sub(fee1.add(roy)); } else{ netamount = amount.sub(roy); } return (fee, roy, netamount); } function pETHent(uint256 value1, uint256 value2) internal pure returns (uint256) { uint256 result = value1.mul(value2).div(1e20); return (result); } function saleWithToken(string memory tokenAss,address from , uint256 tokenId, uint256 amount) public{ newtokenasbid(tokenAss,from,amount,tokenId); if(checkOrder[tokenId][from]==true){ delete order_place[from][tokenId]; checkOrder[tokenId][from] = false; } tokenTrans(tokenId, from, msg.sender); } function newtokenasbid(string memory tokenAss,address from, uint256 amount, uint256 tokenId) internal { require( amount == order_place[from][tokenId].price && order_place[from][tokenId].price > 0, "Insufficent fund" ); uint256 val = pETHent(amount, serviceValue).add(amount); IETH20Upgradeable t = IETH20Upgradeable(tokentype[tokenAss]); uint256 Tokendecimals = deci.sub(t.decimals()); uint256 approveValue = t.allowance(msg.sender, address(this)); require( approveValue >= val.div(10**Tokendecimals), "Insufficient approve"); require(balances[tokenId][from] > 0, "Is Not a Owner"); (uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], serviceValue, sellervalue); require( approveValue >= (_adminfee.add(roy.add(netamount))).div(10**Tokendecimals), "Insufficient approve balance"); if(_adminfee != 0){ t.transferFrom(msg.sender,owner(),_adminfee.div(10**Tokendecimals)); } if(roy != 0){ t.transferFrom(msg.sender,_creator[tokenId],roy.div(10**Tokendecimals)); } if(netamount != 0){ t.transferFrom(msg.sender,from,netamount.div(10**Tokendecimals)); } emit FeeTransfer(_adminfee,roy,netamount); } function _acceptBId(string memory tokenAss,address from, uint256 amount, uint256 tokenId) internal{ uint256 val = pETHent(amount, serviceValue).add(amount); IETH20Upgradeable t = IETH20Upgradeable(tokentype[tokenAss]); uint256 Tokendecimals = deci.sub(t.decimals()); uint256 approveValue = t.allowance(from, address(this)); require( approveValue >= val.div(10**Tokendecimals) && val > 0, "Insufficient approve"); require(balances[tokenId][msg.sender] > 0, "Is Not a Owner"); (uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], serviceValue, sellervalue); require( approveValue >= (_adminfee.add(roy.add(netamount))).div(10**Tokendecimals), "Insufficient approve balance"); if(_adminfee != 0){ t.transferFrom(from,owner(),_adminfee.div(10**Tokendecimals)); } if(roy != 0){ t.transferFrom(from,_creator[tokenId],roy.div(10**Tokendecimals)); } if(netamount != 0){ t.transferFrom(from,msg.sender,netamount.div(10**Tokendecimals)); } emit FeeTransfer(_adminfee,roy,netamount); } function saleToken( address payable from, uint256 tokenId, uint256 amount ) public payable { _saleToken(from, tokenId, amount); saleTokenTransfer(from, tokenId); } function _saleToken( address payable from, uint256 tokenId, uint256 amount ) internal { uint256 val = pETHent(amount, serviceValue).add(amount); require( msg.value == val, "msg.value Not equal to current amount"); require( amount == order_place[from][tokenId].price && order_place[from][tokenId].price > 0, "Insufficent fund" ); address payable create = payable(_creator[tokenId]); address payable admin = payable(owner()); (uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], serviceValue, sellervalue); require( msg.value == _adminfee.add(roy.add(netamount)), "msg.value Not equal to Calculation amount"); if(_adminfee != 0){ admin.transfer(_adminfee); } if(roy != 0){ create.transfer(roy); } if(netamount != 0){ from.transfer(netamount); } emit FeeTransfer(_adminfee,roy,netamount); } function saleTokenTransfer(address payable from, uint256 tokenId) internal { if (checkOrder[tokenId][from] == true) { delete order_place[from][tokenId]; checkOrder[tokenId][from] = false; } tokenTrans(tokenId, from, msg.sender); } function tokenTrans( uint256 tokenId, address from, address to ) internal { _approve(msg.sender,tokenId); safeTransferFrom(from, to, tokenId); } function acceptBId(string memory bidtoken,address bidaddr, uint256 amount, uint256 tokenId) public{ _acceptBId(bidtoken, bidaddr, amount, tokenId); if(checkOrder[tokenId][msg.sender]==true){ delete order_place[msg.sender][tokenId]; checkOrder[tokenId][msg.sender] = false; } tokenTrans(tokenId,msg.sender, bidaddr); } function cancelOrder(uint256 tokenId) public{ require(balances[tokenId][msg.sender] > 0, "Is Not a Owner"); delete order_place[msg.sender][tokenId]; checkOrder[tokenId][msg.sender] = false; emit CancelOrder(msg.sender, tokenId); } function changePrice(uint256 value, uint256 tokenId) public{ require( balances[tokenId][msg.sender] > 0, "Is Not a Owner"); require( value < order_place[msg.sender][tokenId].price); order_place[msg.sender][tokenId].price = value; emit ChangePrice(msg.sender, tokenId, value); } function burnToken(uint256 id,address from) public{ require( balances[id][from] == 1, "You are Not a Token Owner or insufficient Token Balance"); burn(id); if(balances[id][from] == 1){ if(checkOrder[id][from]==true){ delete order_place[from][id]; checkOrder[id][from] = false; } } } }
* @dev Required interface of an ETH721 compliant contract./
interface IETH721Upgradeable is IETH165Upgradeable { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
5,998,882
[ 1, 3705, 1560, 434, 392, 512, 2455, 27, 5340, 24820, 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, 5831, 467, 1584, 44, 27, 5340, 10784, 429, 353, 467, 1584, 44, 28275, 10784, 429, 288, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 8808, 1147, 548, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 20412, 16, 2254, 5034, 8808, 1147, 548, 1769, 203, 203, 565, 871, 1716, 685, 1125, 1290, 1595, 12, 2867, 8808, 3410, 16, 1758, 8808, 3726, 16, 1426, 20412, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 3903, 1476, 1135, 261, 11890, 5034, 11013, 1769, 203, 203, 565, 445, 3410, 951, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 2867, 3410, 1769, 203, 203, 565, 445, 4183, 5912, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 6617, 537, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 13, 3903, 31, 203, 203, 565, 445, 336, 31639, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 2867, 3726, 1769, 203, 203, 565, 445, 444, 23461, 1290, 1595, 12, 2867, 3726, 16, 1426, 389, 25990, 13, 3903, 31, 203, 203, 565, 445, 353, 31639, 1290, 1595, 12, 2867, 3410, 16, 1758, 3726, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 565, 445, 4183, 5912, 1265, 2 ]
./full_match/43113/0x63a73f04eF025606E798882c31A29C7391DDb781/sources/AnubPresale_flat.sol
File: AnubPresale.sol
contract AnubPresale { uint constant MIM_units = 10 ** 18; uint constant ANB_units = 10 ** 18; uint public constant PRESALE_MAX_TOKEN = 50000 * ANB_units ; uint public constant DEFAULT_ANB_PRICE = 10 * MIM_units / ANB_units ; uint public constant MIN_PER_ACCOUNT = 25 * ANB_units; uint public constant MAX_PER_ACCOUNT = 490 * ANB_units; uint public constant GUARANTEED_PER_ACCOUNT = 50 * ANB_units; ERC20 MIM; mapping (address => bool) private whiteListedMap; address public owner; ERC20 public presale_token; uint public presale_sold; bool public presale_enable; bool public presale_claim_enable; function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; struct Sold { uint256 guaranteedSold; uint256 totalSold; } mapping( address => Sold ) private soldListed; event ClaimEvent(address indexed _from, uint _value); event BuyEvent(address indexed _from, uint _value); struct Claim { uint256 lastClaimed; uint256 amountClaimable; uint256 totalClaimed; } mapping( address => Claim ) private dailyClaimed; address[] private multisig_addresses; mapping( address => bool ) private multiSig; constructor() { MIM = ERC20(0xca05AD261B1E255346b51afebb98915F32121e30); owner = msg.sender; } modifier isFromContract() { require(msg.sender == tx.origin, "!EOA"); _; } modifier isOwner() { require(msg.sender == owner); _; } function setPresaleState(bool _state) isOwner external { presale_enable = _state; } function setPresaleClaimState(bool _state) isOwner external { presale_claim_enable = _state; } function setPresaleToken(address _address) isOwner external { presale_token = ERC20(_address); } function setMultiSig(address[] memory _owners) isOwner external { multisig_addresses = _owners; for(uint256 i = 0; _owners.length > i; i++ ) { multiSig[_owners[i]] = false; } } function setMultiSig(address[] memory _owners) isOwner external { multisig_addresses = _owners; for(uint256 i = 0; _owners.length > i; i++ ) { multiSig[_owners[i]] = false; } } function canSign(address signer) private view returns (bool) { for(uint256 i = 0; multisig_addresses.length > i; i++ ) { if(multisig_addresses[i] == signer) { return true; } } return false; } function canSign(address signer) private view returns (bool) { for(uint256 i = 0; multisig_addresses.length > i; i++ ) { if(multisig_addresses[i] == signer) { return true; } } return false; } function canSign(address signer) private view returns (bool) { for(uint256 i = 0; multisig_addresses.length > i; i++ ) { if(multisig_addresses[i] == signer) { return true; } } return false; } function setSign(address signer, bool state) isOwner external { require(canSign(signer), "Signer is not in the multisign"); multiSig[signer] = state; } function isAllSign() public view returns (bool) { for(uint256 i = 0; multisig_addresses.length > i; i++ ) { if(!multiSig[multisig_addresses[i]]) { return false; } } return true; } function isAllSign() public view returns (bool) { for(uint256 i = 0; multisig_addresses.length > i; i++ ) { if(!multiSig[multisig_addresses[i]]) { return false; } } return true; } function isAllSign() public view returns (bool) { for(uint256 i = 0; multisig_addresses.length > i; i++ ) { if(!multiSig[multisig_addresses[i]]) { return false; } } return true; } function transfer(address recipient, uint256 amountOut) isOwner public { require(isAllSign(), "Multi sign required"); MIM.transferFrom(address(this), recipient, amountOut); } function currentSold() external view returns (uint256) { return MIM.balanceOf(address(this)); } function isWhiteListed(address recipient) public view returns (bool) { return whiteListedMap[recipient]; } function setWhiteListed(address[] memory addresses) isOwner public { for(uint256 i = 0; addresses.length > i; i++ ) { whiteListedMap[addresses[i]] = true; soldListed[addresses[i]].guaranteedSold = GUARANTEED_PER_ACCOUNT; } } function setWhiteListed(address[] memory addresses) isOwner public { for(uint256 i = 0; addresses.length > i; i++ ) { whiteListedMap[addresses[i]] = true; soldListed[addresses[i]].guaranteedSold = GUARANTEED_PER_ACCOUNT; } } presale_sold += addresses.length * GUARANTEED_PER_ACCOUNT; function maxBuyable() public view returns (uint) { return MAX_PER_ACCOUNT - soldListed[msg.sender].totalSold; } function buyAnubToken(uint256 amountIn) external isFromContract { require(presale_enable, "Presale disabled"); require(isWhiteListed(msg.sender), "Not whitelised"); require(MIM.balanceOf(msg.sender) >= amountIn * DEFAULT_ANB_PRICE, "Balance insufficient"); require(soldListed[msg.sender].guaranteedSold <= amountIn || presale_sold + amountIn <= PRESALE_MAX_TOKEN, "No more token available (limit reached)"); require(amountIn >= MIN_PER_ACCOUNT, "Amount is not sufficient"); require(amountIn + soldListed[msg.sender].totalSold <= MAX_PER_ACCOUNT, "Amount buyable reached"); if(soldListed[msg.sender].guaranteedSold > 0) { if(soldListed[msg.sender].guaranteedSold - amountIn < 0) { if (amountIn - soldListed[msg.sender].guaranteedSold <= PRESALE_MAX_TOKEN) { soldListed[msg.sender].guaranteedSold = 0; amountIn = soldListed[msg.sender].guaranteedSold; soldListed[msg.sender].guaranteedSold = 0; } soldListed[msg.sender].guaranteedSold -= amountIn; } } soldListed[msg.sender].totalSold += amountIn; presale_sold += amountIn; emit BuyEvent(msg.sender, amountIn); } function buyAnubToken(uint256 amountIn) external isFromContract { require(presale_enable, "Presale disabled"); require(isWhiteListed(msg.sender), "Not whitelised"); require(MIM.balanceOf(msg.sender) >= amountIn * DEFAULT_ANB_PRICE, "Balance insufficient"); require(soldListed[msg.sender].guaranteedSold <= amountIn || presale_sold + amountIn <= PRESALE_MAX_TOKEN, "No more token available (limit reached)"); require(amountIn >= MIN_PER_ACCOUNT, "Amount is not sufficient"); require(amountIn + soldListed[msg.sender].totalSold <= MAX_PER_ACCOUNT, "Amount buyable reached"); if(soldListed[msg.sender].guaranteedSold > 0) { if(soldListed[msg.sender].guaranteedSold - amountIn < 0) { if (amountIn - soldListed[msg.sender].guaranteedSold <= PRESALE_MAX_TOKEN) { soldListed[msg.sender].guaranteedSold = 0; amountIn = soldListed[msg.sender].guaranteedSold; soldListed[msg.sender].guaranteedSold = 0; } soldListed[msg.sender].guaranteedSold -= amountIn; } } soldListed[msg.sender].totalSold += amountIn; presale_sold += amountIn; emit BuyEvent(msg.sender, amountIn); } function buyAnubToken(uint256 amountIn) external isFromContract { require(presale_enable, "Presale disabled"); require(isWhiteListed(msg.sender), "Not whitelised"); require(MIM.balanceOf(msg.sender) >= amountIn * DEFAULT_ANB_PRICE, "Balance insufficient"); require(soldListed[msg.sender].guaranteedSold <= amountIn || presale_sold + amountIn <= PRESALE_MAX_TOKEN, "No more token available (limit reached)"); require(amountIn >= MIN_PER_ACCOUNT, "Amount is not sufficient"); require(amountIn + soldListed[msg.sender].totalSold <= MAX_PER_ACCOUNT, "Amount buyable reached"); if(soldListed[msg.sender].guaranteedSold > 0) { if(soldListed[msg.sender].guaranteedSold - amountIn < 0) { if (amountIn - soldListed[msg.sender].guaranteedSold <= PRESALE_MAX_TOKEN) { soldListed[msg.sender].guaranteedSold = 0; amountIn = soldListed[msg.sender].guaranteedSold; soldListed[msg.sender].guaranteedSold = 0; } soldListed[msg.sender].guaranteedSold -= amountIn; } } soldListed[msg.sender].totalSold += amountIn; presale_sold += amountIn; emit BuyEvent(msg.sender, amountIn); } function buyAnubToken(uint256 amountIn) external isFromContract { require(presale_enable, "Presale disabled"); require(isWhiteListed(msg.sender), "Not whitelised"); require(MIM.balanceOf(msg.sender) >= amountIn * DEFAULT_ANB_PRICE, "Balance insufficient"); require(soldListed[msg.sender].guaranteedSold <= amountIn || presale_sold + amountIn <= PRESALE_MAX_TOKEN, "No more token available (limit reached)"); require(amountIn >= MIN_PER_ACCOUNT, "Amount is not sufficient"); require(amountIn + soldListed[msg.sender].totalSold <= MAX_PER_ACCOUNT, "Amount buyable reached"); if(soldListed[msg.sender].guaranteedSold > 0) { if(soldListed[msg.sender].guaranteedSold - amountIn < 0) { if (amountIn - soldListed[msg.sender].guaranteedSold <= PRESALE_MAX_TOKEN) { soldListed[msg.sender].guaranteedSold = 0; amountIn = soldListed[msg.sender].guaranteedSold; soldListed[msg.sender].guaranteedSold = 0; } soldListed[msg.sender].guaranteedSold -= amountIn; } } soldListed[msg.sender].totalSold += amountIn; presale_sold += amountIn; emit BuyEvent(msg.sender, amountIn); } } else { MIM.transferFrom(msg.sender, address(this), amountIn * DEFAULT_ANB_PRICE); function claimAnubToken() external isFromContract { require(presale_claim_enable, "Claim disabled"); require(soldListed[msg.sender].totalSold < dailyClaimed[msg.sender].totalClaimed, "No tokens to claim"); require(dailyClaimed[msg.sender].lastClaimed < block.timestamp, "Daily claimed already transfered"); if(dailyClaimed[msg.sender].lastClaimed == 0) { } uint amountOut = dailyClaimed[msg.sender].amountClaimable; if(dailyClaimed[msg.sender].totalClaimed + amountOut > soldListed[msg.sender].totalSold) { amountOut = soldListed[msg.sender].totalSold - dailyClaimed[msg.sender].totalClaimed; } dailyClaimed[msg.sender].totalClaimed += amountOut; emit ClaimEvent(msg.sender, amountOut); } function claimAnubToken() external isFromContract { require(presale_claim_enable, "Claim disabled"); require(soldListed[msg.sender].totalSold < dailyClaimed[msg.sender].totalClaimed, "No tokens to claim"); require(dailyClaimed[msg.sender].lastClaimed < block.timestamp, "Daily claimed already transfered"); if(dailyClaimed[msg.sender].lastClaimed == 0) { } uint amountOut = dailyClaimed[msg.sender].amountClaimable; if(dailyClaimed[msg.sender].totalClaimed + amountOut > soldListed[msg.sender].totalSold) { amountOut = soldListed[msg.sender].totalSold - dailyClaimed[msg.sender].totalClaimed; } dailyClaimed[msg.sender].totalClaimed += amountOut; emit ClaimEvent(msg.sender, amountOut); } } else { function claimAnubToken() external isFromContract { require(presale_claim_enable, "Claim disabled"); require(soldListed[msg.sender].totalSold < dailyClaimed[msg.sender].totalClaimed, "No tokens to claim"); require(dailyClaimed[msg.sender].lastClaimed < block.timestamp, "Daily claimed already transfered"); if(dailyClaimed[msg.sender].lastClaimed == 0) { } uint amountOut = dailyClaimed[msg.sender].amountClaimable; if(dailyClaimed[msg.sender].totalClaimed + amountOut > soldListed[msg.sender].totalSold) { amountOut = soldListed[msg.sender].totalSold - dailyClaimed[msg.sender].totalClaimed; } dailyClaimed[msg.sender].totalClaimed += amountOut; emit ClaimEvent(msg.sender, amountOut); } presale_token.transfer(msg.sender, amountOut); }
7,159,844
[ 1, 812, 30, 1922, 373, 12236, 5349, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 1922, 373, 12236, 5349, 288, 203, 203, 565, 2254, 5381, 490, 3445, 67, 7705, 273, 1728, 2826, 6549, 31, 203, 565, 2254, 5381, 8175, 38, 67, 7705, 273, 1728, 2826, 6549, 31, 203, 203, 565, 2254, 1071, 5381, 7071, 5233, 900, 67, 6694, 67, 8412, 273, 1381, 2787, 380, 8175, 38, 67, 7705, 274, 203, 565, 2254, 1071, 5381, 3331, 67, 1258, 38, 67, 7698, 1441, 273, 1728, 380, 490, 3445, 67, 7705, 342, 8175, 38, 67, 7705, 274, 203, 565, 2254, 1071, 5381, 6989, 67, 3194, 67, 21690, 273, 6969, 380, 8175, 38, 67, 7705, 31, 203, 565, 2254, 1071, 5381, 4552, 67, 3194, 67, 21690, 273, 1059, 9349, 380, 8175, 38, 67, 7705, 31, 203, 565, 2254, 1071, 5381, 611, 57, 985, 1258, 1448, 2056, 67, 3194, 67, 21690, 273, 6437, 380, 8175, 38, 67, 7705, 31, 203, 203, 565, 4232, 39, 3462, 490, 3445, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 27859, 329, 863, 31, 203, 203, 565, 1758, 1071, 3410, 31, 203, 565, 4232, 39, 3462, 1071, 4075, 5349, 67, 2316, 31, 203, 565, 2254, 1071, 4075, 5349, 67, 87, 1673, 31, 203, 565, 1426, 1071, 4075, 5349, 67, 7589, 31, 203, 565, 1426, 1071, 4075, 5349, 67, 14784, 67, 7589, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 2 ]
pragma solidity ^0.4.24; pragma experimental "v0.5.0"; import {PackageDB} from "./PackageDB.sol"; import {ReleaseDB} from "./ReleaseDB.sol"; import {ReleaseValidator} from "./ReleaseValidator.sol"; import {PackageRegistryInterface} from "./PackageRegistryInterface.sol"; import {Owned} from "./Owned.sol"; /// @title Database contract for a package index. /// @author Tim Coulter <[email protected]>, Piper Merriam <[email protected]> contract PackageRegistry is Owned, PackageRegistryInterface { PackageDB private packageDb; ReleaseDB private releaseDb; ReleaseValidator private releaseValidator; // Events event PackageRelease(bytes32 indexed nameHash, bytes32 indexed releaseId); event PackageTransfer(address indexed oldOwner, address indexed newOwner); // // Administrative API // /// @dev Sets the address of the PackageDb contract. /// @param newPackageDb The address to set for the PackageDb. function setPackageDb(address newPackageDb) public isOwner returns (bool) { packageDb = PackageDB(newPackageDb); return true; } /// @dev Sets the address of the ReleaseDb contract. /// @param newReleaseDb The address to set for the ReleaseDb. function setReleaseDb(address newReleaseDb) public isOwner returns (bool) { releaseDb = ReleaseDB(newReleaseDb); return true; } /// @dev Sets the address of the ReleaseValidator contract. /// @param newReleaseValidator The address to set for the ReleaseValidator. function setReleaseValidator(address newReleaseValidator) public isOwner returns (bool) { releaseValidator = ReleaseValidator(newReleaseValidator); return true; } // // +-------------+ // | Write API | // +-------------+ // /// @dev Creates a a new release for the named package. If this is the first release for the given package then this will also assign msg.sender as the owner of the package. Returns success. /// @notice Will create a new release the given package with the given release information. /// @param name Package name /// @param version Version string (ex: '1.0.0') /// @param manifestURI The URI for the release manifest for this release. function release( string name, string version, string manifestURI ) public isOwner returns (bytes32 id) { require(address(packageDb) != 0x0, "escape:PackageIndex:package-db-not-set"); require(address(releaseDb) != 0x0, "escape:PackageIndex:release-db-not-set"); require(address(releaseValidator) != 0x0, "escape:PackageIndex:release-validator-not-set"); bytes32 versionHash = releaseDb.hashVersion(version); // If the version for this release is not in the version database, populate // it. This must happen prior to validation to ensure that the version is // present in the releaseDb. if (!releaseDb.versionExists(versionHash)) { releaseDb.setVersion(version); } // Run release validator. This method reverts with an error message string // on failure. releaseValidator.validateRelease( packageDb, releaseDb, name, version, manifestURI ); // Both creates the package if it is new as well as updating the updatedAt // timestamp on the package. packageDb.setPackage(name); bytes32 nameHash = packageDb.hashName(name); // Create the release and add it to the list of package release hashes. releaseDb.setRelease(nameHash, versionHash, manifestURI); // Log the release. bytes32 releaseId = releaseDb.hashRelease(nameHash, versionHash); emit PackageRelease(nameHash, releaseId); return releaseId; } // // +------------+ // | Read API | // +------------+ // /// @dev Returns the address of the packageDb function getPackageDb() public view returns (address) { return address(packageDb); } /// @dev Returns the address of the releaseDb function getReleaseDb() public view returns (address) { return address(releaseDb); } /// @dev Returns the address of the releaseValidator function getReleaseValidator() public view returns (address) { return address(releaseValidator); } /// @dev Query the existence of a package with the given name. Returns boolean indicating whether the package exists. /// @param name Package name function packageExists(string name) public view returns (bool) { return packageDb.packageExists(packageDb.hashName(name)); } /// @dev Query the existence of a release at the provided version for the named package. Returns boolean indicating whether such a release exists. /// @param name Package name /// @param version Version string (ex: '1.0.0') function releaseExists( string name, string version ) public view returns (bool) { bytes32 nameHash = packageDb.hashName(name); bytes32 versionHash = releaseDb.hashVersion(version); return releaseDb.releaseExists(releaseDb.hashRelease(nameHash, versionHash)); } /// @dev Returns a slice of the array of all package hashes for the named package. /// @param _offset The starting index for the slice. /// @param limit The length of the slice function getAllPackageIds(uint _offset, uint limit) public view returns( bytes32[] packageIds, uint offset ) { return packageDb.getAllPackageIds(_offset, limit); } /// @dev Retrieves the name for the given name hash. /// @param nameHash The name hash to lookup the name for. function getPackageName(bytes32 nameHash) public view returns (string) { return packageDb.getPackageName(nameHash); } /// @dev Returns the package data. /// @param name Package name function getPackageData(string name) public view returns ( address packageOwner, uint createdAt, uint numReleases, uint updatedAt ) { bytes32 nameHash = packageDb.hashName(name); (createdAt, updatedAt) = packageDb.getPackageData(nameHash); numReleases = releaseDb.getNumReleasesForNameHash(nameHash); return (packageOwner, createdAt, numReleases, updatedAt); } /// @dev Returns the release data for the release associated with the given release hash. /// @param releaseId The release hash. function getReleaseData(bytes32 releaseId) public view returns ( string name, string version, string manifestURI ) { bytes32 versionHash; bytes32 nameHash; (nameHash,versionHash, ,) = releaseDb.getReleaseData(releaseId); name = packageDb.getPackageName(nameHash); version = releaseDb.getVersion(versionHash); manifestURI = releaseDb.getManifestURI(releaseId); return (name, version, manifestURI); } /// @dev Returns a slice of the array of all package hashes for the named package. /// @param offset The starting index for the slice. /// @param limit The length of the slice function getAllReleaseIds(string name, uint _offset, uint limit) public view returns ( bytes32[] releaseIds, uint offset ) { bytes32 nameHash = packageDb.hashName(name); return releaseDb.getAllReleaseIds(nameHash, _offset, limit); } // @dev Returns release id that *would* be generated for a name and version pair on `release`. // @param name Package name // @param version Version string (ex: '1.0.0') function generateReleaseId(string name, string version) public view returns (bytes32) { bytes32 nameHash = packageDb.hashName(name); bytes32 versionHash = releaseDb.hashVersion(version); return keccak256(abi.encodePacked(nameHash, versionHash)); } }
@dev Returns a slice of the array of all package hashes for the named package. @param _offset The starting index for the slice. @param limit The length of the slice
function getAllPackageIds(uint _offset, uint limit) public view returns( bytes32[] packageIds, uint offset ) { return packageDb.getAllPackageIds(_offset, limit); }
12,703,184
[ 1, 1356, 279, 2788, 434, 326, 526, 434, 777, 2181, 9869, 364, 326, 4141, 2181, 18, 225, 389, 3348, 1021, 5023, 770, 364, 326, 2788, 18, 225, 1800, 225, 1021, 769, 434, 326, 2788, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 5514, 2261, 2673, 12, 11890, 389, 3348, 16, 2254, 1800, 13, 203, 565, 1071, 203, 565, 1476, 203, 565, 1135, 12, 203, 1377, 1731, 1578, 8526, 2181, 2673, 16, 203, 1377, 2254, 1384, 203, 565, 262, 203, 225, 288, 203, 565, 327, 2181, 4331, 18, 588, 1595, 2261, 2673, 24899, 3348, 16, 1800, 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 ]
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./interface/IiToken.sol"; import "./interface/IRewardDistributorV3.sol"; import "./interface/IPriceOracle.sol"; import "./library/Initializable.sol"; import "./library/Ownable.sol"; import "./library/SafeRatioMath.sol"; import "./Controller.sol"; /** * @title dForce's lending reward distributor Contract * @author dForce */ contract RewardDistributorV3 is Initializable, Ownable, IRewardDistributorV3 { using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @notice the controller Controller public controller; /// @notice the global Reward distribution speed uint256 public globalDistributionSpeed; /// @notice the Reward distribution speed of each iToken mapping(address => uint256) public distributionSpeed; /// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa mapping(address => uint256) public distributionFactorMantissa; struct DistributionState { // Token's last updated index, stored as a mantissa uint256 index; // The block number the index was last updated at uint256 block; } /// @notice the Reward distribution supply state of each iToken mapping(address => DistributionState) public distributionSupplyState; /// @notice the Reward distribution borrow state of each iToken mapping(address => DistributionState) public distributionBorrowState; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionSupplierIndex; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionBorrowerIndex; /// @notice the Reward distributed into each account mapping(address => uint256) public reward; /// @notice the Reward token address address public rewardToken; /// @notice whether the reward distribution is paused bool public paused; /// @notice the Reward distribution speed supply side of each iToken mapping(address => uint256) public distributionSupplySpeed; /// @notice the global Reward distribution speed for supply uint256 public globalDistributionSupplySpeed; /** * @dev Throws if called by any account other than the controller. */ modifier onlyController() { require( address(controller) == msg.sender, "onlyController: caller is not the controller" ); _; } /** * @notice Initializes the contract. */ function initialize(Controller _controller) external initializer { require( address(_controller) != address(0), "initialize: controller address should not be zero address!" ); __Ownable_init(); controller = _controller; paused = true; } /** * @notice set reward token address * @dev Admin function, only owner can call this * @param _newRewardToken the address of reward token */ function _setRewardToken(address _newRewardToken) external override onlyOwner { address _oldRewardToken = rewardToken; require( _newRewardToken != address(0) && _newRewardToken != _oldRewardToken, "Reward token address invalid" ); rewardToken = _newRewardToken; emit NewRewardToken(_oldRewardToken, _newRewardToken); } /** * @notice Add the iToken as receipient * @dev Admin function, only controller can call this * @param _iToken the iToken to add as recipient * @param _distributionFactor the distribution factor of the recipient */ function _addRecipient(address _iToken, uint256 _distributionFactor) external override onlyController { distributionFactorMantissa[_iToken] = _distributionFactor; distributionSupplyState[_iToken] = DistributionState({ index: 0, block: block.number }); distributionBorrowState[_iToken] = DistributionState({ index: 0, block: block.number }); emit NewRecipient(_iToken, _distributionFactor); } /** * @notice Pause the reward distribution * @dev Admin function, pause will set global speed to 0 to stop the accumulation */ function _pause() external override onlyOwner { // Set the global distribution speed to 0 to stop accumulation address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], 0); _setDistributionSupplySpeed(_iTokens[i], 0); } _refreshGlobalDistributionSpeeds(); _setPaused(true); } /** * @notice Unpause and set distribution speeds * @dev Admin function * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external override onlyOwner { _setPaused(false); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } /** * @notice Pause/Unpause the reward distribution * @dev Admin function * @param _paused whether to pause/unpause the distribution */ function _setPaused(bool _paused) internal { paused = _paused; emit Paused(_paused); } /** * @notice Set distribution speeds * @dev Admin function, will fail when paused * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSpeeds( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change speeds when paused"); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } function _setDistributionSpeedsInternal( address[] memory _borrowiTokens, uint256[] memory _borrowSpeeds, address[] memory _supplyiTokens, uint256[] memory _supplySpeeds ) internal { _setDistributionBorrowSpeedsInternal(_borrowiTokens, _borrowSpeeds); _setDistributionSupplySpeedsInternal(_supplyiTokens, _supplySpeeds); } /** * @notice Set borrow distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The borrow asset array * @param _borrowSpeeds The borrow speed array */ function _setDistributionBorrowSpeeds( address[] calldata _iTokens, uint256[] calldata _borrowSpeeds ) external onlyOwner { require(!paused, "Can not change borrow speeds when paused"); _setDistributionBorrowSpeedsInternal(_iTokens, _borrowSpeeds); _refreshGlobalDistributionSpeeds(); } /** * @notice Set supply distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSupplySpeeds( address[] calldata _iTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change supply speeds when paused"); _setDistributionSupplySpeedsInternal(_iTokens, _supplySpeeds); _refreshGlobalDistributionSpeeds(); } function _refreshGlobalDistributionSpeeds() internal { address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; uint256 _borrowSpeed; uint256 _supplySpeed; for (uint256 i = 0; i < _len; i++) { _borrowSpeed = _borrowSpeed.add(distributionSpeed[_iTokens[i]]); _supplySpeed = _supplySpeed.add( distributionSupplySpeed[_iTokens[i]] ); } globalDistributionSpeed = _borrowSpeed; globalDistributionSupplySpeed = _supplySpeed; emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed); } function _setDistributionBorrowSpeedsInternal( address[] memory _iTokens, uint256[] memory _borrowSpeeds ) internal { require( _iTokens.length == _borrowSpeeds.length, "Length of _iTokens and _borrowSpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], _borrowSpeeds[i]); } } function _setDistributionSupplySpeedsInternal( address[] memory _iTokens, uint256[] memory _supplySpeeds ) internal { require( _iTokens.length == _supplySpeeds.length, "Length of _iTokens and _supplySpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionSupplySpeed(_iTokens[i], _supplySpeeds[i]); } } function _setDistributionBorrowSpeed(address _iToken, uint256 _borrowSpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update borrow state before updating new speed _updateDistributionState(_iToken, true); distributionSpeed[_iToken] = _borrowSpeed; emit DistributionBorrowSpeedUpdated(_iToken, _borrowSpeed); } function _setDistributionSupplySpeed(address _iToken, uint256 _supplySpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update supply state before updating new speed _updateDistributionState(_iToken, false); distributionSupplySpeed[_iToken] = _supplySpeed; emit DistributionSupplySpeedUpdated(_iToken, _supplySpeed); } /** * @notice Update the iToken's Reward distribution state * @dev Will be called every time when the iToken's supply/borrow changes * @param _iToken The iToken to be updated * @param _isBorrow whether to update the borrow state */ function updateDistributionState(address _iToken, bool _isBorrow) external override { // Skip all updates if it is paused if (paused) { return; } _updateDistributionState(_iToken, _isBorrow); } function _updateDistributionState(address _iToken, bool _isBorrow) internal { require(controller.hasiToken(_iToken), "Token has not been listed"); DistributionState storage state = _isBorrow ? distributionBorrowState[_iToken] : distributionSupplyState[_iToken]; uint256 _speed = _isBorrow ? distributionSpeed[_iToken] : distributionSupplySpeed[_iToken]; uint256 _blockNumber = block.number; uint256 _deltaBlocks = _blockNumber.sub(state.block); if (_deltaBlocks > 0 && _speed > 0) { uint256 _totalToken = _isBorrow ? IiToken(_iToken).totalBorrows().rdiv( IiToken(_iToken).borrowIndex() ) : IERC20Upgradeable(_iToken).totalSupply(); uint256 _totalDistributed = _speed.mul(_deltaBlocks); // Reward distributed per token since last time uint256 _distributedPerToken = _totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0; state.index = state.index.add(_distributedPerToken); } state.block = _blockNumber; } /** * @notice Update the account's Reward distribution state * @dev Will be called every time when the account's supply/borrow changes * @param _iToken The iToken to be updated * @param _account The account to be updated * @param _isBorrow whether to update the borrow state */ function updateReward( address _iToken, address _account, bool _isBorrow ) external override { _updateReward(_iToken, _account, _isBorrow); } function _updateReward( address _iToken, address _account, bool _isBorrow ) internal { require(_account != address(0), "Invalid account address!"); require(controller.hasiToken(_iToken), "Token has not been listed"); uint256 _iTokenIndex; uint256 _accountIndex; uint256 _accountBalance; if (_isBorrow) { _iTokenIndex = distributionBorrowState[_iToken].index; _accountIndex = distributionBorrowerIndex[_iToken][_account]; _accountBalance = IiToken(_iToken) .borrowBalanceStored(_account) .rdiv(IiToken(_iToken).borrowIndex()); // Update the account state to date distributionBorrowerIndex[_iToken][_account] = _iTokenIndex; } else { _iTokenIndex = distributionSupplyState[_iToken].index; _accountIndex = distributionSupplierIndex[_iToken][_account]; _accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account); // Update the account state to date distributionSupplierIndex[_iToken][_account] = _iTokenIndex; } uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex); uint256 _amount = _accountBalance.rmul(_deltaIndex); if (_amount > 0) { reward[_account] = reward[_account].add(_amount); emit RewardDistributed(_iToken, _account, _amount, _accountIndex); } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update */ function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) public override { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, false); _updateDistributionState(_iToken, true); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], false); _updateReward(_iToken, _holders[j], true); } } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update * @param _isBorrow whether to update the borrow state */ function _updateRewards( address[] memory _holders, address[] memory _iTokens, bool _isBorrow ) internal { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, _isBorrow); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], _isBorrow); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _iTokens The _iTokens to claim from */ function claimReward(address[] memory _holders, address[] memory _iTokens) public override { updateRewardBatch(_holders, _iTokens); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _suppliediTokens The _suppliediTokens to claim from * @param _borrowediTokens The _borrowediTokens to claim from */ function claimRewards( address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens ) external override { _updateRewards(_holders, _suppliediTokens, false); _updateRewards(_holders, _borrowediTokens, true); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in all iTokens by the holders * @param _holders The account to claim for */ function claimAllReward(address[] memory _holders) external override { claimReward(_holders, controller.getAlliTokens()); } } // 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.12; import "./IInterestRateModelInterface.sol"; import "./IControllerInterface.sol"; interface IiToken { function isSupported() external returns (bool); function isiToken() external returns (bool); //---------------------------------- //********* User Interface ********* //---------------------------------- function mint(address recipient, uint256 mintAmount) external; function mintAndEnterMarket(address recipient, uint256 mintAmount) external; function redeem(address from, uint256 redeemTokens) external; function redeemUnderlying(address from, uint256 redeemAmount) external; function borrow(uint256 borrowAmount) external; function repayBorrow(uint256 repayAmount) external; function repayBorrowBehalf(address borrower, uint256 repayAmount) external; function liquidateBorrow( address borrower, uint256 repayAmount, address iTokenCollateral ) external; function flashloan( address recipient, uint256 loanAmount, bytes memory data ) external; function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external; function updateInterest() external returns (bool); function controller() external view returns (address); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function totalBorrows() external view returns (uint256); function borrowBalanceCurrent(address _user) external returns (uint256); function borrowBalanceStored(address _user) external view returns (uint256); function borrowIndex() external view returns (uint256); function getAccountSnapshot(address _account) external view returns ( uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function getCash() external view returns (uint256); //---------------------------------- //********* Owner Actions ********** //---------------------------------- function _setNewReserveRatio(uint256 _newReserveRatio) external; function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external; function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external; function _setController(IControllerInterface _newController) external; function _setInterestRateModel( IInterestRateModelInterface _newInterestRateModel ) external; function _withdrawReserves(uint256 _withdrawAmount) external; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRewardDistributorV3 { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); /// @notice Emitted when iToken's Distribution borrow speed is updated event DistributionBorrowSpeedUpdated(address iToken, uint256 borrowSpeed); /// @notice Emitted when iToken's Distribution supply speed is updated event DistributionSupplySpeedUpdated(address iToken, uint256 supplySpeed); /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; function claimRewards(address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IiToken.sol"; interface IPriceOracle { /** * @notice Get the underlying price of a iToken asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(address _iToken) external view returns (uint256); /** * @notice Get the price of a underlying asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable and whether the price is valid. */ function getUnderlyingPriceAndStatus(address _iToken) external view returns (uint256, bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( !_initialized, "Initializable: contract is already initialized" ); _; _initialized = true; } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 {_setPendingOwner} and {_acceptOwner}. */ contract Ownable { /** * @dev Returns the address of the current owner. */ address payable public owner; /** * @dev Returns the address of the current pending owner. */ address payable public pendingOwner; event NewOwner(address indexed previousOwner, address indexed newOwner); event NewPendingOwner( address indexed oldPendingOwner, address indexed newPendingOwner ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender, "onlyOwner: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal { owner = msg.sender; emit NewOwner(address(0), msg.sender); } /** * @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason. * @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer. * @param newPendingOwner New pending owner. */ function _setPendingOwner(address payable newPendingOwner) external onlyOwner { require( newPendingOwner != address(0) && newPendingOwner != pendingOwner, "_setPendingOwner: New owenr can not be zero address and owner has been set!" ); // Gets current owner. address oldPendingOwner = pendingOwner; // Sets new pending owner. pendingOwner = newPendingOwner; emit NewPendingOwner(oldPendingOwner, newPendingOwner); } /** * @dev Accepts the admin rights, but only for pendingOwenr. */ function _acceptOwner() external { require( msg.sender == pendingOwner, "_acceptOwner: Only for pending owner!" ); // Gets current values for events. address oldOwner = owner; address oldPendingOwner = pendingOwner; // Set the new contract owner. owner = pendingOwner; // Clear the pendingOwner. pendingOwner = address(0); emit NewOwner(oldOwner, owner); emit NewPendingOwner(oldPendingOwner, pendingOwner); } uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; library SafeRatioMath { using SafeMathUpgradeable for uint256; uint256 private constant BASE = 10**18; uint256 private constant DOUBLE = 10**36; function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.add(y.sub(1)).div(y); } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).div(BASE); } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).div(y); } function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).add(y.sub(1)).div(y); } function tmul( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256 result) { result = x.mul(y).mul(z).div(DOUBLE); } 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 rounding. for { n := div(n, 2) } n { n := div(n, 2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0, 0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0, 0) } x := div(xxRound, base) if mod(n, 2) { let zx := mul(z, x) if and( iszero(iszero(x)), iszero(eq(div(zx, x), z)) ) { revert(0, 0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0, 0) } z := div(zxRound, base) } } } } } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "./interface/IControllerInterface.sol"; import "./interface/IPriceOracle.sol"; import "./interface/IiToken.sol"; import "./interface/IRewardDistributor.sol"; import "./library/Initializable.sol"; import "./library/Ownable.sol"; import "./library/SafeRatioMath.sol"; /** * @title dForce's lending controller Contract * @author dForce */ contract Controller is Initializable, Ownable, IControllerInterface { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @dev EnumerableSet of all iTokens EnumerableSetUpgradeable.AddressSet internal iTokens; struct Market { /* * Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be in [0, 0.9], and stored as a mantissa. */ uint256 collateralFactorMantissa; /* * Multiplier representing the most one can borrow the asset. * For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor. * When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value * Must be between (0, 1], and stored as a mantissa. */ uint256 borrowFactorMantissa; /* * The borrow capacity of the asset, will be checked in beforeBorrow() * -1 means there is no limit on the capacity * 0 means the asset can not be borrowed any more */ uint256 borrowCapacity; /* * The supply capacity of the asset, will be checked in beforeMint() * -1 means there is no limit on the capacity * 0 means the asset can not be supplied any more */ uint256 supplyCapacity; // Whether market's mint is paused bool mintPaused; // Whether market's redeem is paused bool redeemPaused; // Whether market's borrow is paused bool borrowPaused; } /// @notice Mapping of iTokens to corresponding markets mapping(address => Market) public markets; struct AccountData { // Account's collateral assets EnumerableSetUpgradeable.AddressSet collaterals; // Account's borrowed assets EnumerableSetUpgradeable.AddressSet borrowed; } /// @dev Mapping of accounts' data, including collateral and borrowed assets mapping(address => AccountData) internal accountsData; /** * @notice Oracle to query the price of a given asset */ address public priceOracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; // closeFactorMantissa must be strictly greater than this value uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; // liquidationIncentiveMantissa must be no less than this value uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 // collateralFactorMantissa must not exceed this value uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0 // borrowFactorMantissa must not exceed this value uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0 /** * @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency */ address public pauseGuardian; /// @notice whether global transfer is paused bool public transferPaused; /// @notice whether global seize is paused bool public seizePaused; /** * @notice the address of reward distributor */ address public rewardDistributor; /** * @dev Check if called by owner or pauseGuardian, and only owner can unpause */ modifier checkPauser(bool _paused) { require( msg.sender == owner || (msg.sender == pauseGuardian && _paused), "Only owner and guardian can pause and only owner can unpause" ); _; } /** * @notice Initializes the contract. */ function initialize() external initializer { __Ownable_init(); } /*********************************/ /******** Security Check *********/ /*********************************/ /** * @notice Ensure this is a Controller contract. */ function isController() external view override returns (bool) { return true; } /*********************************/ /******** Admin Operations *******/ /*********************************/ /** * @notice Admin function to add iToken into supported markets * Checks if the iToken already exsits * Will `revert()` if any check fails * @param _iToken The _iToken to add * @param _collateralFactor The _collateralFactor of _iToken * @param _borrowFactor The _borrowFactor of _iToken * @param _supplyCapacity The _supplyCapacity of _iToken * @param _distributionFactor The _distributionFactor of _iToken */ function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external override onlyOwner { require(IiToken(_iToken).isSupported(), "Token is not supported"); // Market must not have been listed, EnumerableSet.add() will return false if it exsits require(iTokens.add(_iToken), "Token has already been listed"); require( _collateralFactor <= collateralFactorMaxMantissa, "Collateral factor invalid" ); require( _borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Underlying price is unavailable" ); markets[_iToken] = Market({ collateralFactorMantissa: _collateralFactor, borrowFactorMantissa: _borrowFactor, borrowCapacity: _borrowCapacity, supplyCapacity: _supplyCapacity, mintPaused: false, redeemPaused: false, borrowPaused: false }); IRewardDistributor(rewardDistributor)._addRecipient( _iToken, _distributionFactor ); emit MarketAdded( _iToken, _collateralFactor, _borrowFactor, _supplyCapacity, _borrowCapacity, _distributionFactor ); } /** * @notice Sets price oracle * @dev Admin function to set price oracle * @param _newOracle New oracle contract */ function _setPriceOracle(address _newOracle) external override onlyOwner { address _oldOracle = priceOracle; require( _newOracle != address(0) && _newOracle != _oldOracle, "Oracle address invalid" ); priceOracle = _newOracle; emit NewPriceOracle(_oldOracle, _newOracle); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param _newCloseFactorMantissa New close factor, scaled by 1e18 */ function _setCloseFactor(uint256 _newCloseFactorMantissa) external override onlyOwner { require( _newCloseFactorMantissa >= closeFactorMinMantissa && _newCloseFactorMantissa <= closeFactorMaxMantissa, "Close factor invalid" ); uint256 _oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = _newCloseFactorMantissa; emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 */ function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa) external override onlyOwner { require( _newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa && _newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, "Liquidation incentive invalid" ); uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa; emit NewLiquidationIncentive( _oldLiquidationIncentiveMantissa, _newLiquidationIncentiveMantissa ); } /** * @notice Sets the collateralFactor for a iToken * @dev Admin function to set collateralFactor for a iToken * @param _iToken The token to set the factor on * @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18 */ function _setCollateralFactor( address _iToken, uint256 _newCollateralFactorMantissa ) external override onlyOwner { _checkiTokenListed(_iToken); require( _newCollateralFactorMantissa <= collateralFactorMaxMantissa, "Collateral factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set collateral factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa; _market.collateralFactorMantissa = _newCollateralFactorMantissa; emit NewCollateralFactor( _iToken, _oldCollateralFactorMantissa, _newCollateralFactorMantissa ); } /** * @notice Sets the borrowFactor for a iToken * @dev Admin function to set borrowFactor for a iToken * @param _iToken The token to set the factor on * @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18 */ function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa) external override onlyOwner { _checkiTokenListed(_iToken); require( _newBorrowFactorMantissa > 0 && _newBorrowFactorMantissa <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set borrow factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa; _market.borrowFactorMantissa = _newBorrowFactorMantissa; emit NewBorrowFactor( _iToken, _oldBorrowFactorMantissa, _newBorrowFactorMantissa ); } /** * @notice Sets the borrowCapacity for a iToken * @dev Admin function to set borrowCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newBorrowCapacity The new borrow capacity */ function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldBorrowCapacity = _market.borrowCapacity; _market.borrowCapacity = _newBorrowCapacity; emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity); } /** * @notice Sets the supplyCapacity for a iToken * @dev Admin function to set supplyCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newSupplyCapacity The new supply capacity */ function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldSupplyCapacity = _market.supplyCapacity; _market.supplyCapacity = _newSupplyCapacity; emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity); } /** * @notice Sets the pauseGuardian * @dev Admin function to set pauseGuardian * @param _newPauseGuardian The new pause guardian */ function _setPauseGuardian(address _newPauseGuardian) external override onlyOwner { address _oldPauseGuardian = pauseGuardian; require( _newPauseGuardian != address(0) && _newPauseGuardian != _oldPauseGuardian, "Pause guardian address invalid" ); pauseGuardian = _newPauseGuardian; emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian); } /** * @notice pause/unpause mint() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllMintPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setMintPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause mint() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setMintPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setMintPausedInternal(_iToken, _paused); } function _setMintPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].mintPaused = _paused; emit MintPaused(_iToken, _paused); } /** * @notice pause/unpause redeem() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllRedeemPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setRedeemPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause redeem() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setRedeemPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setRedeemPausedInternal(_iToken, _paused); } function _setRedeemPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); } /** * @notice pause/unpause borrow() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllBorrowPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setBorrowPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause borrow() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setBorrowPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setBorrowPausedInternal(_iToken, _paused); } function _setBorrowPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause global transfer() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setTransferPaused(bool _paused) external override checkPauser(_paused) { _setTransferPausedInternal(_paused); } function _setTransferPausedInternal(bool _paused) internal { transferPaused = _paused; emit TransferPaused(_paused); } /** * @notice pause/unpause global seize() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setSeizePaused(bool _paused) external override checkPauser(_paused) { _setSeizePausedInternal(_paused); } function _setSeizePausedInternal(bool _paused) internal { seizePaused = _paused; emit SeizePaused(_paused); } /** * @notice pause/unpause all actions iToken, including mint/redeem/borrow * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setiTokenPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setiTokenPausedInternal(_iToken, _paused); } function _setiTokenPausedInternal(address _iToken, bool _paused) internal { Market storage _market = markets[_iToken]; _market.mintPaused = _paused; emit MintPaused(_iToken, _paused); _market.redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); _market.borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setProtocolPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { address _iToken = _iTokens.at(i); _setiTokenPausedInternal(_iToken, _paused); } _setTransferPausedInternal(_paused); _setSeizePausedInternal(_paused); } /** * @notice Sets Reward Distributor * @dev Admin function to set reward distributor * @param _newRewardDistributor new reward distributor */ function _setRewardDistributor(address _newRewardDistributor) external override onlyOwner { address _oldRewardDistributor = rewardDistributor; require( _newRewardDistributor != address(0) && _newRewardDistributor != _oldRewardDistributor, "Reward Distributor address invalid" ); rewardDistributor = _newRewardDistributor; emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor); } /*********************************/ /******** Poclicy Hooks **********/ /*********************************/ /** * @notice Hook function before iToken `mint()` * Checks if the account should be allowed to mint the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the mint against * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken */ function beforeMint( address _iToken, address _minter, uint256 _mintAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.mintPaused, "Token mint has been paused"); // Check the iToken's supply capacity, -1 means no limit uint256 _totalSupplyUnderlying = IERC20Upgradeable(_iToken).totalSupply().rmul( IiToken(_iToken).exchangeRateStored() ); require( _totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity, "Token supply capacity reached" ); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _minter, false ); } /** * @notice Hook function after iToken `mint()` * Will `revert()` if any operation fails * @param _iToken The iToken being minted * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken * @param _mintedAmount The amount of iToken being minted */ function afterMint( address _iToken, address _minter, uint256 _mintAmount, uint256 _mintedAmount ) external override { _iToken; _minter; _mintAmount; _mintedAmount; } /** * @notice Hook function before iToken `redeem()` * Checks if the account should be allowed to redeem the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the redeem against * @param _redeemer The account which would redeem iToken * @param _redeemAmount The amount of iToken to redeem */ function beforeRedeem( address _iToken, address _redeemer, uint256 _redeemAmount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!markets[_iToken].redeemPaused, "Token redeem has been paused"); _redeemAllowed(_iToken, _redeemer, _redeemAmount); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _redeemer, false ); } /** * @notice Hook function after iToken `redeem()` * Will `revert()` if any operation fails * @param _iToken The iToken being redeemed * @param _redeemer The account which redeemed iToken * @param _redeemAmount The amount of iToken being redeemed * @param _redeemedUnderlying The amount of underlying being redeemed */ function afterRedeem( address _iToken, address _redeemer, uint256 _redeemAmount, uint256 _redeemedUnderlying ) external override { _iToken; _redeemer; _redeemAmount; _redeemedUnderlying; } /** * @notice Hook function before iToken `borrow()` * Checks if the account should be allowed to borrow the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the borrow against * @param _borrower The account which would borrow iToken * @param _borrowAmount The amount of underlying to borrow */ function beforeBorrow( address _iToken, address _borrower, uint256 _borrowAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.borrowPaused, "Token borrow has been paused"); if (!hasBorrowed(_borrower, _iToken)) { // Unlike collaterals, borrowed asset can only be added by iToken, // rather than enabled by user directly. require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just add it _addToBorrowed(_borrower, _iToken); } // Check borrower's equity (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount); require(_shortfall == 0, "Account has some shortfall"); // Check the iToken's borrow capacity, -1 means no limit uint256 _totalBorrows = IiToken(_iToken).totalBorrows(); require( _totalBorrows.add(_borrowAmount) <= _market.borrowCapacity, "Token borrow capacity reached" ); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); } /** * @notice Hook function after iToken `borrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being borrewd * @param _borrower The account which borrowed iToken * @param _borrowedAmount The amount of underlying being borrowed */ function afterBorrow( address _iToken, address _borrower, uint256 _borrowedAmount ) external override { _iToken; _borrower; _borrowedAmount; } /** * @notice Hook function before iToken `repayBorrow()` * Checks if the account should be allowed to repay the given iToken * for the borrower. Will `revert()` if any check fails * @param _iToken The iToken to verify the repay against * @param _payer The account which would repay iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); _payer; _repayAmount; } /** * @notice Hook function after iToken `repayBorrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being repaid * @param _payer The account which would repay * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying being repaied */ function afterRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Remove _iToken from borrowed list if new borrow balance is 0 if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) { // Only allow called by iToken as we are going to remove this token from borrower's borrowed list require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just remove it _removeFromBorrowed(_borrower, _iToken); } _payer; _repayAmount; } /** * @notice Hook function before iToken `liquidateBorrow()` * Checks if the account should be allowed to liquidate the given iToken * for the borrower. Will `revert()` if any check fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be liqudate with * @param _liquidator The account which would repay the borrowed iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repayAmount ) external override { // Tokens must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); (, uint256 _shortfall, , ) = calcAccountEquity(_borrower); require(_shortfall > 0, "Account does not have shortfall"); // Only allowed to repay the borrow balance's close factor uint256 _borrowBalance = IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower); uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa); require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed"); _liquidator; } /** * @notice Hook function after iToken `liquidateBorrow()` * Will `revert()` if any operation fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _liquidator The account which would repay and seize * @param _borrower The account which has borrowed * @param _repaidAmount The amount of underlying being repaied * @param _seizedAmount The amount of collateral being seized */ function afterLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repaidAmount, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _repaidAmount; _seizedAmount; // Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance // No need to check whether should remove from borrowed asset list } /** * @notice Hook function before iToken `seize()` * Checks if the liquidator should be allowed to seize the collateral iToken * Will `revert()` if any check fails * @param _iTokenCollateral The collateral iToken to be seize * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid the borrowed iToken * @param _borrower The account which has borrowed * @param _seizeAmount The amount of collateral iToken to seize */ function beforeSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizeAmount ) external override { require(!seizePaused, "Seize has been paused"); // Markets must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); // Sanity Check the controllers require( IiToken(_iTokenBorrowed).controller() == IiToken(_iTokenCollateral).controller(), "Controller mismatch between Borrowed and Collateral" ); // Update the Reward Distribution Supply state on collateral IRewardDistributor(rewardDistributor).updateDistributionState( _iTokenCollateral, false ); // Update reward of liquidator and borrower on collateral IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _liquidator, false ); IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _borrower, false ); _seizeAmount; } /** * @notice Hook function after iToken `seize()` * Will `revert()` if any operation fails * @param _iTokenCollateral The collateral iToken to be seized * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid and seized * @param _borrower The account which has borrowed * @param _seizedAmount The amount of collateral being seized */ function afterSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _seizedAmount; } /** * @notice Hook function before iToken `transfer()` * Checks if the transfer should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be transfered * @param _from The account to be transfered from * @param _to The account to be transfered to * @param _amount The amount to be transfered */ function beforeTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!transferPaused, "Transfer has been paused"); // Check account equity with this amount to decide whether the transfer is allowed _redeemAllowed(_iToken, _from, _amount); // Update the Reward Distribution supply state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); // Update reward of from and to IRewardDistributor(rewardDistributor).updateReward( _iToken, _from, false ); IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false); } /** * @notice Hook function after iToken `transfer()` * Will `revert()` if any operation fails * @param _iToken The iToken was transfered * @param _from The account was transfer from * @param _to The account was transfer to * @param _amount The amount was transfered */ function afterTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { _iToken; _from; _to; _amount; } /** * @notice Hook function before iToken `flashloan()` * Checks if the flashloan should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be flashloaned * @param _to The account flashloaned transfer to * @param _amount The amount to be flashloaned */ function beforeFlashloan( address _iToken, address _to, uint256 _amount ) external override { // Flashloan share the same pause state with borrow require(!markets[_iToken].borrowPaused, "Token borrow has been paused"); _checkiTokenListed(_iToken); _to; _amount; // Update the Reward Distribution Borrow state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); } /** * @notice Hook function after iToken `flashloan()` * Will `revert()` if any operation fails * @param _iToken The iToken was flashloaned * @param _to The account flashloan transfer to * @param _amount The amount was flashloaned */ function afterFlashloan( address _iToken, address _to, uint256 _amount ) external override { _iToken; _to; _amount; } /*********************************/ /***** Internal Functions *******/ /*********************************/ function _redeemAllowed( address _iToken, address _redeemer, uint256 _amount ) private view { _checkiTokenListed(_iToken); // No need to check liquidity if _redeemer has not used _iToken as collateral if (!accountsData[_redeemer].collaterals.contains(_iToken)) { return; } (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0); require(_shortfall == 0, "Account has some shortfall"); } /** * @dev Check if _iToken is listed */ function _checkiTokenListed(address _iToken) private view { require(iTokens.contains(_iToken), "Token has not been listed"); } /*********************************/ /** Account equity calculation ***/ /*********************************/ /** * @notice Calculates current account equity * @param _account The account to query equity of * @return account equity, shortfall, collateral value, borrowed value. */ function calcAccountEquity(address _account) public view override returns ( uint256, uint256, uint256, uint256 ) { return calcAccountEquityWithEffect(_account, address(0), 0, 0); } /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `iTokenBalance` is the number of iTokens the account owns in the collateral, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountEquityLocalVars { uint256 sumCollateral; uint256 sumBorrowed; uint256 iTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 underlyingPrice; uint256 collateralValue; uint256 borrowValue; } /** * @notice Calculates current account equity plus some token and amount to effect * @param _account The account to query equity of * @param _tokenToEffect The token address to add some additional redeeem/borrow * @param _redeemAmount The additional amount to redeem * @param _borrowAmount The additional amount to borrow * @return account euqity, shortfall, collateral value, borrowed value plus the effect. */ function calcAccountEquityWithEffect( address _account, address _tokenToEffect, uint256 _redeemAmount, uint256 _borrowAmount ) internal view virtual returns ( uint256, uint256, uint256, uint256 ) { AccountEquityLocalVars memory _local; AccountData storage _accountData = accountsData[_account]; // Calculate value of all collaterals // collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor // collateralValue = balance * collateralValuePerToken // sumCollateral += collateralValue uint256 _len = _accountData.collaterals.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.collaterals.at(i)); _local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf( _account ); _local.exchangeRateMantissa = _token.exchangeRateStored(); if (_tokenToEffect == address(_token) && _redeemAmount > 0) { _local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); _local.collateralValue = _local .iTokenBalance .mul(_local.underlyingPrice) .rmul(_local.exchangeRateMantissa) .rmul(markets[address(_token)].collateralFactorMantissa); _local.sumCollateral = _local.sumCollateral.add( _local.collateralValue ); } // Calculate all borrowed value // borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor // sumBorrowed += borrowValue _len = _accountData.borrowed.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.borrowed.at(i)); _local.borrowBalance = _token.borrowBalanceStored(_account); if (_tokenToEffect == address(_token) && _borrowAmount > 0) { _local.borrowBalance = _local.borrowBalance.add(_borrowAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); // borrowFactorMantissa can not be set to 0 _local.borrowValue = _local .borrowBalance .mul(_local.underlyingPrice) .rdiv(markets[address(_token)].borrowFactorMantissa); _local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue); } // Should never underflow return _local.sumCollateral > _local.sumBorrowed ? ( _local.sumCollateral - _local.sumBorrowed, uint256(0), _local.sumCollateral, _local.sumBorrowed ) : ( uint256(0), _local.sumBorrowed - _local.sumCollateral, _local.sumCollateral, _local.sumBorrowed ); } /** * @notice Calculate amount of collateral iToken to seize after repaying an underlying amount * @dev Used in liquidation * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _actualRepayAmount The amount of underlying token liquidator has repaied * @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized */ function liquidateCalculateSeizeTokens( address _iTokenBorrowed, address _iTokenCollateral, uint256 _actualRepayAmount ) external view virtual override returns (uint256 _seizedTokenCollateral) { /* Read oracle prices for borrowed and collateral assets */ uint256 _priceBorrowed = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed); uint256 _priceCollateral = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral); require( _priceBorrowed != 0 && _priceCollateral != 0, "Borrowed or Collateral asset price is invalid" ); uint256 _valueRepayPlusIncentive = _actualRepayAmount.mul(_priceBorrowed).rmul( liquidationIncentiveMantissa ); // Use stored value here as it is view function uint256 _exchangeRateMantissa = IiToken(_iTokenCollateral).exchangeRateStored(); // seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral // valuePerTokenCollateral = exchangeRateMantissa * priceCollateral _seizedTokenCollateral = _valueRepayPlusIncentive .rdiv(_exchangeRateMantissa) .div(_priceCollateral); } /*********************************/ /*** Account Markets Operation ***/ /*********************************/ /** * @notice Returns the markets list the account has entered * @param _account The address of the account to query * @return _accountCollaterals The markets list the account has entered */ function getEnteredMarkets(address _account) external view override returns (address[] memory _accountCollaterals) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.collaterals.length(); _accountCollaterals = new address[](_len); for (uint256 i = 0; i < _len; i++) { _accountCollaterals[i] = _accountData.collaterals.at(i); } } /** * @notice Add markets to `msg.sender`'s markets list for liquidity calculations * @param _iTokens The list of addresses of the iToken markets to be entered * @return _results Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _enterMarket(_iTokens[i], msg.sender); } } /** * @notice Only expect to be called by iToken contract. * @dev Add the market to the account's markets list for liquidity calculations * @param _account The address of the account to modify */ function enterMarketFromiToken(address _account) external override { require( _enterMarket(msg.sender, _account), "enterMarketFromiToken: Only can be called by a supported iToken!" ); } /** * @notice Add the market to the account's markets list for liquidity calculations * @param _iToken The market to enter * @param _account The address of the account to modify * @return True if entered successfully, false for non-listed market or other errors */ function _enterMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return false; } // add() will return false if iToken is in account's market list if (accountsData[_account].collaterals.add(_iToken)) { emit MarketEntered(_iToken, _account); } return true; } /** * @notice Returns whether the given account has entered the market * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has entered the market, otherwise false. */ function hasEnteredMarket(address _account, address _iToken) external view override returns (bool) { return accountsData[_account].collaterals.contains(_iToken); } /** * @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations * @param _iTokens The list of addresses of the iToken to exit * @return _results Success indicators for whether each corresponding market was exited */ function exitMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _exitMarket(_iTokens[i], msg.sender); } } /** * @notice Remove the market to the account's markets list for liquidity calculations * @param _iToken The market to exit * @param _account The address of the account to modify * @return True if exit successfully, false for non-listed market or other errors */ function _exitMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return true; } // Account has not entered this market, skip it if (!accountsData[_account].collaterals.contains(_iToken)) { return true; } // Get the iToken balance uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account); // Check account's equity if all balance are redeemed // which means iToken can be removed from collaterals _redeemAllowed(_iToken, _account, _balance); // Have checked account has entered market before accountsData[_account].collaterals.remove(_iToken); emit MarketExited(_iToken, _account); return true; } /** * @notice Returns the asset list the account has borrowed * @param _account The address of the account to query * @return _borrowedAssets The asset list the account has borrowed */ function getBorrowedAssets(address _account) external view override returns (address[] memory _borrowedAssets) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.borrowed.length(); _borrowedAssets = new address[](_len); for (uint256 i = 0; i < _len; i++) { _borrowedAssets[i] = _accountData.borrowed.at(i); } } /** * @notice Add the market to the account's borrowed list for equity calculations * @param _iToken The iToken of underlying to borrow * @param _account The address of the account to modify */ function _addToBorrowed(address _account, address _iToken) internal { // add() will return false if iToken is in account's market list if (accountsData[_account].borrowed.add(_iToken)) { emit BorrowedAdded(_iToken, _account); } } /** * @notice Returns whether the given account has borrowed the given iToken * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has borrowed the iToken, otherwise false. */ function hasBorrowed(address _account, address _iToken) public view override returns (bool) { return accountsData[_account].borrowed.contains(_iToken); } /** * @notice Remove the iToken from the account's borrowed list * @param _iToken The iToken to remove * @param _account The address of the account to modify */ function _removeFromBorrowed(address _account, address _iToken) internal { // remove() will return false if iToken does not exist in account's borrowed list if (accountsData[_account].borrowed.remove(_iToken)) { emit BorrowedRemoved(_iToken, _account); } } /*********************************/ /****** General Information ******/ /*********************************/ /** * @notice Return all of the iTokens * @return _alliTokens The list of iToken addresses */ function getAlliTokens() public view override returns (address[] memory _alliTokens) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); _alliTokens = new address[](_len); for (uint256 i = 0; i < _len; i++) { _alliTokens[i] = _iTokens.at(i); } } /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) public view override returns (bool) { return iTokens.contains(_iToken); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title dForce Lending Protocol's InterestRateModel Interface. * @author dForce Team. */ interface IInterestRateModelInterface { function isInterestRateModel() external view returns (bool); /** * @dev Calculates the current borrow interest rate per block. * @param cash The total amount of cash the market has. * @param borrows The total amount of borrows the market has. * @param reserves The total amnount of reserves the market has. * @return The borrow rate per block (as a percentage, and scaled by 1e18). */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @dev Calculates the current supply interest rate per block. * @param cash The total amount of cash the market has. * @param borrows The total amount of borrows the market has. * @param reserves The total amnount of reserves the market has. * @param reserveRatio The current reserve factor the market has. * @return The supply rate per block (as a percentage, and scaled by 1e18). */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveRatio ) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IControllerAdminInterface { /// @notice Emitted when an admin supports a market event MarketAdded( address iToken, uint256 collateralFactor, uint256 borrowFactor, uint256 supplyCapacity, uint256 borrowCapacity, uint256 distributionFactor ); function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external; /// @notice Emitted when new price oracle is set event NewPriceOracle(address oldPriceOracle, address newPriceOracle); function _setPriceOracle(address newOracle) external; /// @notice Emitted when close factor is changed by admin event NewCloseFactor( uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa ); function _setCloseFactor(uint256 newCloseFactorMantissa) external; /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive( uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa ); function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external; /// @notice Emitted when iToken's collateral factor is changed by admin event NewCollateralFactor( address iToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa ); function _setCollateralFactor( address iToken, uint256 newCollateralFactorMantissa ) external; /// @notice Emitted when iToken's borrow factor is changed by admin event NewBorrowFactor( address iToken, uint256 oldBorrowFactorMantissa, uint256 newBorrowFactorMantissa ); function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa) external; /// @notice Emitted when iToken's borrow capacity is changed by admin event NewBorrowCapacity( address iToken, uint256 oldBorrowCapacity, uint256 newBorrowCapacity ); function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity) external; /// @notice Emitted when iToken's supply capacity is changed by admin event NewSupplyCapacity( address iToken, uint256 oldSupplyCapacity, uint256 newSupplyCapacity ); function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity) external; /// @notice Emitted when pause guardian is changed by admin event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); function _setPauseGuardian(address newPauseGuardian) external; /// @notice Emitted when mint is paused/unpaused by admin or pause guardian event MintPaused(address iToken, bool paused); function _setMintPaused(address iToken, bool paused) external; function _setAllMintPaused(bool paused) external; /// @notice Emitted when redeem is paused/unpaused by admin or pause guardian event RedeemPaused(address iToken, bool paused); function _setRedeemPaused(address iToken, bool paused) external; function _setAllRedeemPaused(bool paused) external; /// @notice Emitted when borrow is paused/unpaused by admin or pause guardian event BorrowPaused(address iToken, bool paused); function _setBorrowPaused(address iToken, bool paused) external; function _setAllBorrowPaused(bool paused) external; /// @notice Emitted when transfer is paused/unpaused by admin or pause guardian event TransferPaused(bool paused); function _setTransferPaused(bool paused) external; /// @notice Emitted when seize is paused/unpaused by admin or pause guardian event SeizePaused(bool paused); function _setSeizePaused(bool paused) external; function _setiTokenPaused(address iToken, bool paused) external; function _setProtocolPaused(bool paused) external; event NewRewardDistributor( address oldRewardDistributor, address _newRewardDistributor ); function _setRewardDistributor(address _newRewardDistributor) external; } interface IControllerPolicyInterface { function beforeMint( address iToken, address account, uint256 mintAmount ) external; function afterMint( address iToken, address minter, uint256 mintAmount, uint256 mintedAmount ) external; function beforeRedeem( address iToken, address redeemer, uint256 redeemAmount ) external; function afterRedeem( address iToken, address redeemer, uint256 redeemAmount, uint256 redeemedAmount ) external; function beforeBorrow( address iToken, address borrower, uint256 borrowAmount ) external; function afterBorrow( address iToken, address borrower, uint256 borrowedAmount ) external; function beforeRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function afterRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function beforeLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external; function afterLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repaidAmount, uint256 seizedAmount ) external; function beforeSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizeAmount ) external; function afterSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizedAmount ) external; function beforeTransfer( address iToken, address from, address to, uint256 amount ) external; function afterTransfer( address iToken, address from, address to, uint256 amount ) external; function beforeFlashloan( address iToken, address to, uint256 amount ) external; function afterFlashloan( address iToken, address to, uint256 amount ) external; } interface IControllerAccountEquityInterface { function calcAccountEquity(address account) external view returns ( uint256, uint256, uint256, uint256 ); function liquidateCalculateSeizeTokens( address iTokenBorrowed, address iTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256); } interface IControllerAccountInterface { function hasEnteredMarket(address account, address iToken) external view returns (bool); function getEnteredMarkets(address account) external view returns (address[] memory); /// @notice Emitted when an account enters a market event MarketEntered(address iToken, address account); function enterMarkets(address[] calldata iTokens) external returns (bool[] memory); function enterMarketFromiToken(address _account) external; /// @notice Emitted when an account exits a market event MarketExited(address iToken, address account); function exitMarkets(address[] calldata iTokens) external returns (bool[] memory); /// @notice Emitted when an account add a borrow asset event BorrowedAdded(address iToken, address account); /// @notice Emitted when an account remove a borrow asset event BorrowedRemoved(address iToken, address account); function hasBorrowed(address account, address iToken) external view returns (bool); function getBorrowedAssets(address account) external view returns (address[] memory); } interface IControllerInterface is IControllerAdminInterface, IControllerPolicyInterface, IControllerAccountEquityInterface, IControllerAccountInterface { /** * @notice Security checks when updating the comptroller of a market, always expect to return true. */ function isController() external view returns (bool); /** * @notice Return all of the iTokens * @return The list of iToken addresses */ function getAlliTokens() external view returns (address[] memory); /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRewardDistributor { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); function _setGlobalDistributionSpeeds( uint256 borrowSpeed, uint256 supplySpeed ) external; /// @notice Emitted when iToken's Distribution speed is updated event DistributionSpeedsUpdated( address iToken, uint256 borrowSpeed, uint256 supplySpeed ); function updateDistributionSpeed() external; /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function _setDistributionFactors( address[] calldata iToken, uint256[] calldata distributionFactors ) external; function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); }
* @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer @dev Admin function, only owner and pauseGuardian can call this @param _paused whether to pause or unpause/
function _setProtocolPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { address _iToken = _iTokens.at(i); _setiTokenPausedInternal(_iToken, _paused); } _setTransferPausedInternal(_paused); _setSeizePausedInternal(_paused); }
1,318,098
[ 1, 19476, 19, 318, 19476, 7278, 1771, 16, 6508, 312, 474, 19, 266, 24903, 19, 70, 15318, 19, 307, 554, 19, 13866, 225, 7807, 445, 16, 1338, 3410, 471, 11722, 16709, 2779, 848, 745, 333, 225, 389, 8774, 3668, 2856, 358, 11722, 578, 640, 19476, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 389, 542, 5752, 28590, 12, 6430, 389, 8774, 3668, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 866, 16507, 1355, 24899, 8774, 3668, 13, 203, 565, 288, 203, 3639, 6057, 25121, 694, 10784, 429, 18, 1887, 694, 2502, 389, 77, 5157, 273, 277, 5157, 31, 203, 3639, 2254, 5034, 389, 1897, 273, 389, 77, 5157, 18, 2469, 5621, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 1897, 31, 277, 27245, 288, 203, 5411, 1758, 389, 77, 1345, 273, 389, 77, 5157, 18, 270, 12, 77, 1769, 203, 203, 5411, 389, 542, 77, 1345, 28590, 3061, 24899, 77, 1345, 16, 389, 8774, 3668, 1769, 203, 3639, 289, 203, 203, 3639, 389, 542, 5912, 28590, 3061, 24899, 8774, 3668, 1769, 203, 3639, 389, 542, 1761, 554, 28590, 3061, 24899, 8774, 3668, 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 ]
/** *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); } }
* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { _setOwner(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), 'Ownable: caller is not the owner'); _; } function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } 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); } }
10,726,694
[ 1, 8924, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 2525, 805, 16, 326, 3410, 2236, 903, 506, 326, 1245, 716, 5993, 383, 1900, 326, 6835, 18, 1220, 848, 5137, 506, 3550, 598, 288, 13866, 5460, 12565, 5496, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 203, 3639, 1758, 8808, 2416, 5541, 16, 203, 3639, 1758, 8808, 394, 5541, 203, 565, 11272, 203, 203, 565, 3885, 1435, 288, 203, 3639, 389, 542, 5541, 24899, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 8443, 1435, 422, 389, 3576, 12021, 9334, 296, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8284, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 389, 542, 5541, 12, 2867, 12, 20, 10019, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 394, 5541, 480, 1758, 12, 20, 3631, 203, 5411, 296, 5460, 429, 30, 394, 3410, 353, 326, 3634, 1758, 11, 203, 3639, 11272, 203, 3639, 389, 542, 5541, 12, 2704, 5541, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 542, 5541, 12, 2867, 394, 5541, 13, 3238, 288, 203, 3639, 1758, 1592, 5541, 273, 389, 8443, 31, 203, 3639, 389, 8443, 273, 394, 5541, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 1673, 5541, 16, 394, 5541, 1769, 203, 565, 289, 203, 97, 203, 2 ]
./full_match/421613/0x8e1c56Cc0EC07182f1EbeC67F5c485feE82C4650/sources/project_/contracts/GarbiswapTradeGRBWETH.sol
tokenReserve/baseReserve = (tokenReserve+tokenInputAmount)/(baseReserve+baseInputAmount) => tokenReserve+tokenInputAmount = tokenReserve*(baseReserve+baseInputAmount)/baseReserve => tokenInputAmount = tokenReserve*(baseReserve+baseInputAmount)/baseReserve - tokenReserve; mintLP/totalLP = baseInputAmount/baseReserve mintLP = totalLP*baseInputAmount/baseReserve
function addLP(uint256 minLP, uint256 baseInputAmount, uint256 maxTokenInputAmount, uint256 deadline) public onlyWhitelist returns (uint256) { require(deadline >= block.timestamp, 'INVALID_DEADLINE'); require(minLP > 0, 'INVALID_MIN_LP'); require(baseInputAmount > 0, 'INVALID_BASE_INPUT'); require(maxTokenInputAmount > 0, 'INVALID_MAX_TOKEN_INPUT'); uint256 totalSupply = totalSupply(); if(totalSupply == 0) { base.transferFrom(msg.sender, address(this), baseInputAmount); token.transferFrom(msg.sender, address(this), maxTokenInputAmount); uint256 initLP = baseInputAmount; _mint(msg.sender, initLP); emit onAddLP(msg.sender, initLP, baseInputAmount, maxTokenInputAmount, base.balanceOf(address(this)), token.balanceOf(address(this))); return initLP; } else { uint256 baseReserve = 0; uint256 tokenReserve = 0; (baseReserve, tokenReserve) = getTotalReserve(); uint256 tokenInputAmount = tokenReserve.mul(baseReserve.add(baseInputAmount)).div(baseReserve).sub(tokenReserve); uint256 platformFeeOnBase = baseInputAmount.mul(PLATFORM_FEE).div(1000); uint256 platformFeeOnToken = tokenInputAmount.mul(PLATFORM_FEE).div(1000); uint256 mintLP = totalSupply.mul(baseInputAmount.sub(platformFeeOnBase)).div(baseReserve); require(tokenInputAmount > 0, 'INVALID_TOKEN_INPUT'); require(tokenInputAmount <= maxTokenInputAmount, 'INVALID_TOKEN_INPUT'); require(mintLP >= minLP, "INVALID_MINT_LP"); base.transferFrom(msg.sender, address(this), baseInputAmount); token.transferFrom(msg.sender, address(this), tokenInputAmount); base.transfer(platformFundAddress, platformFeeOnBase); token.transfer(platformFundAddress, platformFeeOnToken); _mint(msg.sender, mintLP); emit onAddLP(msg.sender, mintLP, baseInputAmount, tokenInputAmount, base.balanceOf(address(this)), token.balanceOf(address(this))); return mintLP; } }
11,583,583
[ 1, 2316, 607, 6527, 19, 1969, 607, 6527, 273, 261, 2316, 607, 6527, 15, 2316, 1210, 6275, 13176, 12, 1969, 607, 6527, 15, 1969, 1210, 6275, 13, 516, 1147, 607, 6527, 15, 2316, 1210, 6275, 273, 1147, 607, 6527, 12, 1969, 607, 6527, 15, 1969, 1210, 6275, 13176, 1969, 607, 6527, 516, 1147, 1210, 6275, 273, 1147, 607, 6527, 12, 1969, 607, 6527, 15, 1969, 1210, 6275, 13176, 1969, 607, 6527, 300, 1147, 607, 6527, 31, 312, 474, 14461, 19, 4963, 14461, 273, 225, 1026, 1210, 6275, 19, 1969, 607, 6527, 312, 474, 14461, 273, 2078, 14461, 1969, 1210, 6275, 19, 1969, 607, 6527, 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, 565, 445, 527, 14461, 12, 11890, 5034, 1131, 14461, 16, 2254, 5034, 1026, 1210, 6275, 16, 2254, 5034, 943, 1345, 1210, 6275, 16, 2254, 5034, 14096, 13, 1071, 1338, 18927, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 22097, 1369, 1545, 1203, 18, 5508, 16, 296, 9347, 67, 1639, 1880, 5997, 8284, 203, 3639, 2583, 12, 1154, 14461, 405, 374, 16, 296, 9347, 67, 6236, 67, 14461, 8284, 203, 3639, 2583, 12, 1969, 1210, 6275, 405, 374, 16, 296, 9347, 67, 8369, 67, 15934, 8284, 203, 3639, 2583, 12, 1896, 1345, 1210, 6275, 405, 374, 16, 296, 9347, 67, 6694, 67, 8412, 67, 15934, 8284, 203, 540, 203, 3639, 2254, 5034, 2078, 3088, 1283, 273, 2078, 3088, 1283, 5621, 203, 3639, 309, 12, 4963, 3088, 1283, 422, 374, 13, 288, 203, 5411, 1026, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 1026, 1210, 6275, 1769, 203, 5411, 1147, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 943, 1345, 1210, 6275, 1769, 203, 2398, 203, 5411, 2254, 5034, 1208, 14461, 273, 1026, 1210, 6275, 31, 203, 5411, 389, 81, 474, 12, 3576, 18, 15330, 16, 1208, 14461, 1769, 203, 5411, 3626, 603, 986, 14461, 12, 3576, 18, 15330, 16, 1208, 14461, 16, 1026, 1210, 6275, 16, 943, 1345, 1210, 6275, 16, 1026, 18, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 5411, 327, 1208, 14461, 31, 203, 3639, 289, 203, 3639, 469, 288, 7010, 2 ]
./partial_match/1/0x9a129032F01EB4dDD764c1777c81b771C34a2fbE/sources/contracts/ERC998TopDown.sol
* @notice NOT SUPPORTED Intended to transfer bottom-up composable child token from top-down composable to other ERC721 token./
function transferChildToParent( uint256, address, uint256, address, uint256, bytes memory ) external virtual override { revert("BOTTOM_UP_CHILD_NOT_SUPPORTED"); }
16,187,166
[ 1, 4400, 29556, 657, 8140, 358, 7412, 5469, 17, 416, 532, 23252, 1151, 1147, 628, 1760, 17, 2378, 532, 23252, 358, 1308, 4232, 39, 27, 5340, 1147, 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, 7412, 1763, 774, 3054, 12, 203, 3639, 2254, 5034, 16, 203, 3639, 1758, 16, 203, 3639, 2254, 5034, 16, 203, 3639, 1758, 16, 203, 3639, 2254, 5034, 16, 203, 3639, 1731, 3778, 203, 565, 262, 3903, 5024, 3849, 288, 203, 3639, 15226, 2932, 28891, 67, 3079, 67, 27043, 67, 4400, 67, 21134, 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 ]
./full_match/137/0x6857D601E199e7dC2Da276bc6E860124948B4F34/sources/project_/contracts/Pool.sol
sets the totalIncentiveAmount if available UPDATE - N1 Audit Report
address _incentiveToken = address(incentiveToken);
4,741,891
[ 1, 4424, 326, 2078, 382, 2998, 688, 6275, 309, 2319, 11028, 300, 423, 21, 12975, 8706, 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, 3639, 1758, 389, 267, 2998, 688, 1345, 273, 1758, 12, 267, 2998, 688, 1345, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.5; //solhint-disable-next-line import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./LegalEntityVerification.sol"; /** Features: -> Manufacturer mints a token representing the product. -> Hash of the serial number, zip code of the factory will be included in the Product struct. -> When the product is given to next entity, the transfer function will be called and the ownership will be transfered to the next owner. -> It should be possible to trace the output to its original manifacturer. Time |t=0 -> -> t=t ------------------------------------------------------- Owner|Factory -mints-> A1 -transfer-> A2 -transfer-> A3 //TODO: Redo this part. Origin of A3: Factory then. You can trace the transfers in the contract data. //TODO: Refactor that there may be several factories, add functions corresponding to that. */ /// @title Provenance tracking system for manifactured items using ERC721-tokens. /// @author Deniz Surmeli, Doğukan Türksoy /// @notice Use it only for simulation /// @dev Contract is a ERC721 implementation. contract Provenance is ERC721{ /// @notice The production process is serialized, thus we will use this /// field as a counter. uint256 public serialId = 0; /// @notice The deployer of the contract will be the factory. It's the only entity that can mint. address public factory; /// @notice Observe that we need to store the deployed address in order to call functions from it. address public legalEntityContractAddress; /// @notice For structured information. struct Product{ bytes32 _serialHash; //hash of the serial id. uint256 _manufacturerZipCode; //zip code of the manufacturer. In fact, this is a constant. } /// @notice Emits when tokens are transferred. event TokenTransferred(uint256 tokenId,address from,address to); /// @notice Emits when an owner approves the ownership. event TokenApproved(uint256 tokenId,address tokenOwner); event TokenMinted(uint256 tokenId); mapping(uint256=>Product) products; /// @notice We use this mapping to track the origins of the products. mapping(uint256=>address[]) owners; /// @notice We track that the token is in approval or not. mapping(uint256=>bool) approvalState; /// @notice Only addresses that have been approved by state authority can perform actions. /// @param _address address to be queried. modifier onlyVerifiedAddress(address _address){ LegalEntityVerification friendContract = LegalEntityVerification(legalEntityContractAddress); require(friendContract.isVerified(_address),"Only verified addresses can perform actions."); _; } /// @notice Only tokens that have been minted can perform actions. /// @param _tokenId id of the token. modifier onlyExistentToken(uint256 _tokenId){ require(ownerOf(_tokenId) != address(0),"Only minted tokens can be transferred."); _; } /// @notice Only tokens that in state of approval can perform actions /// @param _tokenId id of the token. modifier onlyNonApprovedToken(uint256 _tokenId){ require(approvalState[_tokenId] == true); _; } /// @notice Only authorized addresses can perform actions. /// @param _address address to be queried. modifier onlyAuthorized(address _address){ require(factory == _address,"Only authorized addreses can perform actions."); _; } /// @notice Only the owner of the token can perform actions. /// @param _tokenId ID of the token to be queried against. /// @param _address In query address. modifier onlyOwner(uint256 _tokenId,address _address){ require(ownerOf(_tokenId) == _address,"Only the owner of the token can perform actions."); _; } /// @notice Only approved tokens can be subject to actions. /// @param _tokenId ID of the token to be queried against. /// @param _address In query address. modifier onlyApprovedToken(uint256 _tokenId,address _address){ require(ownerOf(_tokenId) == _address,"Only the owner of the token can perform actions."); require(approvalState[_tokenId] == false,"You can only perform operations on approved tokens."); _; } /// @notice Constructor of the Provenance system. /// @param name_ name of the contract,factory name. /// @param symbol_ symbol of the contract,factory symbol. /// @param auxAddress Address of the helper contract, LegalEntityVerification. constructor(string memory name_,string memory symbol_,address auxAddress) ERC721(name_,symbol_) { factory = msg.sender; legalEntityContractAddress = auxAddress; } /// @notice Ownership approval function. Observe that we are going a bit offroad from ERC-721 Standard here. /// @param _tokenId Token that will be approved. function approveOwnership(uint256 _tokenId) onlyOwner(_tokenId,msg.sender) onlyNonApprovedToken(_tokenId) public{ owners[_tokenId].push(msg.sender); approvalState[_tokenId] = false; emit TokenApproved(_tokenId,msg.sender); } /// @notice Transfers the token with _tokenId from _from to _to. /// @param _from Address that is transfering. /// @param _to Address to be transfered. /// @param _tokenId ID of the token to be transfered. function transferToken(address _from,address _to, uint256 _tokenId) onlyOwner(_tokenId,_from) onlyApprovedToken(_tokenId,_from) onlyVerifiedAddress(_to) onlyExistentToken(_tokenId) public { require(_to != ownerOf(_tokenId)); _transfer(_from,_to,_tokenId); approvalState[_tokenId] = true; emit TokenTransferred(_tokenId,_from,_to); } /// @notice A manufacturer mints a product. Only authorized addreses can call. /// @dev First mint is directly to the factory. function mintProductToken(uint256 _zipCode) onlyAuthorized(msg.sender) public { //wrap the parameters in a clearer way for code readability. uint256 productId = serialId; uint256 manufacturerZipCode = _zipCode; _safeMint(msg.sender,productId); //mint the token, using the ERC721 implementation. Since the company is the minter,and only company members(see:onlyAuthorized) can call the mint, msg.sender is the first receiver automatically. // build product fields and map it to the corresponding address. products[productId] = Product({ _serialHash : keccak256(abi.encodePacked(productId)), _manufacturerZipCode: manufacturerZipCode }); approvalState[productId] = true; //auto-approve transfer for factory approveOwnership(productId); emit TokenMinted(serialId); // increment the id by one since it's serialized. serialId += 1; } /// @notice Fetch the origin address of the product. /// @param _tokenId Tokenized product data's id for indexing. /// @return address of the origin manufacturer. function getTheOriginAddress(uint256 _tokenId) public view returns(address){ return owners[_tokenId][0]; } /// @notice Gets the factory address.(for testing purposes) /// @return the factory address. function getFactoryAddress() public view returns(address){ return factory; } /// @notice Gets the approval state of the token /// @return the token id function getApprovalState(uint256 _tokenId) public view returns(bool){ return approvalState[_tokenId]; } /// @notice Returns the list of all owners for a token.(for testing purposes) /// @param _tokenId tokenId to be queried. /// @return an array of all owners. function getAllOwners(uint256 _tokenId) public view returns(address[] memory){ return owners[_tokenId]; } }
@notice Transfers the token with _tokenId from _from to _to. @param _from Address that is transfering. @param _to Address to be transfered. @param _tokenId ID of the token to be transfered.
function transferToken(address _from,address _to, uint256 _tokenId) onlyOwner(_tokenId,_from) onlyApprovedToken(_tokenId,_from) onlyVerifiedAddress(_to) onlyExistentToken(_tokenId) public { require(_to != ownerOf(_tokenId)); _transfer(_from,_to,_tokenId); approvalState[_tokenId] = true; emit TokenTransferred(_tokenId,_from,_to); }
12,700,973
[ 1, 1429, 18881, 326, 1147, 598, 389, 2316, 548, 628, 389, 2080, 358, 389, 869, 18, 225, 389, 2080, 5267, 716, 353, 7412, 310, 18, 225, 389, 869, 282, 5267, 358, 506, 7412, 329, 18, 225, 389, 2316, 548, 1599, 434, 326, 1147, 358, 506, 7412, 329, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7412, 1345, 12, 2867, 389, 2080, 16, 2867, 389, 869, 16, 2254, 5034, 389, 2316, 548, 13, 1338, 5541, 24899, 2316, 548, 16, 67, 2080, 13, 1338, 31639, 1345, 24899, 2316, 548, 16, 67, 2080, 13, 1338, 24369, 1887, 24899, 869, 13, 1338, 4786, 319, 1345, 24899, 2316, 548, 13, 225, 1071, 288, 203, 3639, 2583, 24899, 869, 480, 3410, 951, 24899, 2316, 548, 10019, 203, 3639, 389, 13866, 24899, 2080, 16, 67, 869, 16, 67, 2316, 548, 1769, 203, 3639, 23556, 1119, 63, 67, 2316, 548, 65, 273, 638, 31, 203, 3639, 3626, 3155, 1429, 4193, 24899, 2316, 548, 16, 67, 2080, 16, 67, 869, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "./ControllableV2.sol"; import "./ControllerStorage.sol"; import "../interface/IAnnouncer.sol"; /// @title Contract for holding scheduling for time-lock actions /// @dev Use with TetuProxy /// @author belbix contract Announcer is ControllableV2, IAnnouncer { /// @notice Version of the contract /// @dev Should be incremented when contract is changed string public constant VERSION = "1.2.0"; bytes32 internal constant _TIME_LOCK_SLOT = 0x244FE7C39AF244D294615908664E79A2F65DD3F4D5C387AF1D52197F465D1C2E; /// @dev Hold schedule for time-locked operations mapping(bytes32 => uint256) public override timeLockSchedule; /// @dev Hold values for upgrade TimeLockInfo[] private _timeLockInfos; /// @dev Hold indexes for upgrade info mapping(TimeLockOpCodes => uint256) public timeLockIndexes; /// @dev Hold indexes for upgrade info by address mapping(TimeLockOpCodes => mapping(address => uint256)) public multiTimeLockIndexes; /// @dev Deprecated, don't remove for keep slot ordering mapping(TimeLockOpCodes => bool) public multiOpCodes; /// @notice Address change was announced event AddressChangeAnnounce(TimeLockOpCodes opCode, address newAddress); /// @notice Uint256 change was announced event UintChangeAnnounce(TimeLockOpCodes opCode, uint256 newValue); /// @notice Ratio change was announced event RatioChangeAnnounced(TimeLockOpCodes opCode, uint256 numerator, uint256 denominator); /// @notice Token movement was announced event TokenMoveAnnounced(TimeLockOpCodes opCode, address target, address token, uint256 amount); /// @notice Proxy Upgrade was announced event ProxyUpgradeAnnounced(address _contract, address _implementation); /// @notice Mint was announced event MintAnnounced(uint256 totalAmount, address _distributor, address _otherNetworkFund); /// @notice Announce was closed event AnnounceClosed(bytes32 opHash); /// @notice Strategy Upgrade was announced event StrategyUpgradeAnnounced(address _contract, address _implementation); /// @notice Vault stop action announced event VaultStop(address _contract); constructor() { require(_TIME_LOCK_SLOT == bytes32(uint256(keccak256("eip1967.announcer.timeLock")) - 1), "wrong timeLock"); } /// @notice Initialize contract after setup it as proxy implementation /// @dev Use it only once after first logic setup /// @param _controller Controller address /// @param _timeLock TimeLock period function initialize(address _controller, uint256 _timeLock) external initializer { ControllableV2.initializeControllable(_controller); // fill timeLock bytes32 slot = _TIME_LOCK_SLOT; assembly { sstore(slot, _timeLock) } // placeholder for index 0 _timeLockInfos.push(TimeLockInfo(TimeLockOpCodes.ZeroPlaceholder, 0, address(0), new address[](0), new uint256[](0))); } /// @dev Operations allowed only for Governance address modifier onlyGovernance() { require(_isGovernance(msg.sender), "not governance"); _; } /// @dev Operations allowed for Governance or Dao addresses modifier onlyGovernanceOrDao() { require(_isGovernance(msg.sender) || IController(_controller()).isDao(msg.sender), "not governance or dao"); _; } /// @dev Operations allowed for Governance or Dao addresses modifier onlyControlMembers() { require( _isGovernance(msg.sender) || _isController(msg.sender) || IController(_controller()).isDao(msg.sender) || IController(_controller()).vaultController() == msg.sender , "not control member"); _; } // ************** VIEW ******************** /// @notice Return time-lock period (in seconds) saved in the contract slot /// @return result TimeLock period function timeLock() public view returns (uint256 result) { bytes32 slot = _TIME_LOCK_SLOT; assembly { result := sload(slot) } } /// @notice Length of the the array of all undone announced actions /// @return Array length function timeLockInfosLength() external view returns (uint256) { return _timeLockInfos.length; } /// @notice Return information about announced time-locks for given index /// @param idx Index of time lock info /// @return TimeLock information function timeLockInfo(uint256 idx) external override view returns (TimeLockInfo memory) { return _timeLockInfos[idx]; } // ************** ANNOUNCES ************** /// @notice Only Governance can do it. /// Announce address change. You will be able to setup new address after Time-lock period /// @param opCode Operation code from the list /// 0 - Governance /// 1 - Dao /// 2 - FeeRewardForwarder /// 3 - Bookkeeper /// 4 - MintHelper /// 5 - RewardToken /// 6 - FundToken /// 7 - PsVault /// 8 - Fund /// 19 - VaultController /// @param newAddress New address function announceAddressChange(TimeLockOpCodes opCode, address newAddress) external onlyGovernance { require(timeLockIndexes[opCode] == 0, "already announced"); require(newAddress != address(0), "zero address"); bytes32 opHash = keccak256(abi.encode(opCode, newAddress)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory values = new address[](1); values[0] = newAddress; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _controller(), values, new uint256[](0))); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit AddressChangeAnnounce(opCode, newAddress); } /// @notice Only Governance can do it. /// Announce some single uint256 change. You will be able to setup new value after Time-lock period /// @param opCode Operation code from the list /// 20 - RewardBoostDuration /// 21 - RewardRatioWithoutBoost /// @param newValue New value function announceUintChange(TimeLockOpCodes opCode, uint256 newValue) external onlyGovernance { require(timeLockIndexes[opCode] == 0, "already announced"); bytes32 opHash = keccak256(abi.encode(opCode, newValue)); timeLockSchedule[opHash] = block.timestamp + timeLock(); uint256[] memory values = new uint256[](1); values[0] = newValue; _timeLockInfos.push(TimeLockInfo(opCode, opHash, address(0), new address[](0), values)); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit UintChangeAnnounce(opCode, newValue); } /// @notice Only Governance or DAO can do it. /// Announce ratio change. You will be able to setup new ratio after Time-lock period /// @param opCode Operation code from the list /// 9 - PsRatio /// 10 - FundRatio /// @param numerator New numerator /// @param denominator New denominator function announceRatioChange(TimeLockOpCodes opCode, uint256 numerator, uint256 denominator) external override onlyGovernanceOrDao { require(timeLockIndexes[opCode] == 0, "already announced"); require(numerator <= denominator, "invalid values"); require(denominator != 0, "cannot divide by 0"); bytes32 opHash = keccak256(abi.encode(opCode, numerator, denominator)); timeLockSchedule[opHash] = block.timestamp + timeLock(); uint256[] memory values = new uint256[](2); values[0] = numerator; values[1] = denominator; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _controller(), new address[](0), values)); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit RatioChangeAnnounced(opCode, numerator, denominator); } /// @notice Only Governance can do it. Announce token movement. You will be able to transfer after Time-lock period /// @param opCode Operation code from the list /// 11 - ControllerTokenMove /// 12 - StrategyTokenMove /// 13 - FundTokenMove /// @param target Destination of the transfer /// @param token Token the user wants to move. /// @param amount Amount that you want to move function announceTokenMove(TimeLockOpCodes opCode, address target, address token, uint256 amount) external onlyGovernance { require(timeLockIndexes[opCode] == 0, "already announced"); require(target != address(0), "zero target"); require(token != address(0), "zero token"); require(amount != 0, "zero amount"); bytes32 opHash = keccak256(abi.encode(opCode, target, token, amount)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory adrValues = new address[](1); adrValues[0] = token; uint256[] memory intValues = new uint256[](1); intValues[0] = amount; _timeLockInfos.push(TimeLockInfo(opCode, opHash, target, adrValues, intValues)); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit TokenMoveAnnounced(opCode, target, token, amount); } /// @notice Only Governance can do it. Announce weekly mint. You will able to mint after Time-lock period /// @param totalAmount Total amount to mint. /// 33% will go to current network, 67% to FundKeeper for other networks /// @param _distributor Distributor address, usually NotifyHelper /// @param _otherNetworkFund Fund address, usually FundKeeper function announceMint( uint256 totalAmount, address _distributor, address _otherNetworkFund, bool mintAllAvailable ) external onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.Mint; require(timeLockIndexes[opCode] == 0, "already announced"); require(totalAmount != 0 || mintAllAvailable, "zero amount"); require(_distributor != address(0), "zero distributor"); require(_otherNetworkFund != address(0), "zero fund"); bytes32 opHash = keccak256(abi.encode(opCode, totalAmount, _distributor, _otherNetworkFund, mintAllAvailable)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory adrValues = new address[](2); adrValues[0] = _distributor; adrValues[1] = _otherNetworkFund; uint256[] memory intValues = new uint256[](1); intValues[0] = totalAmount; address mintHelper = IController(_controller()).mintHelper(); _timeLockInfos.push(TimeLockInfo(opCode, opHash, mintHelper, adrValues, intValues)); timeLockIndexes[opCode] = _timeLockInfos.length - 1; emit MintAnnounced(totalAmount, _distributor, _otherNetworkFund); } /// @notice Only Governance can do it. Announce Batch Proxy upgrade /// @param _contracts Array of Proxy contract addresses for upgrade /// @param _implementations Array of New implementation addresses function announceTetuProxyUpgradeBatch(address[] calldata _contracts, address[] calldata _implementations) external onlyGovernance { require(_contracts.length == _implementations.length, "wrong arrays"); for (uint256 i = 0; i < _contracts.length; i++) { announceTetuProxyUpgrade(_contracts[i], _implementations[i]); } } /// @notice Only Governance can do it. Announce Proxy upgrade. You will able to mint after Time-lock period /// @param _contract Proxy contract address for upgrade /// @param _implementation New implementation address function announceTetuProxyUpgrade(address _contract, address _implementation) public onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.TetuProxyUpdate; require(multiTimeLockIndexes[opCode][_contract] == 0, "already announced"); require(_contract != address(0), "zero contract"); require(_implementation != address(0), "zero implementation"); bytes32 opHash = keccak256(abi.encode(opCode, _contract, _implementation)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory values = new address[](1); values[0] = _implementation; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _contract, values, new uint256[](0))); multiTimeLockIndexes[opCode][_contract] = (_timeLockInfos.length - 1); emit ProxyUpgradeAnnounced(_contract, _implementation); } /// @notice Only Governance can do it. Announce strategy update for given vaults /// @param _targets Vault addresses /// @param _strategies Strategy addresses function announceStrategyUpgrades(address[] calldata _targets, address[] calldata _strategies) external onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.StrategyUpgrade; require(_targets.length == _strategies.length, "wrong arrays"); for (uint256 i = 0; i < _targets.length; i++) { require(multiTimeLockIndexes[opCode][_targets[i]] == 0, "already announced"); bytes32 opHash = keccak256(abi.encode(opCode, _targets[i], _strategies[i])); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory values = new address[](1); values[0] = _strategies[i]; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _targets[i], values, new uint256[](0))); multiTimeLockIndexes[opCode][_targets[i]] = (_timeLockInfos.length - 1); emit StrategyUpgradeAnnounced(_targets[i], _strategies[i]); } } /// @notice Only Governance can do it. Announce the stop vault action /// @param _vaults Vault addresses function announceVaultStopBatch(address[] calldata _vaults) external onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.VaultStop; for (uint256 i = 0; i < _vaults.length; i++) { require(multiTimeLockIndexes[opCode][_vaults[i]] == 0, "already announced"); bytes32 opHash = keccak256(abi.encode(opCode, _vaults[i])); timeLockSchedule[opHash] = block.timestamp + timeLock(); _timeLockInfos.push(TimeLockInfo(opCode, opHash, _vaults[i], new address[](0), new uint256[](0))); multiTimeLockIndexes[opCode][_vaults[i]] = (_timeLockInfos.length - 1); emit VaultStop(_vaults[i]); } } /// @notice Close any announce. Use in emergency case. /// @param opCode TimeLockOpCodes uint8 value /// @param opHash keccak256(abi.encode()) code with attributes. /// @param target Address for multi time lock. Set zero address if not required. function closeAnnounce(TimeLockOpCodes opCode, bytes32 opHash, address target) external onlyGovernance { clearAnnounce(opHash, opCode, target); emit AnnounceClosed(opHash); } /// @notice Only controller can use it. Clear announce after successful call time-locked function /// @param opHash Generated keccak256 opHash /// @param opCode TimeLockOpCodes uint8 value function clearAnnounce(bytes32 opHash, TimeLockOpCodes opCode, address target) public override onlyControlMembers { timeLockSchedule[opHash] = 0; if (multiTimeLockIndexes[opCode][target] != 0) { multiTimeLockIndexes[opCode][target] = 0; } else { timeLockIndexes[opCode] = 0; } } } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "../../openzeppelin/Initializable.sol"; import "../interface/IControllable.sol"; import "../interface/IControllableExtended.sol"; import "../interface/IController.sol"; /// @title Implement basic functionality for any contract that require strict control /// V2 is optimised version for less gas consumption /// @dev Can be used with upgradeable pattern. /// Require call initializeControllable() in any case. /// @author belbix abstract contract ControllableV2 is Initializable, IControllable, IControllableExtended { bytes32 internal constant _CONTROLLER_SLOT = bytes32(uint256(keccak256("eip1967.controllable.controller")) - 1); bytes32 internal constant _CREATED_SLOT = bytes32(uint256(keccak256("eip1967.controllable.created")) - 1); bytes32 internal constant _CREATED_BLOCK_SLOT = bytes32(uint256(keccak256("eip1967.controllable.created_block")) - 1); event ContractInitialized(address controller, uint ts, uint block); /// @notice Initialize contract after setup it as proxy implementation /// Save block.timestamp in the "created" variable /// @dev Use it only once after first logic setup /// @param __controller Controller address function initializeControllable(address __controller) public initializer { _setController(__controller); _setCreated(block.timestamp); _setCreatedBlock(block.number); emit ContractInitialized(__controller, block.timestamp, block.number); } /// @dev Return true if given address is controller function isController(address _value) external override view returns (bool) { return _isController(_value); } function _isController(address _value) internal view returns (bool) { return _value == _controller(); } /// @notice Return true if given address is setup as governance in Controller function isGovernance(address _value) external override view returns (bool) { return _isGovernance(_value); } function _isGovernance(address _value) internal view returns (bool) { return IController(_controller()).governance() == _value; } // ************* SETTERS/GETTERS ******************* /// @notice Return controller address saved in the contract slot function controller() external view override returns (address) { return _controller(); } function _controller() internal view returns (address result) { bytes32 slot = _CONTROLLER_SLOT; assembly { result := sload(slot) } } /// @dev Set a controller address to contract slot function _setController(address _newController) private { require(_newController != address(0)); bytes32 slot = _CONTROLLER_SLOT; assembly { sstore(slot, _newController) } } /// @notice Return creation timestamp /// @return ts Creation timestamp function created() external view override returns (uint256 ts) { bytes32 slot = _CREATED_SLOT; assembly { ts := sload(slot) } } /// @dev Filled only once when contract initialized /// @param _value block.timestamp function _setCreated(uint256 _value) private { bytes32 slot = _CREATED_SLOT; assembly { sstore(slot, _value) } } /// @notice Return creation block number /// @return ts Creation block number function createdBlock() external view returns (uint256 ts) { bytes32 slot = _CREATED_BLOCK_SLOT; assembly { ts := sload(slot) } } /// @dev Filled only once when contract initialized /// @param _value block.number function _setCreatedBlock(uint256 _value) private { bytes32 slot = _CREATED_BLOCK_SLOT; assembly { sstore(slot, _value) } } } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "../interface/IController.sol"; import "../../openzeppelin/Initializable.sol"; /// @title Eternal storage + getters and setters pattern /// @dev If a key value is changed it will be required to setup it again. /// @author belbix abstract contract ControllerStorage is Initializable, IController { // don't change names or ordering! mapping(bytes32 => uint256) private uintStorage; mapping(bytes32 => address) private addressStorage; /// @notice Address changed the variable with `name` event UpdatedAddressSlot(string indexed name, address oldValue, address newValue); /// @notice Value changed the variable with `name` event UpdatedUint256Slot(string indexed name, uint256 oldValue, uint256 newValue); /// @notice Initialize contract after setup it as proxy implementation /// @dev Use it only once after first logic setup /// @param __governance Governance address function initializeControllerStorage( address __governance ) public initializer { _setGovernance(__governance); } // ******************* SETTERS AND GETTERS ********************** // ----------- ADDRESSES ---------- function _setGovernance(address _address) internal { emit UpdatedAddressSlot("governance", _governance(), _address); setAddress("governance", _address); } /// @notice Return governance address /// @return Governance address function governance() external override view returns (address) { return _governance(); } function _governance() internal view returns (address) { return getAddress("governance"); } function _setDao(address _address) internal { emit UpdatedAddressSlot("dao", _dao(), _address); setAddress("dao", _address); } /// @notice Return DAO address /// @return DAO address function dao() external override view returns (address) { return _dao(); } function _dao() internal view returns (address) { return getAddress("dao"); } function _setFeeRewardForwarder(address _address) internal { emit UpdatedAddressSlot("feeRewardForwarder", feeRewardForwarder(), _address); setAddress("feeRewardForwarder", _address); } /// @notice Return FeeRewardForwarder address /// @return FeeRewardForwarder address function feeRewardForwarder() public override view returns (address) { return getAddress("feeRewardForwarder"); } function _setBookkeeper(address _address) internal { emit UpdatedAddressSlot("bookkeeper", _bookkeeper(), _address); setAddress("bookkeeper", _address); } /// @notice Return Bookkeeper address /// @return Bookkeeper address function bookkeeper() external override view returns (address) { return _bookkeeper(); } function _bookkeeper() internal view returns (address) { return getAddress("bookkeeper"); } function _setMintHelper(address _address) internal { emit UpdatedAddressSlot("mintHelper", mintHelper(), _address); setAddress("mintHelper", _address); } /// @notice Return MintHelper address /// @return MintHelper address function mintHelper() public override view returns (address) { return getAddress("mintHelper"); } function _setRewardToken(address _address) internal { emit UpdatedAddressSlot("rewardToken", rewardToken(), _address); setAddress("rewardToken", _address); } /// @notice Return TETU address /// @return TETU address function rewardToken() public override view returns (address) { return getAddress("rewardToken"); } function _setFundToken(address _address) internal { emit UpdatedAddressSlot("fundToken", fundToken(), _address); setAddress("fundToken", _address); } /// @notice Return a token address used for FundKeeper /// @return FundKeeper's main token address function fundToken() public override view returns (address) { return getAddress("fundToken"); } function _setPsVault(address _address) internal { emit UpdatedAddressSlot("psVault", psVault(), _address); setAddress("psVault", _address); } /// @notice Return Profit Sharing pool address /// @return Profit Sharing pool address function psVault() public override view returns (address) { return getAddress("psVault"); } function _setFund(address _address) internal { emit UpdatedAddressSlot("fund", fund(), _address); setAddress("fund", _address); } /// @notice Return FundKeeper address /// @return FundKeeper address function fund() public override view returns (address) { return getAddress("fund"); } function _setDistributor(address _address) internal { emit UpdatedAddressSlot("distributor", distributor(), _address); setAddress("distributor", _address); } /// @notice Return Reward distributor address /// @return Distributor address function distributor() public override view returns (address) { return getAddress("distributor"); } function _setAnnouncer(address _address) internal { emit UpdatedAddressSlot("announcer", _announcer(), _address); setAddress("announcer", _address); } /// @notice Return Announcer address /// @return Announcer address function announcer() external override view returns (address) { return _announcer(); } function _announcer() internal view returns (address) { return getAddress("announcer"); } function _setVaultController(address _address) internal { emit UpdatedAddressSlot("vaultController", vaultController(), _address); setAddress("vaultController", _address); } /// @notice Return FundKeeper address /// @return FundKeeper address function vaultController() public override view returns (address) { return getAddress("vaultController"); } // ----------- INTEGERS ---------- function _setPsNumerator(uint256 _value) internal { emit UpdatedUint256Slot("psNumerator", psNumerator(), _value); setUint256("psNumerator", _value); } /// @notice Return Profit Sharing pool ratio's numerator /// @return Profit Sharing pool ratio numerator function psNumerator() public view override returns (uint256) { return getUint256("psNumerator"); } function _setPsDenominator(uint256 _value) internal { emit UpdatedUint256Slot("psDenominator", psDenominator(), _value); setUint256("psDenominator", _value); } /// @notice Return Profit Sharing pool ratio's denominator /// @return Profit Sharing pool ratio denominator function psDenominator() public view override returns (uint256) { return getUint256("psDenominator"); } function _setFundNumerator(uint256 _value) internal { emit UpdatedUint256Slot("fundNumerator", fundNumerator(), _value); setUint256("fundNumerator", _value); } /// @notice Return FundKeeper ratio's numerator /// @return FundKeeper ratio numerator function fundNumerator() public view override returns (uint256) { return getUint256("fundNumerator"); } function _setFundDenominator(uint256 _value) internal { emit UpdatedUint256Slot("fundDenominator", fundDenominator(), _value); setUint256("fundDenominator", _value); } /// @notice Return FundKeeper ratio's denominator /// @return FundKeeper ratio denominator function fundDenominator() public view override returns (uint256) { return getUint256("fundDenominator"); } // ******************** STORAGE INTERNAL FUNCTIONS ******************** function setAddress(string memory key, address _address) private { addressStorage[keccak256(abi.encodePacked(key))] = _address; } function getAddress(string memory key) private view returns (address) { return addressStorage[keccak256(abi.encodePacked(key))]; } function setUint256(string memory key, uint256 _value) private { uintStorage[keccak256(abi.encodePacked(key))] = _value; } function getUint256(string memory key) private view returns (uint256) { return uintStorage[keccak256(abi.encodePacked(key))]; } //slither-disable-next-line unused-state uint256[50] private ______gap; } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IAnnouncer { /// @dev Time lock operation codes enum TimeLockOpCodes { // TimeLockedAddresses Governance, // 0 Dao, // 1 FeeRewardForwarder, // 2 Bookkeeper, // 3 MintHelper, // 4 RewardToken, // 5 FundToken, // 6 PsVault, // 7 Fund, // 8 // TimeLockedRatios PsRatio, // 9 FundRatio, // 10 // TimeLockedTokenMoves ControllerTokenMove, // 11 StrategyTokenMove, // 12 FundTokenMove, // 13 // Other TetuProxyUpdate, // 14 StrategyUpgrade, // 15 Mint, // 16 Announcer, // 17 ZeroPlaceholder, //18 VaultController, //19 RewardBoostDuration, //20 RewardRatioWithoutBoost, //21 VaultStop //22 } /// @dev Holder for human readable info struct TimeLockInfo { TimeLockOpCodes opCode; bytes32 opHash; address target; address[] adrValues; uint256[] numValues; } function clearAnnounce(bytes32 opHash, TimeLockOpCodes opCode, address target) external; function timeLockSchedule(bytes32 opHash) external returns (uint256); function timeLockInfo(uint256 idx) external returns (TimeLockInfo memory); // ************ DAO ACTIONS ************* function announceRatioChange(TimeLockOpCodes opCode, uint256 numerator, uint256 denominator) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IControllable { function isController(address _contract) external view returns (bool); function isGovernance(address _contract) external view returns (bool); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; /// @dev This interface contains additional functions for Controllable class /// Don't extend the exist Controllable for the reason of huge coherence interface IControllableExtended { function created() external view returns (uint256 ts); function controller() external view returns (address adr); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IController { function addVaultsAndStrategies(address[] memory _vaults, address[] memory _strategies) external; function addStrategy(address _strategy) external; function governance() external view returns (address); function dao() external view returns (address); function bookkeeper() external view returns (address); function feeRewardForwarder() external view returns (address); function mintHelper() external view returns (address); function rewardToken() external view returns (address); function fundToken() external view returns (address); function psVault() external view returns (address); function fund() external view returns (address); function distributor() external view returns (address); function announcer() external view returns (address); function vaultController() external view returns (address); function whiteList(address _target) external view returns (bool); function vaults(address _target) external view returns (bool); function strategies(address _target) external view returns (bool); function psNumerator() external view returns (uint256); function psDenominator() external view returns (uint256); function fundNumerator() external view returns (uint256); function fundDenominator() external view returns (uint256); function isAllowedUser(address _adr) external view returns (bool); function isDao(address _adr) external view returns (bool); function isHardWorker(address _adr) external view returns (bool); function isRewardDistributor(address _adr) external view returns (bool); function isPoorRewardConsumer(address _adr) external view returns (bool); function isValidVault(address _vault) external view returns (bool); function isValidStrategy(address _strategy) external view returns (bool); function rebalance(address _strategy) external; // ************ DAO ACTIONS ************* function setPSNumeratorDenominator(uint256 numerator, uint256 denominator) external; function setFundNumeratorDenominator(uint256 numerator, uint256 denominator) external; function changeWhiteListStatus(address[] calldata _targets, bool status) external; }
@notice Initialize contract after setup it as proxy implementation @dev Use it only once after first logic setup @param _controller Controller address @param _timeLock TimeLock period fill timeLock
function initialize(address _controller, uint256 _timeLock) external initializer { ControllableV2.initializeControllable(_controller); bytes32 slot = _TIME_LOCK_SLOT; assembly { sstore(slot, _timeLock) } }
14,610,354
[ 1, 7520, 6835, 1839, 3875, 518, 487, 2889, 4471, 225, 2672, 518, 1338, 3647, 1839, 1122, 4058, 3875, 225, 389, 5723, 6629, 1758, 225, 389, 957, 2531, 2647, 2531, 3879, 3636, 813, 2531, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 4046, 12, 2867, 389, 5723, 16, 2254, 5034, 389, 957, 2531, 13, 3903, 12562, 288, 203, 565, 1816, 30453, 58, 22, 18, 11160, 660, 30453, 24899, 5723, 1769, 203, 203, 565, 1731, 1578, 4694, 273, 389, 4684, 67, 6589, 67, 55, 1502, 56, 31, 203, 565, 19931, 288, 203, 1377, 272, 2233, 12, 14194, 16, 389, 957, 2531, 13, 203, 565, 289, 203, 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 ]
./partial_match/1/0x38F9BC6E04F85cB1a6B2EEa40Cf4E17453C18eEc/sources/A.sol
exclude from paying fees or having max transaction amount
constructor() ERC20(unicode"🅰️", unicode"🅰️") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 25; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 25; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
4,221,769
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 12, 9124, 6, 177, 258, 232, 113, 176, 121, 242, 3113, 5252, 6, 177, 258, 232, 113, 176, 121, 242, 7923, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 203, 5411, 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, 203, 3639, 11272, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 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, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 6969, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {ERC721Full} from "../../.openzeppelin/0.8/token/ERC721/ERC721Full.sol"; import {Counters} from "../../.openzeppelin/0.8/drafts/Counters.sol"; import {IERC721} from "../../.openzeppelin/0.8/token/ERC721/IERC721.sol"; import {Address} from "../../.openzeppelin/0.8/utils/Address.sol"; import {Bytes32} from "../../lib/Bytes32.sol"; import {Adminable} from "../../lib/Adminable.sol"; import {Initializable} from "../../lib/Initializable.sol"; import {DefiPassportStorage} from "./DefiPassportStorage.sol"; import {ISapphirePassportScores} from "../../sapphire/ISapphirePassportScores.sol"; import {SapphireTypes} from "../../sapphire/SapphireTypes.sol"; contract DefiPassport is ERC721Full, Adminable, DefiPassportStorage, Initializable { /* ========== Libraries ========== */ using Counters for Counters.Counter; using Address for address; using Bytes32 for bytes32; /* ========== Events ========== */ event BaseURISet(string _baseURI); event ApprovedSkinStatusChanged( address _skin, uint256 _skinTokenId, bool _status ); event ApprovedSkinsStatusesChanged( SkinAndTokenIdStatusRecord[] _skinsRecords ); event DefaultSkinStatusChanged( address _skin, bool _status ); event DefaultActiveSkinChanged( address _skin, uint256 _skinTokenId ); event ActiveSkinSet( uint256 _tokenId, SkinRecord _skinRecord ); event SkinManagerSet(address _skinManager); event WhitelistSkinSet(address _skin, bool _status); /* ========== Public variables ========== */ string public override baseURI; /** * @dev Deprecated. Including this because this is a proxy implementation. */ bytes32 private _proofProtocol; /* ========== Modifier ========== */ modifier onlySkinManager () { require( msg.sender == skinManager, "DefiPassport: caller is not skin manager" ); _; } /* ========== Restricted Functions ========== */ function init( string calldata name_, string calldata symbol_, address _skinManager ) external onlyAdmin initializer { _name = name_; _symbol = symbol_; skinManager = _skinManager; } /** * @dev Sets the base URI that is appended as a prefix to the * token URI. */ function setBaseURI( string calldata _baseURI ) external onlyAdmin { baseURI = _baseURI; emit BaseURISet(_baseURI); } /** * @dev Sets the address of the skin manager role * * @param _skinManager The new skin manager */ function setSkinManager( address _skinManager ) external onlyAdmin { require ( _skinManager != skinManager, "DefiPassport: the same skin manager is already set" ); skinManager = _skinManager; emit SkinManagerSet(skinManager); } /** * @notice Registers/unregisters a default skin * * @param _skin Address of the skin NFT * @param _status Wether or not it should be considered as a default * skin or not */ function setDefaultSkin( address _skin, bool _status ) external onlySkinManager { if (!_status) { require( defaultActiveSkin.skin != _skin, "Defi Passport: cannot unregister the default active skin" ); } require( defaultSkins[_skin] != _status, "DefiPassport: skin already has the same status" ); require( _skin.isContract(), "DefiPassport: the given skin is not a contract" ); require ( IERC721(_skin).ownerOf(1) != address(0), "DefiPassport: default skin must at least have tokenId eq 1" ); if (defaultActiveSkin.skin == address(0)) { defaultActiveSkin = SkinRecord(address(0), _skin, 1); } defaultSkins[_skin] = _status; emit DefaultSkinStatusChanged(_skin, _status); } /** * @dev Set the default active skin, which will be used instead of * unavailable user's active one * @notice Skin should be used as default one (with setDefaultSkin function) * * @param _skin Address of the skin NFT * @param _skinTokenId The NFT token ID */ function setDefaultActiveSkin( address _skin, uint256 _skinTokenId ) external onlySkinManager { require( defaultSkins[_skin], "DefiPassport: the given skin is not registered as a default" ); require( defaultActiveSkin.skin != _skin || defaultActiveSkin.skinTokenId != _skinTokenId, "DefiPassport: the skin is already set as default active" ); defaultActiveSkin = SkinRecord(address(0), _skin, _skinTokenId); emit DefaultActiveSkinChanged(_skin, _skinTokenId); } /** * @notice Approves a passport skin. * Only callable by the skin manager */ function setApprovedSkin( address _skin, uint256 _skinTokenId, bool _status ) external onlySkinManager { approvedSkins[_skin][_skinTokenId] = _status; emit ApprovedSkinStatusChanged(_skin, _skinTokenId, _status); } /** * @notice Sets the approved status for all skin contracts and their * token IDs passed into this function. */ function setApprovedSkins( SkinAndTokenIdStatusRecord[] memory _skinsToApprove ) public onlySkinManager { for (uint256 i = 0; i < _skinsToApprove.length; i++) { TokenIdStatus[] memory tokensAndStatuses = _skinsToApprove[i].skinTokenIdStatuses; for (uint256 j = 0; j < tokensAndStatuses.length; j ++) { TokenIdStatus memory tokenStatusPair = tokensAndStatuses[j]; approvedSkins[_skinsToApprove[i].skin][tokenStatusPair.tokenId] = tokenStatusPair.status; } } emit ApprovedSkinsStatusesChanged(_skinsToApprove); } /** * @notice Adds or removes a skin contract to the whitelist. * The Defi Passport considers all skins minted by whitelisted contracts * to be valid skins for applying them on to the passport. * The user applying the skins must still be their owner though. */ function setWhitelistedSkin( address _skinContract, bool _status ) external onlySkinManager { require ( _skinContract.isContract(), "DefiPassport: address is not a contract" ); require ( whitelistedSkins[_skinContract] != _status, "DefiPassport: the skin already has the same whitelist status" ); whitelistedSkins[_skinContract] = _status; emit WhitelistSkinSet(_skinContract, _status); } /* ========== Public Functions ========== */ /** * @notice Mints a DeFi passport to the address specified by `_to`. Note: * - The `_passportSkin` must be an approved or default skin. * - The token URI will be composed by <baseURI> + `_to`, * without the "0x" in front * * @param _to The receiver of the defi passport * @param _passportSkin The address of the skin NFT to be applied to the passport * @param _skinTokenId The ID of the passport skin NFT, owned by the receiver */ function mint( address _to, address _passportSkin, uint256 _skinTokenId ) external returns (uint256) { require ( isSkinAvailable(_to, _passportSkin, _skinTokenId), "DefiPassport: invalid skin" ); // A user cannot have two passports require( balanceOf(_to) == 0, "DefiPassport: user already has a defi passport" ); _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _mint(_to, newTokenId); _setActiveSkin(newTokenId, SkinRecord(_to, _passportSkin, _skinTokenId)); return newTokenId; } /** * @notice Changes the passport skin of the caller's passport * * @param _skin The contract address to the skin NFT * @param _skinTokenId The ID of the skin NFT */ function setActiveSkin( address _skin, uint256 _skinTokenId ) external { require( balanceOf(msg.sender) > 0, "DefiPassport: caller has no passport" ); require( isSkinAvailable(msg.sender, _skin, _skinTokenId), "DefiPassport: invalid skin" ); uint256 tokenId = tokenOfOwnerByIndex(msg.sender, 0); _setActiveSkin(tokenId, SkinRecord(msg.sender, _skin, _skinTokenId)); } function approve( address, uint256 ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function setApprovalForAll( address, bool ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function safeTransferFrom( address, address, uint256 ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function safeTransferFrom( address, address, uint256, bytes memory ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function transferFrom( address, address, uint256 ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } /* ========== Public View Functions ========== */ function name() external override view returns (string memory) { return _name; } function symbol() external override view returns (string memory) { return _symbol; } /** * @notice Returns whether a certain skin can be applied to the specified * user's passport. * * @param _user The user for whom to check * @param _skinContract The address of the skin NFT * @param _skinTokenId The NFT token ID */ function isSkinAvailable( address _user, address _skinContract, uint256 _skinTokenId ) public view returns (bool) { if (defaultSkins[_skinContract]) { return IERC721(_skinContract).ownerOf(_skinTokenId) != address(0); } else if ( whitelistedSkins[_skinContract] || approvedSkins[_skinContract][_skinTokenId] ) { return _isSkinOwner(_user, _skinContract, _skinTokenId); } return false; } /** * @notice Returns the active skin of the given passport ID * * @param _tokenId Passport ID */ function getActiveSkin( uint256 _tokenId ) public view returns (SkinRecord memory) { SkinRecord memory _activeSkin = _activeSkins[_tokenId]; if (isSkinAvailable(_activeSkin.owner, _activeSkin.skin, _activeSkin.skinTokenId)) { return _activeSkin; } else { return defaultActiveSkin; } } /** * @dev Returns the URI for a given token ID. May return an empty string. * * Reverts if the token ID does not exist. */ function tokenURI( uint256 tokenId ) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); address owner = ownerOf(tokenId); return string(abi.encodePacked(baseURI, "0x", _toAsciiString(owner))); } /* ========== Private Functions ========== */ /** * @dev Converts the given address to string. Used when minting new * passports. */ function _toAsciiString( address _address ) private pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(_address)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = _char(hi); s[2*i+1] = _char(lo); } return string(s); } function _char( bytes1 b ) private pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } /** * @dev Ensures that the user is the owner of the skin NFT */ function _isSkinOwner( address _user, address _skin, uint256 _tokenId ) internal view returns (bool) { /** * It is not sure if the skin contract implements the ERC721 or ERC1155 standard, * so we must do the check. */ bytes memory payload = abi.encodeWithSignature("ownerOf(uint256)", _tokenId); (bool success, bytes memory returnData) = _skin.staticcall(payload); if (success) { (address owner) = abi.decode(returnData, (address)); return owner == _user; } else { // The skin contract might be an ERC1155 (like OpenSea) payload = abi.encodeWithSignature("balanceOf(address,uint256)", _user, _tokenId); (success, returnData) = _skin.staticcall(payload); if (success) { (uint256 balance) = abi.decode(returnData, (uint256)); return balance > 0; } } return false; } function _setActiveSkin( uint256 _tokenId, SkinRecord memory _skinRecord ) private { SkinRecord memory currentSkin = _activeSkins[_tokenId]; require( currentSkin.skin != _skinRecord.skin || currentSkin.skinTokenId != _skinRecord.skinTokenId, "DefiPassport: the same skin is already active" ); _activeSkins[_tokenId] = _skinRecord; emit ActiveSkinSet(_tokenId, _skinRecord); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721.sol"; import "./ERC721Enumerable.sol"; import "./ERC721Metadata.sol"; /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { function _transferFrom( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { ERC721Enumerable._transferFrom(from, to, tokenId); } function _mint( address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { ERC721Enumerable._mint(to, tokenId); } function _burn( address owner, uint256 tokenId ) internal override(ERC721, ERC721Enumerable, ERC721Metadata) { // Burn implementation of Metadata ERC721._burn(owner, tokenId); ERC721Metadata._burn(owner, tokenId); ERC721Enumerable._burn(owner, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) external; } // 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) { // 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]. * * _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-low-level-calls (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; library Bytes32 { function toString( bytes32 _bytes ) internal pure returns (string memory) { uint8 i = 0; while (i < 32 && _bytes[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes[i] != 0; i++) { bytesArray[i] = _bytes[i]; } return string(bytesArray); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import { Storage } from "./Storage.sol"; /** * @title Adminable * @author dYdX * * @dev EIP-1967 Proxy Admin contract. */ contract Adminable { /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will revert. */ modifier onlyAdmin() { require( msg.sender == getAdmin(), "Adminable: caller is not admin" ); _; } /** * @return The EIP-1967 proxy admin */ function getAdmin() public view returns (address) { return address(uint160(uint256(Storage.load(ADMIN_SLOT)))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * Taken from OpenZeppelin */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {Counters} from "../../.openzeppelin/0.8/drafts/Counters.sol"; import {ISapphirePassportScores} from "../../sapphire/ISapphirePassportScores.sol"; contract DefiPassportStorage { /* ========== Structs ========== */ struct SkinRecord { address owner; address skin; uint256 skinTokenId; } struct TokenIdStatus { uint256 tokenId; bool status; } struct SkinAndTokenIdStatusRecord { address skin; TokenIdStatus[] skinTokenIdStatuses; } // Made these internal because the getters override these variables (because this is an upgrade) string internal _name; string internal _symbol; /** * @notice The credit score contract used by the passport */ ISapphirePassportScores private passportScoresContract; /* ========== Public Variables ========== */ /** * @notice Records the whitelisted skins. All tokens minted by these contracts * will be considered valid to apply on the passport, given they are * owned by the caller. */ mapping (address => bool) public whitelistedSkins; /** * @notice Records the approved skins of the passport */ mapping (address => mapping (uint256 => bool)) public approvedSkins; /** * @notice Records the default skins */ mapping (address => bool) public defaultSkins; /** * @notice Records the default skins */ SkinRecord public defaultActiveSkin; /** * @notice The skin manager appointed by the admin, who can * approve and revoke passport skins */ address public skinManager; /* ========== Internal Variables ========== */ /** * @notice Maps a passport (tokenId) to its active skin NFT */ mapping (uint256 => SkinRecord) internal _activeSkins; Counters.Counter internal _tokenIds; } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {SapphireTypes} from "./SapphireTypes.sol"; interface ISapphirePassportScores { function updateMerkleRoot(bytes32 newRoot) external; function setMerkleRootUpdater(address merkleRootUpdater) external; /** * Reverts if proof is invalid */ function verify(SapphireTypes.ScoreProof calldata proof) external view returns(bool); function setMerkleRootDelay(uint256 delay) external; function setPause(bool status) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; library SapphireTypes { struct ScoreProof { address account; bytes32 protocol; uint256 score; bytes32[] merkleProof; } struct Vault { uint256 collateralAmount; uint256 borrowedAmount; } struct RootInfo { bytes32 merkleRoot; uint256 timestamp; } enum Operation { Deposit, Withdraw, Borrow, Repay, Liquidate } struct Action { uint256 amount; Operation operation; address userToLiquidate; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../GSN/Context.sol"; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../drafts/Counters.sol"; import "../../introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public override view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public override view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public override virtual { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public override view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public override virtual { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public override view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public override virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public override virtual { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override virtual { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, 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. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @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) internal returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../GSN/Context.sol"; import "./IERC721Enumerable.sol"; import "./ERC721.sol"; import "../../introspection/ERC165.sol"; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public override view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public override view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public override view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal override virtual { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal override virtual { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal override virtual { _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @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 = _ownedTokens[from].length - 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 _ownedTokens[from].pop(); // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @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 _allTokens.pop(); _allTokensIndex[tokenId] = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../GSN/Context.sol"; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "../../introspection/ERC165.sol"; contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Gets the token name. * @return string representing the token name */ function name() external override virtual view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external override virtual view returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */ function tokenURI(uint256 tokenId) external override virtual view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _tokenURI)); } } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: if all token IDs share a prefix (e.g. if your URIs look like * `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}. * * _Available since v2.5.0._ */ function _setBaseURI(string memory baseURI_) internal { _baseURI = baseURI_; } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a preffix in {tokenURI} to each token's URI, when * they are non-empty. * * _Available since v2.5.0._ */ function baseURI() external virtual view returns (string memory) { return _baseURI; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address, uint256 tokenId) internal override virtual { // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // 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 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; } } // 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 { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) external returns (bytes4); } // 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 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external override view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library Storage { /** * @dev Performs an SLOAD and returns the data in the slot. */ function load( bytes32 slot ) internal view returns (bytes32) { bytes32 result; /* solhint-disable-next-line no-inline-assembly */ assembly { result := sload(slot) } return result; } /** * @dev Performs an SSTORE to save the value to the slot. */ function store( bytes32 slot, bytes32 value ) internal { /* solhint-disable-next-line no-inline-assembly */ assembly { sstore(slot, value) } } }
Burn implementation of Metadata
function _burn( address owner, uint256 tokenId ) internal override(ERC721, ERC721Enumerable, ERC721Metadata) { ERC721._burn(owner, tokenId); ERC721Metadata._burn(owner, tokenId); ERC721Enumerable._burn(owner, tokenId); }
11,896,573
[ 1, 38, 321, 4471, 434, 6912, 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, 389, 70, 321, 12, 203, 3639, 1758, 3410, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 203, 3639, 2713, 203, 3639, 3849, 12, 654, 39, 27, 5340, 16, 4232, 39, 27, 5340, 3572, 25121, 16, 4232, 39, 27, 5340, 2277, 13, 203, 565, 288, 203, 3639, 4232, 39, 27, 5340, 6315, 70, 321, 12, 8443, 16, 1147, 548, 1769, 203, 3639, 4232, 39, 27, 5340, 2277, 6315, 70, 321, 12, 8443, 16, 1147, 548, 1769, 203, 3639, 4232, 39, 27, 5340, 3572, 25121, 6315, 70, 321, 12, 8443, 16, 1147, 548, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, 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; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } //Abstract contract for Calling ERC20 contract contract AbstractCon { function allowance(address _owner, address _spender) public pure returns (uint256 remaining); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function decimals() public returns (uint8); //function approve(address _spender, uint256 _value) public returns (bool); //test //function transfer(address _to, uint256 _value) public returns (bool); //test } //... contract EXOTokenSale is Ownable { using SafeMath for uint256; string public constant name = "EXO_TOKEN_SALE"; /////////////////////// // DATA STRUCTURES /// /////////////////////// enum StageName {Pause, PreSale, Sale, Ended, Refund} struct StageProperties { uint256 planEndDate; address tokenKeeper; } StageName public currentStage; mapping(uint8 => StageProperties) public campaignStages; mapping(address => uint256) public deposited; uint256 public weiRaised=0; //All raised ether uint256 public token_rate=1600; // decimal part of token per wei (0.3$ if 480$==1ETH) uint256 public minimum_token_sell=1000; // !!! token count - without decimals!!! uint256 public softCap=1042*10**18;// 500 000$ if 480$==1ETH uint256 public hardCap=52083*10**18;//25 000 000$ if 480$==1ETH address public wallet ; address public ERC20address; /////////////////////// /// EVENTS /////// ////////////////////// event Income(address from, uint256 amount, uint64 timestamp); event NewTokenRate(uint256 rate); event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 weivalue, uint256 tokens); event FundsWithdraw(address indexed who, uint256 amount , uint64 timestamp); event Refunded(address investor, uint256 depositedValue); //20180501 = 1525132800 //20180901 = 1535760000 //20181231 = 1546214400 function EXOTokenSale(address _wallet, address _preSaleTokenKeeper , address _SaleTokenKeeper) public { //costructor require(_wallet != address(0)); wallet = _wallet; campaignStages[uint8(StageName.PreSale)] = StageProperties(1525132800, _preSaleTokenKeeper); campaignStages[uint8(StageName.Sale)] = StageProperties(1535760000, _SaleTokenKeeper); currentStage = StageName.Pause; } //For disable transfers from incompatible wallet (Coinbase) // or from a non ERC-20 compatible wallet //it may be purposefully comment this fallback function and recieve // Ether direct through exchangeEtherOnTokens() function() public payable { exchangeEtherOnTokens(msg.sender); } // low level token purchase function function exchangeEtherOnTokens(address beneficiary) public payable { emit Income(msg.sender, msg.value, uint64(now)); require(currentStage == StageName.PreSale || currentStage == StageName.Sale); uint256 weiAmount = msg.value; //local uint256 tokens = getTokenAmount(weiAmount); require(beneficiary != address(0)); require(token_rate > 0);//implicit enabling sell AbstractCon ac = AbstractCon(ERC20address); require(tokens >= minimum_token_sell.mul(10 ** uint256(ac.decimals()))); require(ac.transferFrom(campaignStages[uint8(currentStage)].tokenKeeper, beneficiary, tokens)); checkCurrentStage(); weiRaised = weiRaised.add(weiAmount); deposited[beneficiary] = deposited[beneficiary].add(weiAmount); emit TokenPurchase(msg.sender, beneficiary, msg.value, tokens); if (weiRaised >= softCap) withdrawETH(); } //Stage time and conditions control function checkCurrentStage() internal { if (campaignStages[uint8(currentStage)].planEndDate <= now) { // Allow refund if softCap is not reached during PreSale stage if (currentStage == StageName.PreSale && (weiRaised + msg.value) < softCap ) { currentStage = StageName.Refund; return; } currentStage = StageName.Pause; } //Finish tokensale campaign when hardCap will reached if (currentStage == StageName.Sale && (weiRaised + msg.value) >= hardCap ) { currentStage = StageName.Ended; } } //for all discount logic function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { return weiAmount.mul(token_rate); } function withdrawETH() internal { emit FundsWithdraw(wallet, this.balance, uint64(now)); wallet.transfer(this.balance);// or weiAmount } //Set current stage of campaign manually function setCurrentStage(StageName _name) external onlyOwner { currentStage = _name; } //Manually stages control function setStageProperties( StageName _name, uint256 _planEndDate, address _tokenKeeper ) external onlyOwner { campaignStages[uint8(_name)] = StageProperties(_planEndDate, _tokenKeeper); } //set erc20 address for token process with check of allowance function setERC20address(address newERC20contract) external onlyOwner { require(address(newERC20contract) != 0); AbstractCon ac = AbstractCon(newERC20contract); require(ac.allowance(campaignStages[uint8(currentStage)].tokenKeeper, address(this))>0); ERC20address = newERC20contract; } //refund if not softCapped function refund(address investor) external { require(currentStage == StageName.Refund); require(investor != address(0)); assert(msg.data.length >= 32 + 4); //Short Address Attack uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } function setTokenRate(uint256 newRate) external onlyOwner { token_rate = newRate; emit NewTokenRate(newRate); } function setSoftCap(uint256 _val) external onlyOwner { softCap = _val; } function setHardCap(uint256 _val) external onlyOwner { hardCap = _val; } function setMinimumTokenSell(uint256 newNumber) external onlyOwner { minimum_token_sell = newNumber; } function setWallet(address _wallet) external onlyOwner { wallet = _wallet; } function destroy() external onlyOwner { if (weiRaised >= softCap) selfdestruct(owner); } } //*************************************************************** // Designed by by IBERGroup, email:[email protected]; // Telegram: https://t.me/msmobile // https://t.me/alexamuek // Code released under the MIT License(see git root). //// SafeMath and Ownable part of this contract based on //// https://github.com/OpenZeppelin/zeppelin-solidity ////**************************************************************
Manually stages control
function setStageProperties( StageName _name, uint256 _planEndDate, address _tokenKeeper ) external onlyOwner { campaignStages[uint8(_name)] = StageProperties(_planEndDate, _tokenKeeper); }
1,624,724
[ 1, 5669, 3452, 20298, 3325, 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, 8755, 2297, 12, 203, 3639, 16531, 461, 389, 529, 16, 7010, 3639, 2254, 5034, 389, 7088, 24640, 16, 7010, 3639, 1758, 389, 2316, 17891, 7010, 3639, 262, 3903, 1338, 5541, 288, 203, 3639, 8965, 31359, 63, 11890, 28, 24899, 529, 25887, 273, 16531, 2297, 24899, 7088, 24640, 16, 389, 2316, 17891, 1769, 203, 565, 289, 7010, 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 ]
./partial_match/1/0x4f858fd08c9D7f068D8bB3Df25b9D14Bbc9d9Fee/sources/TOAD.sol
set as operations wallet
operationsWallet = address(0x546598971eAde6251b6c68159c9c9da4a721e18a);
3,717,985
[ 1, 542, 487, 5295, 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, 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, 3639, 5295, 16936, 273, 1758, 12, 20, 92, 6564, 26, 6162, 6675, 11212, 73, 37, 323, 26, 2947, 21, 70, 26, 71, 9470, 24872, 71, 29, 71, 29, 2414, 24, 69, 27, 5340, 73, 2643, 69, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x8fE8bDffD9ab3eC8ABF8D010e3ae3E6021814508/sources/contracts/upgradeable_contracts/omnibridge_nft/ForeignNFTOmnibridge.sol
* @title ForeignNFTOmnibridge @dev Foreign side implementation for multi-token ERC721 mediator intended to work on top of AMB bridge. It is designed to be used as an implementation contract of EternalStorageProxy contract./
contract ForeignNFTOmnibridge is BasicNFTOmnibridge, GasLimitManager { function initialize( address _bridgeContract, address _mediatorContract, uint256 _requestGasLimit, address _owner, address _imageERC721, address _imageERC1155 pragma abicoder v2; constructor(string memory _suffix) BasicNFTOmnibridge("TEST") {} ) external onlyRelevantSender returns (bool) { require(!isInitialized()); _setBridgeContract(_bridgeContract); _setMediatorContractOnOtherSide(_mediatorContract); _setRequestGasLimit(_requestGasLimit); _setOwner(_owner); _setTokenImageERC721(_imageERC721); _setTokenImageERC1155(_imageERC1155); setInitialize(); return isInitialized(); } function _passMessage(bytes memory _data, bool _useOracleLane) internal override returns (bytes32) { (_useOracleLane); return bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), _data, requestGasLimit()); } }
797,919
[ 1, 7816, 26473, 4296, 13607, 495, 5404, 225, 17635, 4889, 4471, 364, 3309, 17, 2316, 4232, 39, 27, 5340, 6735, 10620, 12613, 358, 1440, 603, 1760, 434, 432, 7969, 10105, 18, 2597, 353, 26584, 358, 506, 1399, 487, 392, 4471, 6835, 434, 512, 1174, 3245, 3886, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 17635, 26473, 4296, 13607, 495, 5404, 353, 7651, 26473, 4296, 13607, 495, 5404, 16, 31849, 3039, 1318, 288, 203, 203, 565, 445, 4046, 12, 203, 3639, 1758, 389, 18337, 8924, 16, 203, 3639, 1758, 389, 17113, 8924, 16, 203, 3639, 2254, 5034, 389, 2293, 27998, 3039, 16, 203, 3639, 1758, 389, 8443, 16, 203, 3639, 1758, 389, 2730, 654, 39, 27, 5340, 16, 203, 3639, 1758, 389, 2730, 654, 39, 2499, 2539, 203, 683, 9454, 1223, 335, 5350, 331, 22, 31, 203, 565, 3885, 12, 1080, 3778, 389, 8477, 13, 7651, 26473, 4296, 13607, 495, 5404, 2932, 16961, 7923, 2618, 203, 565, 262, 3903, 1338, 17018, 7445, 12021, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 5, 291, 11459, 10663, 203, 203, 3639, 389, 542, 13691, 8924, 24899, 18337, 8924, 1769, 203, 3639, 389, 542, 13265, 10620, 8924, 1398, 8290, 8895, 24899, 17113, 8924, 1769, 203, 3639, 389, 542, 691, 27998, 3039, 24899, 2293, 27998, 3039, 1769, 203, 3639, 389, 542, 5541, 24899, 8443, 1769, 203, 3639, 389, 542, 1345, 2040, 654, 39, 27, 5340, 24899, 2730, 654, 39, 27, 5340, 1769, 203, 3639, 389, 542, 1345, 2040, 654, 39, 2499, 2539, 24899, 2730, 654, 39, 2499, 2539, 1769, 203, 203, 3639, 444, 7520, 5621, 203, 203, 3639, 327, 25359, 5621, 203, 565, 289, 203, 203, 565, 445, 389, 5466, 1079, 12, 3890, 3778, 389, 892, 16, 1426, 389, 1202, 23601, 48, 8806, 13, 2713, 3849, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 261, 67, 1202, 23601, 48, 8806, 1769, 203, 2 ]
./partial_match/1/0x15bBeB47e642828778937b90fdA1926b744b0733/sources/Bank.sol
* generates a pseudorandom number @param seed a value ensure different outcomes for different sources in the same block @return a pseudorandom value/
function random(uint256 seed) internal view returns (uint256) { return uint256( keccak256( abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, seed ) ) ); }
4,336,650
[ 1, 3441, 815, 279, 29606, 280, 2111, 1300, 225, 5009, 279, 460, 3387, 3775, 29867, 364, 3775, 5550, 316, 326, 1967, 1203, 327, 279, 29606, 280, 2111, 460, 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, 2744, 12, 11890, 5034, 5009, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 203, 5411, 2254, 5034, 12, 203, 7734, 417, 24410, 581, 5034, 12, 203, 10792, 24126, 18, 3015, 4420, 329, 12, 203, 13491, 2229, 18, 10012, 16, 203, 13491, 1203, 2816, 12, 2629, 18, 2696, 300, 404, 3631, 203, 13491, 1203, 18, 5508, 16, 203, 13491, 5009, 203, 10792, 262, 203, 7734, 262, 203, 5411, 11272, 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 ]
// SPDX-License-Identifier: MIT // 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/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 v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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 v4.4.1 (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); } /** * @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 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 {} } // File: contracts/contract.sol pragma solidity >=0.7.0 <0.9.0; contract EvilRabbits is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriPrefix = ""; uint256 public cost = 0.1 ether; uint256 public presaleCost = 0.07 ether; uint256 public maxSupply =5005; // uint256 public maxMintAmountPerTx = 5; uint256 public maxMintAmountPerPresaleAccount = 5; uint256 public maxMintAmountPerPublicAccount = 3; bool public paused = true; bool public onlyWhitelisted=true; address[] public whitelistedAddresses; constructor() ERC721("EvilRabbits", "ER") { _mintLoop(msg.sender, 50); } modifier mintCompliance(uint256 _mintAmount) { // require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(_mintAmount > 0, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function totalSupply() public view returns (uint256) { return supply.current(); } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); if(onlyWhitelisted==true){ require(isWhiteListed(msg.sender),"user is not whitelisted"); require(msg.value >= presaleCost * _mintAmount, "Insufficient funds!"); require(balanceOf(msg.sender)<=maxMintAmountPerPresaleAccount,"Mint limit exceeded"); } else{ require(msg.value >= cost * _mintAmount, "Insufficient funds!"); require(balanceOf(msg.sender)<=maxMintAmountPerPublicAccount,"Mint limit exceeded"); } _mintLoop(msg.sender, _mintAmount); } function isWhiteListed(address _user) public view returns (bool){ for(uint256 i=0; i < whitelistedAddresses.length; i++){ if(whitelistedAddresses[i]==_user){ return true; } } return false; } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), ".json")) : ""; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function setPresaleCost(uint256 _presaleCost) public onlyOwner { presaleCost = _presaleCost; } // function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { // maxMintAmountPerTx = _maxMintAmountPerTx; // } function setMaxMintPresaleAccount(uint256 _maxMintAmountPerPresaleAccount) public onlyOwner { maxMintAmountPerPresaleAccount = _maxMintAmountPerPresaleAccount; } function setMaxMintPublicAccount(uint256 _maxMintAmountPerPublicAccount) public onlyOwner { maxMintAmountPerPublicAccount = _maxMintAmountPerPublicAccount; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function setOnlyWhiteListed(bool _state) public onlyOwner { onlyWhitelisted = _state; } function whitelistUsers(address[] calldata _users) public onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } function addOneWhitelistUser(address _user) public onlyOwner { whitelistedAddresses.push(_user); } function withdraw() public onlyOwner { // This will transfer the remaining contract balance to the owner. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
File: contracts/contract.sol uint256 public maxMintAmountPerTx = 5;
contract EvilRabbits is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriPrefix = ""; uint256 public cost = 0.1 ether; uint256 public presaleCost = 0.07 ether; uint256 public maxSupply =5005; uint256 public maxMintAmountPerPresaleAccount = 5; uint256 public maxMintAmountPerPublicAccount = 3; bool public paused = true; bool public onlyWhitelisted=true; address[] public whitelistedAddresses; function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity >=0.7.0 <0.9.0; constructor() ERC721("EvilRabbits", "ER") { _mintLoop(msg.sender, 50); } modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function totalSupply() public view returns (uint256) { return supply.current(); } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); if(onlyWhitelisted==true){ require(isWhiteListed(msg.sender),"user is not whitelisted"); require(msg.value >= presaleCost * _mintAmount, "Insufficient funds!"); require(balanceOf(msg.sender)<=maxMintAmountPerPresaleAccount,"Mint limit exceeded"); } else{ require(msg.value >= cost * _mintAmount, "Insufficient funds!"); require(balanceOf(msg.sender)<=maxMintAmountPerPublicAccount,"Mint limit exceeded"); } _mintLoop(msg.sender, _mintAmount); } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); if(onlyWhitelisted==true){ require(isWhiteListed(msg.sender),"user is not whitelisted"); require(msg.value >= presaleCost * _mintAmount, "Insufficient funds!"); require(balanceOf(msg.sender)<=maxMintAmountPerPresaleAccount,"Mint limit exceeded"); } else{ require(msg.value >= cost * _mintAmount, "Insufficient funds!"); require(balanceOf(msg.sender)<=maxMintAmountPerPublicAccount,"Mint limit exceeded"); } _mintLoop(msg.sender, _mintAmount); } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); if(onlyWhitelisted==true){ require(isWhiteListed(msg.sender),"user is not whitelisted"); require(msg.value >= presaleCost * _mintAmount, "Insufficient funds!"); require(balanceOf(msg.sender)<=maxMintAmountPerPresaleAccount,"Mint limit exceeded"); } else{ require(msg.value >= cost * _mintAmount, "Insufficient funds!"); require(balanceOf(msg.sender)<=maxMintAmountPerPublicAccount,"Mint limit exceeded"); } _mintLoop(msg.sender, _mintAmount); } function isWhiteListed(address _user) public view returns (bool){ for(uint256 i=0; i < whitelistedAddresses.length; i++){ if(whitelistedAddresses[i]==_user){ return true; } } return false; } function isWhiteListed(address _user) public view returns (bool){ for(uint256 i=0; i < whitelistedAddresses.length; i++){ if(whitelistedAddresses[i]==_user){ return true; } } return false; } function isWhiteListed(address _user) public view returns (bool){ for(uint256 i=0; i < whitelistedAddresses.length; i++){ if(whitelistedAddresses[i]==_user){ return true; } } return false; } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), ".json")) : ""; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function setPresaleCost(uint256 _presaleCost) public onlyOwner { presaleCost = _presaleCost; } function setMaxMintPresaleAccount(uint256 _maxMintAmountPerPresaleAccount) public onlyOwner { maxMintAmountPerPresaleAccount = _maxMintAmountPerPresaleAccount; } function setMaxMintPublicAccount(uint256 _maxMintAmountPerPublicAccount) public onlyOwner { maxMintAmountPerPublicAccount = _maxMintAmountPerPublicAccount; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function setOnlyWhiteListed(bool _state) public onlyOwner { onlyWhitelisted = _state; } function whitelistUsers(address[] calldata _users) public onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } function addOneWhitelistUser(address _user) public onlyOwner { whitelistedAddresses.push(_user); } function withdraw() public onlyOwner { require(os); } (bool os, ) = payable(owner()).call{value: address(this).balance}(""); function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
13,780,589
[ 1, 812, 30, 20092, 19, 16351, 18, 18281, 282, 2254, 5034, 1071, 943, 49, 474, 6275, 2173, 4188, 273, 1381, 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 ]
[ 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, 16351, 30964, 330, 54, 378, 6789, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 225, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 225, 9354, 87, 18, 4789, 3238, 14467, 31, 203, 203, 225, 533, 1071, 2003, 2244, 273, 1408, 31, 203, 21281, 225, 2254, 5034, 1071, 6991, 273, 374, 18, 21, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 4075, 5349, 8018, 273, 374, 18, 8642, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 943, 3088, 1283, 273, 12483, 25, 31, 203, 225, 2254, 5034, 1071, 943, 49, 474, 6275, 2173, 12236, 5349, 3032, 273, 1381, 31, 203, 225, 2254, 5034, 1071, 943, 49, 474, 6275, 2173, 4782, 3032, 273, 890, 31, 203, 203, 225, 1426, 1071, 17781, 273, 638, 31, 203, 203, 225, 1426, 1071, 1338, 18927, 329, 33, 3767, 31, 203, 225, 1758, 8526, 1071, 26944, 7148, 31, 203, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 27, 18, 20, 411, 20, 18, 29, 18, 20, 31, 203, 203, 203, 203, 203, 225, 3885, 1435, 4232, 39, 27, 5340, 2932, 20861, 330, 54, 378, 6789, 3113, 315, 654, 7923, 288, 203, 377, 203, 565, 389, 81, 474, 6452, 12, 3576, 18, 15330, 16, 6437, 1769, 203, 225, 289, 203, 203, 225, 9606, 312, 474, 16687, 2 ]
./full_match/3/0x334E7825C204bf3c37b7A388CBCc3b4B0299fDb4/sources/SyntheticToken.sol
0x07d090e7FcBC6AFaA507A3441C7c5eE507C457e6 mainnet bsc 0x07d090e7FcBC6AFaA507A3441C7c5eE507C457e6 testnet bsc 0x57079e0d0657890218C630DA5248A1103a1b4ad0 local 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f mainnet bsc 0xd417A0A4b65D24f5eBD0898d9028D92E3592afCC testnet bsc 0xd627ba3B9D89b99aa140BbdefD005e8CdF395a25 local 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c mainnet bsc (WBNB) 0x1e33833a035069f42d68D1F53b341643De1C018D testnet bsc (WBNB) 0xEb59fE75AC86dF3997A990EDe100b90DDCf9a826 local
abstract contract SyntheticToken is BEP20 { using SafeMath for uint256; using SafeMath for uint64; address payable public masterAddress; address payable public masterCandidate; uint256 currentEvaluation; IWiseToken public WISE_CONTRACT; bool public tokenDefined; bool public allowDeposit; PancakeSwapRouterV2 public constant PANCAKE_ROUTER = PancakeSwapRouterV2( ); PancakeSwapV2Factory public constant PANCAKE_FACTORY = PancakeSwapV2Factory( ); PancakeSwapV2Pair public PANCAKE_PAIR; IWrappedBNB constant WBNB = IWrappedBNB( ); uint256 constant PRECISION_POINTS = 10000; uint256 constant _decimals = 18; bytes4 constant BALANCEOF = bytes4( keccak256( bytes( 'balanceOf(address)' ) ) ); function squareRoot( uint256 num ) public pure returns (uint256) { return Babylonian.sqrt(num); } function _preparePath( address _wiseAddress, address _sbnbAddress ) private pure returns (address[] memory _path) { _path = new address[](2); _path[0] = _wiseAddress; _path[1] = _sbnbAddress; } function _extractAndSendFees( uint256 _currentEvaluation, uint256 _newEvaluation, uint256 _amountDeposited ) internal { } function getTradingFeeAmount( uint256 _previousEvaluation, uint256 _currentEvaluation ) public view returns (uint256) { uint256 ratio = _currentEvaluation .mul(PRECISION_POINTS) .div(_previousEvaluation); uint256 ratioSquareRoot = squareRoot(ratio); uint256 lpTokenBalance = safeBalanceOf( address(this), address(PANCAKE_PAIR) ); return PRECISION_POINTS .sub(ratioSquareRoot) .mul(lpTokenBalance); } function cleanUp() external { _cleanUp(0); } function _cleanUp( uint256 _depositAmount ) internal { uint256 availableBalance = address(this) .balance .sub(_depositAmount); uint256 selfBalance = safeBalanceOf( address(this), address(this) ); _burn( address(this), selfBalance ); masterAddress.transfer( availableBalance ); } function _swapExactTokensForTokens( uint256 _amount, uint256 _amountOutMin, address _fromTokenAddress, address _toTokenAddress, address _to ) internal { _amount, _amountInMax, [ _fromTokenAddress, _toTokenAddress ], _to, block.timestamp.add(2 hours) );*/ } function _addLiquidity( uint256 _amountBNB, uint256 _amountSBNB ) internal { } function _removeLiquidity( uint256 _amount ) internal { } function getWrappedBalance() public view returns (uint256) { return safeBalanceOf( address(WBNB), address(PANCAKE_PAIR) ); } function getSyntheticBalance() public view returns (uint256) { return safeBalanceOf( address(this), address(PANCAKE_PAIR) ); } function getPairBalances() public view returns ( uint256 wrappedBalance, uint256 syntheticBalance ) { wrappedBalance = getWrappedBalance(); syntheticBalance = getSyntheticBalance(); } function getEvaluation() public view returns(uint256) { uint256 wrappedBalance = getWrappedBalance(); uint256 syntheticBalance = getSyntheticBalance(); uint256 liquidityPercent = getLiquidityPercent(); return wrappedBalance .mul(syntheticBalance) .mul(liquidityPercent) .div(PRECISION_POINTS); } function profitArbitrage() public view returns (uint256) { uint256 wrappedBalance = getWrappedBalance(); uint256 syntheticBalance = getSyntheticBalance(); uint256 sum = wrappedBalance .add(syntheticBalance); uint256 product = wrappedBalance .mul(syntheticBalance); return sum.sub( uint256(2).mul( squareRoot(product) ) ); } function toRemoveSBNB() public view returns (uint256) { uint256 wrappedBalance = getWrappedBalance(); uint256 lpTokenBalance = getLpTokenBalance(); uint256 syntheticBalance = getSyntheticBalance(); uint256 liquidityPercent = getLiquidityPercent(); if (wrappedBalance == 0 || liquidityPercent == 0) return 0; uint256 sum = wrappedBalance .add(syntheticBalance); uint256 product = wrappedBalance .mul(syntheticBalance); uint256 result = uint256(2) .mul(squareRoot(product)); uint256 profit = sum .sub(result) .div(wrappedBalance); return lpTokenBalance .mul(profit) .div(liquidityPercent); } function toRemoveBNB() public view returns(uint256) { uint256 product = wrappedBalance .mul(syntheticBalance); uint256 buffer2 = uint256(2).mul( squareRoot(product) ); uint256 buffer3 = buffer2.sub(syntheticBalance); uint256 buffer4 = squareRoot(product); uint256 buffer5 = buffer3.div( buffer4 ); return ( buffer1.mul( buffer6 ) ).mul(lpTokenBalance); } function getLpTokenBalance() public view returns (uint256) { return safeBalanceOf( address(PANCAKE_PAIR), address(address(this)) ); } function getLiquidityPercent() public view returns (uint256) { uint256 lpTokenBalance = getLpTokenBalance(); uint256 lpTotalSupply = PANCAKE_PAIR .totalSupply(); if (lpTotalSupply == 0) return 0; return lpTokenBalance .mul(PRECISION_POINTS) .div(lpTotalSupply); } function getBalanceDiff( uint256 _amount ) public view returns (uint256) { return address(this).balance.sub(_amount); } function safeBalanceOf( address _token, address _owner ) public view returns (uint256) { IGenericToken token = IGenericToken( _token ); return token.balanceOf( _owner ); } }
14,251,101
[ 1, 20, 92, 8642, 72, 5908, 20, 73, 27, 42, 71, 16283, 26, 6799, 69, 37, 3361, 27, 37, 5026, 9803, 39, 27, 71, 25, 73, 41, 3361, 27, 39, 7950, 27, 73, 26, 225, 2774, 2758, 324, 1017, 374, 92, 8642, 72, 5908, 20, 73, 27, 42, 71, 16283, 26, 6799, 69, 37, 3361, 27, 37, 5026, 9803, 39, 27, 71, 25, 73, 41, 3361, 27, 39, 7950, 27, 73, 26, 225, 1842, 2758, 324, 1017, 374, 92, 25, 7301, 7235, 73, 20, 72, 7677, 10321, 6675, 3103, 2643, 39, 4449, 20, 9793, 25, 3247, 28, 37, 17506, 23, 69, 21, 70, 24, 361, 20, 225, 1191, 374, 92, 25, 39, 8148, 70, 41, 73, 27, 1611, 10241, 28, 3461, 69, 22, 38, 26, 69, 23, 2056, 40, 24, 38, 2313, 9401, 8876, 29, 952, 25, 69, 37, 26, 74, 225, 2774, 2758, 324, 1017, 374, 7669, 24, 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, 17801, 6835, 16091, 16466, 1345, 353, 9722, 52, 3462, 225, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 1105, 31, 203, 203, 565, 1758, 8843, 429, 1071, 4171, 1887, 31, 203, 565, 1758, 8843, 429, 1071, 4171, 11910, 31, 203, 203, 565, 2254, 5034, 783, 13468, 31, 203, 203, 565, 467, 59, 784, 1345, 1071, 678, 45, 1090, 67, 6067, 2849, 1268, 31, 203, 203, 565, 1426, 1071, 1147, 8116, 31, 203, 565, 1426, 1071, 1699, 758, 1724, 31, 203, 203, 565, 12913, 23780, 12521, 8259, 58, 22, 1071, 5381, 453, 1258, 3587, 6859, 67, 1457, 1693, 654, 273, 12913, 23780, 12521, 8259, 58, 22, 12, 203, 565, 11272, 203, 203, 565, 12913, 23780, 12521, 58, 22, 1733, 1071, 5381, 453, 1258, 3587, 6859, 67, 16193, 273, 12913, 23780, 12521, 58, 22, 1733, 12, 203, 565, 11272, 203, 203, 565, 12913, 23780, 12521, 58, 22, 4154, 1071, 453, 1258, 3587, 6859, 67, 4066, 7937, 31, 203, 203, 565, 467, 17665, 15388, 38, 5381, 678, 15388, 38, 273, 467, 17665, 15388, 38, 12, 203, 565, 11272, 203, 203, 565, 2254, 5034, 5381, 7071, 26913, 67, 8941, 55, 273, 12619, 31, 203, 565, 2254, 5034, 5381, 389, 31734, 273, 6549, 31, 203, 203, 565, 1731, 24, 5381, 605, 1013, 4722, 3932, 273, 1731, 24, 12, 203, 3639, 417, 24410, 581, 5034, 12, 203, 5411, 1731, 12, 203, 7734, 296, 12296, 951, 12, 2867, 2506, 203, 5411, 262, 203, 3639, 262, 203, 565, 11272, 203, 203, 565, 2 ]
./full_match/1/0x9a8A1D7Eac06871f60158f127704F3910613E3c3/sources/contracts/adapters/SanTokenERC4626Adapter.sol
@notice Address of the `StableMaster` in the Core module of the protocol @notice Address of the corresponding poolManager @notice Address of the associated sanToken @inheritdoc IERC4626Upgradeable @inheritdoc IERC4626Upgradeable
function stableMaster() public view virtual returns (IStableMaster); function poolManager() public view virtual returns (address); function sanToken() public view virtual returns (IERC20MetadataUpgradeable); function asset() public view virtual returns (address); function totalAssets() public view virtual returns (uint256) { return _convertToAssetsWithSlippage(sanToken().balanceOf(address(this))); }
3,219,197
[ 1, 1887, 434, 326, 1375, 30915, 7786, 68, 316, 326, 4586, 1605, 434, 326, 1771, 225, 5267, 434, 326, 4656, 2845, 1318, 225, 5267, 434, 326, 3627, 272, 304, 1345, 632, 10093, 467, 654, 39, 8749, 5558, 10784, 429, 632, 10093, 467, 654, 39, 8749, 5558, 10784, 429, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 14114, 7786, 1435, 1071, 1476, 5024, 1135, 261, 45, 30915, 7786, 1769, 203, 203, 565, 445, 2845, 1318, 1435, 1071, 1476, 5024, 1135, 261, 2867, 1769, 203, 203, 565, 445, 272, 304, 1345, 1435, 1071, 1476, 5024, 1135, 261, 45, 654, 39, 3462, 2277, 10784, 429, 1769, 203, 203, 565, 445, 3310, 1435, 1071, 1476, 5024, 1135, 261, 2867, 1769, 203, 203, 565, 445, 2078, 10726, 1435, 1071, 1476, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 6283, 774, 10726, 1190, 55, 3169, 2433, 12, 87, 304, 1345, 7675, 12296, 951, 12, 2867, 12, 2211, 3719, 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 ]
./full_match/5/0xe070CE020AfBe9566BF44592CFca8934D602fbD7/sources/project_/contracts/SmartLeaseRegistry.sol
暫時 */ 檢查 address(0) 是什麼
address testAddress_0;
7,082,560
[ 1, 167, 253, 109, 167, 252, 229, 342, 225, 167, 108, 100, 167, 258, 103, 1758, 12, 20, 13, 225, 167, 251, 112, 165, 124, 227, 170, 123, 125, 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, 1758, 1842, 1887, 67, 20, 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 ]
pragma solidity ^0.4.11; /** * @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&#39;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; /** * @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 { require(newOwner != address(0)); 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 PoSTokenStandard * @dev the interface of PoSTokenStandard */ contract PoSTokenStandard { uint256 public stakeStartTime; uint256 public stakeMinAge; uint256 public stakeMaxAge; function mint() returns (bool); function coinAge() constant returns (uint256); function annualInterest() constant returns (uint256); event Mint(address indexed _address, uint _reward); } contract COCO is ERC20,PoSTokenStandard,Ownable { using SafeMath for uint256; string public name = "Cookie Coin"; string public symbol = "COCO"; uint public decimals = 18; uint public chainStartTime; //chain start time uint public chainStartBlockNumber; //chain start block number uint public stakeStartTime; //stake start time uint public stakeMinAge = 3 days; // minimum age for coin age: 3D uint public stakeMaxAge = 90 days; // stake age of full weight: 90D uint public maxMintProofOfStake = 50000000000000000; // default 5% annual interest Years 3-15 uint public yearOneMultiplier = 72; //72 times the default 5% (360%) uint public yearTwoMultiplier = 2; //2 times the default 5% (10%) uint public totalSupply; uint public maxTotalSupply; uint public totalInitialSupply; struct transferInStruct{ uint128 amount; uint64 time; } mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; mapping(address => transferInStruct[]) transferIns; event Burn(address indexed burner, uint256 value); /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } modifier canPoSMint() { require(totalSupply < maxTotalSupply); _; } function COCO() { maxTotalSupply = 32200000000000000000000000; // 32.2 Mil. totalInitialSupply = 3200000000000000000000000; // 3.2 Mil. chainStartTime = now; chainStartBlockNumber = block.number; balances[msg.sender] = totalInitialSupply; totalSupply = totalInitialSupply; } function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) returns (bool) { if(msg.sender == _to) return mint(); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender]; uint64 _now = uint64(now); transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now)); transferIns[_to].push(transferInStruct(uint128(_value),_now)); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) returns (bool) { require(_to != address(0)); var _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); if(transferIns[_from].length > 0) delete transferIns[_from]; uint64 _now = uint64(now); transferIns[_from].push(transferInStruct(uint128(balances[_from]),_now)); transferIns[_to].push(transferInStruct(uint128(_value),_now)); return true; } function approve(address _spender, uint256 _value) returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function mint() canPoSMint returns (bool) { if(balances[msg.sender] <= 0) return false; if(transferIns[msg.sender].length <= 0) return false; uint reward = getProofOfStakeReward(msg.sender); if(reward <= 0) return false; totalSupply = totalSupply.add(reward); balances[msg.sender] = balances[msg.sender].add(reward); delete transferIns[msg.sender]; transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now))); Mint(msg.sender, reward); return true; } function getBlockNumber() returns (uint blockNumber) { blockNumber = block.number.sub(chainStartBlockNumber); } function coinAge() constant returns (uint myCoinAge) { myCoinAge = getCoinAge(msg.sender,now); } //Interest Check Function function annualInterest() constant returns(uint interest) { uint _now = now; interest = maxMintProofOfStake; if((_now.sub(stakeStartTime)).div(1 years) == 0) { interest = maxMintProofOfStake * yearOneMultiplier; } else if((_now.sub(stakeStartTime)).div(1 years) == 1){ interest = maxMintProofOfStake * yearTwoMultiplier; } } function getProofOfStakeReward(address _address) internal returns (uint) { require( (now >= stakeStartTime) && (stakeStartTime > 0) ); uint _now = now; uint _coinAge = getCoinAge(_address, _now); if(_coinAge <= 0) return 0; uint interest = maxMintProofOfStake; // Due to the high interest rate for the first two years, compounding should be taken into account. // Effective annual interest rate = (1 + (nominal rate / number of compounding periods)) ^ (number of compounding periods) - 1 if((_now.sub(stakeStartTime)).div(1 years) == 0) { // 1st year effective annual interest rate is 100% when we select the stakeMaxAge (90 days) as the compounding period. interest = maxMintProofOfStake * yearOneMultiplier; } else if((_now.sub(stakeStartTime)).div(1 years) == 1){ // 2nd year effective annual interest rate is 50% interest = maxMintProofOfStake * yearTwoMultiplier; } return (_coinAge * interest).div(365 * (10**decimals)); } function getCoinAge(address _address, uint _now) internal returns (uint _coinAge) { if(transferIns[_address].length <= 0) return 0; for (uint i = 0; i < transferIns[_address].length; i++){ if( _now < uint(transferIns[_address][i].time).add(stakeMinAge) ) continue; uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time)); if( nCoinSeconds > stakeMaxAge ) nCoinSeconds = stakeMaxAge; _coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days)); } } function ownerSetStakeStartTime(uint timestamp) onlyOwner { require((stakeStartTime <= 0) && (timestamp >= chainStartTime)); stakeStartTime = timestamp; } function ownerBurnToken(uint _value) onlyOwner { require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); delete transferIns[msg.sender]; transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now))); totalSupply = totalSupply.sub(_value); totalInitialSupply = totalInitialSupply.sub(_value); maxTotalSupply = maxTotalSupply.sub(_value*10); Burn(msg.sender, _value); } /* Batch token transfer. Used by contract creator to distribute initial tokens to holders */ function batchTransfer(address[] _recipients, uint[] _values) onlyOwner returns (bool) { require( _recipients.length > 0 && _recipients.length == _values.length); uint total = 0; for(uint i = 0; i < _values.length; i++){ total = total.add(_values[i]); } require(total <= balances[msg.sender]); uint64 _now = uint64(now); for(uint j = 0; j < _recipients.length; j++){ balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]); transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now)); Transfer(msg.sender, _recipients[j], _values[j]); } balances[msg.sender] = balances[msg.sender].sub(total); if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender]; if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now)); return true; } function setBaseInterest(uint amount) onlyOwner{ maxMintProofOfStake = amount; } function setYearOneMultiplier (uint amount) onlyOwner{ yearOneMultiplier = amount; } function setYearTwoMultiplier (uint amount) onlyOwner{ yearTwoMultiplier = amount; } }
default 5% annual interest Years 3-15
uint public maxMintProofOfStake = 50000000000000000;
2,114,499
[ 1, 1886, 1381, 9, 8226, 1462, 16513, 16666, 87, 890, 17, 3600, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 943, 49, 474, 20439, 951, 510, 911, 273, 1381, 12648, 12648, 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 ]
./full_match/1/0x93256C28ac5B2DFe5eA80251c685390736b42114/sources/contracts/Registry.sol
* @dev Unpauses our creator which enables calculateCreatorPayout and any marketplaces that read from this registry. Requirements: - Creator must be paused/
function unpauseCreator(address creatorAddress) external { require(_isCreatorRegistered(creatorAddress), "CreatorAddress is not registered"); require(_canPause(creatorAddress), "Sender cannot unpause this creator"); require(_addressToCreator[creatorAddress].paused, "Creator not paused"); _addressToCreator[creatorAddress].paused = false; emit CreatorUnpaused(creatorAddress); }
8,427,564
[ 1, 984, 8774, 6117, 3134, 11784, 1492, 19808, 4604, 10636, 52, 2012, 471, 1281, 13667, 11350, 716, 855, 628, 333, 4023, 18, 29076, 30, 300, 29525, 1297, 506, 17781, 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, 640, 19476, 10636, 12, 2867, 11784, 1887, 13, 3903, 288, 203, 3639, 2583, 24899, 291, 10636, 10868, 12, 20394, 1887, 3631, 315, 10636, 1887, 353, 486, 4104, 8863, 203, 3639, 2583, 24899, 4169, 19205, 12, 20394, 1887, 3631, 315, 12021, 2780, 640, 19476, 333, 11784, 8863, 203, 3639, 2583, 24899, 2867, 774, 10636, 63, 20394, 1887, 8009, 8774, 3668, 16, 315, 10636, 486, 17781, 8863, 203, 3639, 389, 2867, 774, 10636, 63, 20394, 1887, 8009, 8774, 3668, 273, 629, 31, 203, 203, 3639, 3626, 29525, 984, 8774, 3668, 12, 20394, 1887, 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 ]
pragma solidity ^0.4.21; /* GI0 ERC20 Sale Contract Sale(address ethwallet) // this will send the received ETH funds to this address */ contract ERC20 { uint public totalSupply; function balanceOf(address who) public constant returns (uint); function allowance(address owner, address spender) public constant returns (uint); function transfer(address to, uint value) public returns (bool ok); function transferFrom(address from, address to, uint value) public returns (bool ok); function approve(address spender, uint value) public returns (bool ok); function mintToken(address to, uint256 value) public returns (uint256); function changeTransfer(bool allowed) public; } contract Sale { uint256 public maxMintable; uint256 public totalMinted; uint public endBlock; uint public startBlock; uint public exchangeRate; bool public isFunding; ERC20 public Token; address public ETHWallet; uint256 public heldTotal; bool private configSet; address public creator; event Contribution(address from, uint256 amount); event ReleaseTokens(address from, uint256 amount); constructor(address _wallet) public { startBlock = block.number; maxMintable = 33333333000000000000000000; // 33,333,333 ETHWallet = _wallet; isFunding = true; creator = msg.sender; exchangeRate = 3636; // 0.000275 ETH } // setup function to be ran only 1 time // setup token address // setup end Block number function setup(address token_address, uint end_block) public { require(!configSet); Token = ERC20(token_address); endBlock = end_block; configSet = true; } function closeSale() external { require(msg.sender==creator); isFunding = false; } function () payable public { require(msg.value>0); require(isFunding); require(block.number <= endBlock); uint256 amount = msg.value * exchangeRate; uint256 total = totalMinted + amount; require(total<=maxMintable); totalMinted += total; ETHWallet.transfer(msg.value); Token.mintToken(msg.sender, amount); emit Contribution(msg.sender, amount); } // CONTRIBUTE FUNCTION // converts ETH to TOKEN and sends new TOKEN to the sender function contribute() external payable { require(msg.value>0); require(isFunding); require(block.number <= endBlock); uint256 amount = msg.value * exchangeRate; uint256 total = totalMinted + amount; require(total<=maxMintable); totalMinted += total; ETHWallet.transfer(msg.value); Token.mintToken(msg.sender, amount); emit Contribution(msg.sender, amount); } // update the ETH/GI0 rate function updateRate(uint256 rate) external { require(msg.sender==creator); require(isFunding); exchangeRate = rate; } // change creator address function changeCreator(address _creator) external { require(msg.sender==creator); creator = _creator; } // change transfer status for ERC20 token function changeTransferStats(bool _allowed) external { require(msg.sender==creator); Token.changeTransfer(_allowed); } }
setup function to be ran only 1 time setup token address setup end Block number
function setup(address token_address, uint end_block) public { require(!configSet); Token = ERC20(token_address); endBlock = end_block; configSet = true; }
996,936
[ 1, 8401, 445, 358, 506, 18892, 1338, 404, 813, 3875, 1147, 1758, 3875, 679, 3914, 1300, 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, 3875, 12, 2867, 1147, 67, 2867, 16, 2254, 679, 67, 2629, 13, 1071, 288, 203, 3639, 2583, 12, 5, 1425, 694, 1769, 203, 3639, 3155, 273, 4232, 39, 3462, 12, 2316, 67, 2867, 1769, 203, 3639, 679, 1768, 273, 679, 67, 2629, 31, 203, 3639, 642, 694, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // Contract setup ==================== contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(uint256 _id); event Unpause(uint256 _id); bool public paused_1 = false; bool public paused_2 = false; bool public paused_3 = false; bool public paused_4 = false; modifier whenNotPaused_1() { require(!paused_1); _; } modifier whenNotPaused_2() { require(!paused_2); _; } modifier whenNotPaused_3() { require(!paused_3); _; } modifier whenNotPaused_4() { require(!paused_4); _; } modifier whenPaused_1() { require(paused_1); _; } modifier whenPaused_2() { require(paused_2); _; } modifier whenPaused_3() { require(paused_3); _; } modifier whenPaused_4() { require(paused_4); _; } function pause_1() onlyOwner whenNotPaused_1 public { paused_1 = true; emit Pause(1); } function pause_2() onlyOwner whenNotPaused_2 public { paused_2 = true; emit Pause(2); } function pause_3() onlyOwner whenNotPaused_3 public { paused_3 = true; emit Pause(3); } function pause_4() onlyOwner whenNotPaused_4 public { paused_4 = true; emit Pause(4); } function unpause_1() onlyOwner whenPaused_1 public { paused_1 = false; emit Unpause(1); } function unpause_2() onlyOwner whenPaused_2 public { paused_2 = false; emit Unpause(2); } function unpause_3() onlyOwner whenPaused_3 public { paused_3 = false; emit Unpause(3); } function unpause_4() onlyOwner whenPaused_4 public { paused_4 = false; emit Unpause(4); } } contract JCLYLong is Pausable { using SafeMath for *; event KeyPurchase(address indexed purchaser, uint256 eth, uint256 amount); event LeekStealOn(); address private constant WALLET_ETH_COM1 = 0x2509CF8921b95bef38DEb80fBc420Ef2bbc53ce3; address private constant WALLET_ETH_COM2 = 0x18d9fc8e3b65124744553d642989e3ba9e41a95a; // Configurables ==================== uint256 constant private rndInit_ = 10 hours; uint256 constant private rndInc_ = 30 seconds; uint256 constant private rndMax_ = 24 hours; // eth limiter uint256 constant private ethLimiterRange1_ = 1e20; uint256 constant private ethLimiterRange2_ = 5e20; uint256 constant private ethLimiter1_ = 2e18; uint256 constant private ethLimiter2_ = 7e18; // whitelist range uint256 constant private whitelistRange_ = 1 days; // for price uint256 constant private priceStage1_ = 500e18; uint256 constant private priceStage2_ = 1000e18; uint256 constant private priceStage3_ = 2000e18; uint256 constant private priceStage4_ = 4000e18; uint256 constant private priceStage5_ = 8000e18; uint256 constant private priceStage6_ = 16000e18; uint256 constant private priceStage7_ = 32000e18; uint256 constant private priceStage8_ = 64000e18; uint256 constant private priceStage9_ = 128000e18; uint256 constant private priceStage10_ = 256000e18; uint256 constant private priceStage11_ = 512000e18; uint256 constant private priceStage12_ = 1024000e18; // for gu phrase uint256 constant private guPhrase1_ = 5 days; uint256 constant private guPhrase2_ = 7 days; uint256 constant private guPhrase3_ = 9 days; uint256 constant private guPhrase4_ = 11 days; uint256 constant private guPhrase5_ = 13 days; uint256 constant private guPhrase6_ = 15 days; uint256 constant private guPhrase7_ = 17 days; uint256 constant private guPhrase8_ = 19 days; uint256 constant private guPhrase9_ = 21 days; uint256 constant private guPhrase10_ = 23 days; // Data setup ==================== uint256 public contractStartDate_; // contract creation time uint256 public allMaskGu_; // for sharing eth-profit by holding gu uint256 public allGuGiven_; // for sharing eth-profit by holding gu mapping (uint256 => uint256) public playOrders_; // playCounter => pID // AIRDROP DATA uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop mapping (uint256 => mapping (uint256 => uint256)) public airDropWinners_; // counter => pID => winAmt uint256 public airDropCount_; // LEEKSTEAL DATA uint256 public leekStealPot_; // person who gets the first leeksteal wins part of this pot uint256 public leekStealTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning leek steal uint256 public leekStealToday_; bool public leekStealOn_; mapping (uint256 => uint256) public dayStealTime_; // dayNum => time that makes leekSteal available mapping (uint256 => uint256) public leekStealWins_; // pID => winAmt // PLAYER DATA uint256 public pID_; // total number of players mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address // mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Datasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => Datasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (uint256 => Datasets.PlayerPhrases)) public plyrPhas_; // (pID => phraseID => data) player round data by player id & round id // ROUND DATA uint256 public rID_; // round id number / total rounds that have happened mapping (uint256 => Datasets.Round) public round_; // (rID => data) round data // PHRASE DATA uint256 public phID_; // gu phrase ID mapping (uint256 => Datasets.Phrase) public phrase_; // (phID_ => data) round data // WHITELIST mapping(address => bool) public whitelisted_Prebuy; // pID => isWhitelisted // Constructor ==================== constructor() public { // set genesis player pIDxAddr_[owner] = 0; plyr_[0].addr = owner; pIDxAddr_[WALLET_ETH_COM1] = 1; plyr_[1].addr = WALLET_ETH_COM1; pIDxAddr_[WALLET_ETH_COM2] = 2; plyr_[2].addr = WALLET_ETH_COM2; pID_ = 2; } // Modifiers ==================== modifier isActivated() { require(activated_ == true); _; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000); require(_eth <= 100000000000000000000000); _; } modifier withinMigrationPeriod() { require(now < 1535637600); _; } // Public functions ==================== function deposit() isWithinLimits(msg.value) onlyOwner public payable {} function migrateBasicData(uint256 allMaskGu, uint256 allGuGiven, uint256 airDropPot, uint256 airDropTracker, uint256 leekStealPot, uint256 leekStealTracker, uint256 leekStealToday, uint256 pID, uint256 rID) withinMigrationPeriod onlyOwner public { allMaskGu_ = allMaskGu; allGuGiven_ = allGuGiven; airDropPot_ = airDropPot; airDropTracker_ = airDropTracker; leekStealPot_ = leekStealPot; leekStealTracker_ = leekStealTracker; leekStealToday_ = leekStealToday; pID_ = pID; rID_ = rID; } function migratePlayerData1(uint256 _pID, address addr, uint256 win, uint256 gen, uint256 genGu, uint256 aff, uint256 refund, uint256 lrnd, uint256 laff, uint256 withdraw) withinMigrationPeriod onlyOwner public { pIDxAddr_[addr] = _pID; plyr_[_pID].addr = addr; plyr_[_pID].win = win; plyr_[_pID].gen = gen; plyr_[_pID].genGu = genGu; plyr_[_pID].aff = aff; plyr_[_pID].refund = refund; plyr_[_pID].lrnd = lrnd; plyr_[_pID].laff = laff; plyr_[_pID].withdraw = withdraw; } function migratePlayerData2(uint256 _pID, address addr, uint256 maskGu, uint256 gu, uint256 referEth, uint256 lastClaimedPhID) withinMigrationPeriod onlyOwner public { pIDxAddr_[addr] = _pID; plyr_[_pID].addr = addr; plyr_[_pID].maskGu = maskGu; plyr_[_pID].gu = gu; plyr_[_pID].referEth = referEth; plyr_[_pID].lastClaimedPhID = lastClaimedPhID; } function migratePlayerRoundsData(uint256 _pID, uint256 eth, uint256 keys, uint256 maskKey, uint256 genWithdraw) withinMigrationPeriod onlyOwner public { plyrRnds_[_pID][1].eth = eth; plyrRnds_[_pID][1].keys = keys; plyrRnds_[_pID][1].maskKey = maskKey; plyrRnds_[_pID][1].genWithdraw = genWithdraw; } function migratePlayerPhrasesData(uint256 _pID, uint256 eth, uint256 guRewarded) withinMigrationPeriod onlyOwner public { // pIDxAddr_[addr] = _pID; plyrPhas_[_pID][1].eth = eth; plyrPhas_[_pID][1].guRewarded = guRewarded; } function migrateRoundData(uint256 plyr, uint256 end, bool ended, uint256 strt, uint256 allkeys, uint256 keys, uint256 eth, uint256 pot, uint256 maskKey, uint256 playCtr, uint256 withdraw) withinMigrationPeriod onlyOwner public { round_[1].plyr = plyr; round_[1].end = end; round_[1].ended = ended; round_[1].strt = strt; round_[1].allkeys = allkeys; round_[1].keys = keys; round_[1].eth = eth; round_[1].pot = pot; round_[1].maskKey = maskKey; round_[1].playCtr = playCtr; round_[1].withdraw = withdraw; } function migratePhraseData(uint256 eth, uint256 guGiven, uint256 mask, uint256 minEthRequired, uint256 guPoolAllocation) withinMigrationPeriod onlyOwner public { phrase_[1].eth = eth; phrase_[1].guGiven = guGiven; phrase_[1].mask = mask; phrase_[1].minEthRequired = minEthRequired; phrase_[1].guPoolAllocation = guPoolAllocation; } function updateWhitelist(address[] _addrs, bool _isWhitelisted) public onlyOwner { for (uint i = 0; i < _addrs.length; i++) { whitelisted_Prebuy[_addrs[i]] = _isWhitelisted; } } // buy using last stored affiliate ID function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // determine if player is new or not uint256 _pID = pIDxAddr_[msg.sender]; if (_pID == 0) { pID_++; // grab their player ID and last aff ID, from player names contract pIDxAddr_[msg.sender] = pID_; // set up player account plyr_[pID_].addr = msg.sender; // set up player account _pID = pID_; } // buy core buyCore(_pID, plyr_[_pID].laff); } function buyXid(uint256 _affID) isActivated() isHuman() isWithinLimits(msg.value) public payable { // determine if player is new or not uint256 _pID = pIDxAddr_[msg.sender]; // fetch player id if (_pID == 0) { pID_++; // grab their player ID and last aff ID, from player names contract pIDxAddr_[msg.sender] = pID_; // set up player account plyr_[pID_].addr = msg.sender; // set up player account _pID = pID_; } // manage affiliate residuals // if no affiliate code was given or player tried to use their own if (_affID == 0 || _affID == _pID || _affID > pID_) { _affID = plyr_[_pID].laff; // use last stored affiliate code // if affiliate code was given & its not the same as previously stored } else if (_affID != plyr_[_pID].laff) { if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; // update last affiliate else _affID = plyr_[_pID].laff; } // buy core buyCore(_pID, _affID); } function reLoadXid() isActivated() isHuman() public { uint256 _pID = pIDxAddr_[msg.sender]; // fetch player ID require(_pID > 0); reLoadCore(_pID, plyr_[_pID].laff); } function reLoadCore(uint256 _pID, uint256 _affID) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // whitelist checking if (_now < round_[rID_].strt + whitelistRange_) { require(whitelisted_Prebuy[plyr_[_pID].addr] || whitelisted_Prebuy[plyr_[_affID].addr]); } // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { uint256 _eth = withdrawEarnings(_pID, false); if (_eth > 0) { // call core core(_rID, _pID, _eth, _affID); } // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; endRound(); } } function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // end the round (distributes pot) round_[_rID].ended = true; endRound(); // get their earnings _eth = withdrawEarnings(_pID, true); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID, true); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); } } function buyCore(uint256 _pID, uint256 _affID) whenNotPaused_1 private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // whitelist checking if (_now < round_[rID_].strt + whitelistRange_) { require(whitelisted_Prebuy[plyr_[_pID].addr] || whitelisted_Prebuy[plyr_[_affID].addr]); } // if round is active if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; endRound(); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID) private { // if player is new to current round if (plyrRnds_[_pID][_rID].keys == 0) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); plyr_[_pID].lrnd = rID_; // update player&#39;s last round played } // early round eth limiter (0-100 eth) uint256 _availableLimit; uint256 _refund; if (round_[_rID].eth < ethLimiterRange1_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter1_) { _availableLimit = (ethLimiter1_).sub(plyrRnds_[_pID][_rID].eth); _refund = _eth.sub(_availableLimit); plyr_[_pID].refund = plyr_[_pID].refund.add(_refund); _eth = _availableLimit; } else if (round_[_rID].eth < ethLimiterRange2_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter2_) { _availableLimit = (ethLimiter2_).sub(plyrRnds_[_pID][_rID].eth); _refund = _eth.sub(_availableLimit); plyr_[_pID].refund = plyr_[_pID].refund.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1e9) { // mint the new keys uint256 _keys = keysRec(round_[_rID].eth, _eth); // if they bought at least 1 whole key if (_keys >= 1e18) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; emit KeyPurchase(plyr_[round_[_rID].plyr].addr, _eth, _keys); } // manage airdrops if (_eth >= 1e17) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 1e19) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won } else if (_eth >= 1e18 && _eth < 1e19) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won } else if (_eth >= 1e17 && _eth < 1e18) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won } // reset air drop tracker airDropTracker_ = 0; // NEW airDropCount_++; airDropWinners_[airDropCount_][_pID] = _prize; } } leekStealGo(); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); round_[_rID].playCtr++; playOrders_[round_[_rID].playCtr] = pID_; // for recording the 500 winners // update round round_[_rID].allkeys = _keys.add(round_[_rID].allkeys); round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); // distribute eth distributeExternal(_rID, _pID, _eth, _affID); distributeInternal(_rID, _pID, _eth, _keys); // manage gu-referral updateGuReferral(_pID, _affID, _eth); checkDoubledProfit(_pID, _rID); checkDoubledProfit(_affID, _rID); } } // zero out keys if the accumulated profit doubled function checkDoubledProfit(uint256 _pID, uint256 _rID) private { // if pID has no keys, skip this uint256 _keys = plyrRnds_[_pID][_rID].keys; if (_keys > 0) { uint256 _genVault = plyr_[_pID].gen; uint256 _genWithdraw = plyrRnds_[_pID][_rID].genWithdraw; uint256 _genEarning = calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd); uint256 _doubleProfit = (plyrRnds_[_pID][_rID].eth).mul(2); if (_genVault.add(_genWithdraw).add(_genEarning) >= _doubleProfit) { // put only calculated-remain-profit into gen vault uint256 _remainProfit = _doubleProfit.sub(_genVault).sub(_genWithdraw); plyr_[_pID].gen = _remainProfit.add(plyr_[_pID].gen); plyrRnds_[_pID][_rID].keyProfit = _remainProfit.add(plyrRnds_[_pID][_rID].keyProfit); // follow maskKey round_[_rID].keys = round_[_rID].keys.sub(_keys); plyrRnds_[_pID][_rID].keys = plyrRnds_[_pID][_rID].keys.sub(_keys); plyrRnds_[_pID][_rID].maskKey = 0; // treat this player like a new player } } } function keysRec(uint256 _curEth, uint256 _newEth) private returns (uint256) { uint256 _startEth; uint256 _incrRate; uint256 _initPrice; if (_curEth < priceStage1_) { _startEth = 0; _initPrice = 33333; //3e-5; _incrRate = 50000000; //2e-8; } else if (_curEth < priceStage2_) { _startEth = priceStage1_; _initPrice = 25000; // 4e-5; _incrRate = 50000000; //2e-8; } else if (_curEth < priceStage3_) { _startEth = priceStage2_; _initPrice = 20000; //5e-5; _incrRate = 50000000; //2e-8;; } else if (_curEth < priceStage4_) { _startEth = priceStage3_; _initPrice = 12500; //8e-5; _incrRate = 26666666; //3.75e-8; } else if (_curEth < priceStage5_) { _startEth = priceStage4_; _initPrice = 5000; //2e-4; _incrRate = 17777777; //5.625e-8; } else if (_curEth < priceStage6_) { _startEth = priceStage5_; _initPrice = 2500; // 4e-4; _incrRate = 10666666; //9.375e-8; } else if (_curEth < priceStage7_) { _startEth = priceStage6_; _initPrice = 1000; //0.001; _incrRate = 5688282; //1.758e-7; } else if (_curEth < priceStage8_) { _startEth = priceStage7_; _initPrice = 250; //0.004; _incrRate = 2709292; //3.691e-7; } else if (_curEth < priceStage9_) { _startEth = priceStage8_; _initPrice = 62; //0.016; _incrRate = 1161035; //8.613e-7; } else if (_curEth < priceStage10_) { _startEth = priceStage9_; _initPrice = 14; //0.071; _incrRate = 451467; //2.215e-6; } else if (_curEth < priceStage11_) { _startEth = priceStage10_; _initPrice = 2; //0.354; _incrRate = 144487; //6.921e-6; } else if (_curEth < priceStage12_) { _startEth = priceStage11_; _initPrice = 0; //2.126; _incrRate = 40128; //2.492e-5; } else { _startEth = priceStage12_; _initPrice = 0; _incrRate = 40128; //2.492e-5; } return _newEth.mul(((_incrRate.mul(_initPrice)) / (_incrRate.add(_initPrice.mul((_curEth.sub(_startEth))/1e18))))); } function updateGuReferral(uint256 _pID, uint256 _affID, uint256 _eth) private { uint256 _newPhID = updateGuPhrase(); // update phrase, and distribute remaining gu for the last phrase if (phID_ < _newPhID) { updateReferralMasks(phID_); plyr_[1].gu = (phrase_[_newPhID].guPoolAllocation / 10).add(plyr_[1].gu); // give 20% gu to community first, at the beginning of the phrase start plyr_[2].gu = (phrase_[_newPhID].guPoolAllocation / 10).add(plyr_[2].gu); // give 20% gu to community first, at the beginning of the phrase start phrase_[_newPhID].guGiven = (phrase_[_newPhID].guPoolAllocation / 5).add(phrase_[_newPhID].guGiven); allGuGiven_ = (phrase_[_newPhID].guPoolAllocation / 5).add(allGuGiven_); phID_ = _newPhID; // update the phrase ID } // update referral eth on affiliate if (_affID != 0 && _affID != _pID) { plyrPhas_[_affID][_newPhID].eth = _eth.add(plyrPhas_[_affID][_newPhID].eth); plyr_[_affID].referEth = _eth.add(plyr_[_affID].referEth); phrase_[_newPhID].eth = _eth.add(phrase_[_newPhID].eth); } uint256 _remainGuReward = phrase_[_newPhID].guPoolAllocation.sub(phrase_[_newPhID].guGiven); // if 1) one has referral amt larger than requirement, 2) has remaining => then distribute certain amt of Gu, i.e. update gu instead of adding gu if (plyrPhas_[_affID][_newPhID].eth >= phrase_[_newPhID].minEthRequired && _remainGuReward >= 1e18) { // check if need to reward more gu uint256 _totalReward = plyrPhas_[_affID][_newPhID].eth / phrase_[_newPhID].minEthRequired; _totalReward = _totalReward.mul(1e18); uint256 _rewarded = plyrPhas_[_affID][_newPhID].guRewarded; uint256 _toReward = _totalReward.sub(_rewarded); if (_remainGuReward < _toReward) _toReward = _remainGuReward; // give out gu reward if (_toReward > 0) { plyr_[_affID].gu = _toReward.add(plyr_[_affID].gu); // give gu to player plyrPhas_[_affID][_newPhID].guRewarded = _toReward.add(plyrPhas_[_affID][_newPhID].guRewarded); phrase_[_newPhID].guGiven = 1e18.add(phrase_[_newPhID].guGiven); allGuGiven_ = 1e18.add(allGuGiven_); } } } function updateReferralMasks(uint256 _phID) private { uint256 _remainGu = phrase_[phID_].guPoolAllocation.sub(phrase_[phID_].guGiven); if (_remainGu > 0 && phrase_[_phID].eth > 0) { // remaining gu per total ethIn in the phrase uint256 _gpe = (_remainGu.mul(1e18)) / phrase_[_phID].eth; phrase_[_phID].mask = _gpe.add(phrase_[_phID].mask); // should only added once } } function transferGu(address _to, uint256 _guAmt) public whenNotPaused_2 returns (bool) { require(_to != address(0)); if (_guAmt > 0) { uint256 _pIDFrom = pIDxAddr_[msg.sender]; uint256 _pIDTo = pIDxAddr_[_to]; require(plyr_[_pIDFrom].addr == msg.sender); require(plyr_[_pIDTo].addr == _to); // update profit for playerFrom uint256 _profit = (allMaskGu_.mul(_guAmt)/1e18).sub( (plyr_[_pIDFrom].maskGu.mul(_guAmt) / plyr_[_pIDFrom].gu) ); plyr_[_pIDFrom].genGu = _profit.add(plyr_[_pIDFrom].genGu); // put in genGu vault plyr_[_pIDFrom].guProfit = _profit.add(plyr_[_pIDFrom].guProfit); // update mask for playerFrom plyr_[_pIDFrom].maskGu = plyr_[_pIDFrom].maskGu.sub( (allMaskGu_.mul(_guAmt)/1e18).sub(_profit) ); // for playerTo plyr_[_pIDTo].maskGu = (allMaskGu_.mul(_guAmt)/1e18).add(plyr_[_pIDTo].maskGu); plyr_[_pIDFrom].gu = plyr_[_pIDFrom].gu.sub(_guAmt); plyr_[_pIDTo].gu = plyr_[_pIDTo].gu.add(_guAmt); return true; } else return false; } function updateGuPhrase() private returns (uint256) // return phraseNum { if (now <= contractStartDate_ + guPhrase1_) { phrase_[1].minEthRequired = 5e18; phrase_[1].guPoolAllocation = 100e18; return 1; } if (now <= contractStartDate_ + guPhrase2_) { phrase_[2].minEthRequired = 4e18; phrase_[2].guPoolAllocation = 200e18; return 2; } if (now <= contractStartDate_ + guPhrase3_) { phrase_[3].minEthRequired = 3e18; phrase_[3].guPoolAllocation = 400e18; return 3; } if (now <= contractStartDate_ + guPhrase4_) { phrase_[4].minEthRequired = 2e18; phrase_[4].guPoolAllocation = 800e18; return 4; } if (now <= contractStartDate_ + guPhrase5_) { phrase_[5].minEthRequired = 1e18; phrase_[5].guPoolAllocation = 1600e18; return 5; } if (now <= contractStartDate_ + guPhrase6_) { phrase_[6].minEthRequired = 1e18; phrase_[6].guPoolAllocation = 3200e18; return 6; } if (now <= contractStartDate_ + guPhrase7_) { phrase_[7].minEthRequired = 1e18; phrase_[7].guPoolAllocation = 6400e18; return 7; } if (now <= contractStartDate_ + guPhrase8_) { phrase_[8].minEthRequired = 1e18; phrase_[8].guPoolAllocation = 12800e18; return 8; } if (now <= contractStartDate_ + guPhrase9_) { phrase_[9].minEthRequired = 1e18; phrase_[9].guPoolAllocation = 25600e18; return 9; } if (now <= contractStartDate_ + guPhrase10_) { phrase_[10].minEthRequired = 1e18; phrase_[10].guPoolAllocation = 51200e18; return 10; } phrase_[11].minEthRequired = 0; phrase_[11].guPoolAllocation = 0; return 11; } function calcUnMaskedKeyEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { if ( (((round_[_rIDlast].maskKey).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)) > (plyrRnds_[_pID][_rIDlast].maskKey) ) return( (((round_[_rIDlast].maskKey).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)).sub(plyrRnds_[_pID][_rIDlast].maskKey) ); else return 0; } function calcUnMaskedGuEarnings(uint256 _pID) private view returns(uint256) { if ( ((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)) > (plyr_[_pID].maskGu) ) return( ((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)).sub(plyr_[_pID].maskGu) ); else return 0; } function endRound() private { // setup local rID uint256 _rID = rID_; // grab our winning player id uint256 _winPID = round_[_rID].plyr; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // jcg share, and amount reserved for next pot uint256 _win = (_pot.mul(40)) / 100; uint256 _res = (_pot.mul(10)) / 100; // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // pay the rest of the 500 winners pay500Winners(_pot); // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_); round_[_rID].pot = _res; } function pay500Winners(uint256 _pot) private { uint256 _rID = rID_; uint256 _plyCtr = round_[_rID].playCtr; // pay the 2-10th uint256 _win2 = _pot.mul(25).div(100).div(9); for (uint256 i = _plyCtr.sub(9); i <= _plyCtr.sub(1); i++) { plyr_[playOrders_[i]].win = _win2.add(plyr_[playOrders_[i]].win); } // pay the 11-100th uint256 _win3 = _pot.mul(15).div(100).div(90); for (uint256 j = _plyCtr.sub(99); j <= _plyCtr.sub(10); j++) { plyr_[playOrders_[j]].win = _win3.add(plyr_[playOrders_[j]].win); } // pay the 101-500th uint256 _win4 = _pot.mul(10).div(100).div(400); for (uint256 k = _plyCtr.sub(499); k <= _plyCtr.sub(100); k++) { plyr_[playOrders_[k]].win = _win4.add(plyr_[playOrders_[k]].win); } } function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedKeyEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].maskKey = _earnings.add(plyrRnds_[_pID][_rIDlast].maskKey); plyrRnds_[_pID][_rIDlast].keyProfit = _earnings.add(plyrRnds_[_pID][_rIDlast].keyProfit); // NEW: follow maskKey } } function updateGenGuVault(uint256 _pID) private { uint256 _earnings = calcUnMaskedGuEarnings(_pID); if (_earnings > 0) { // put in genGu vault plyr_[_pID].genGu = _earnings.add(plyr_[_pID].genGu); // zero out their earnings by updating mask plyr_[_pID].maskGu = _earnings.add(plyr_[_pID].maskGu); plyr_[_pID].guProfit = _earnings.add(plyr_[_pID].guProfit); } } // update gu-reward for referrals function updateReferralGu(uint256 _pID) private { // get current phID uint256 _phID = phID_; // get last claimed phID till uint256 _lastClaimedPhID = plyr_[_pID].lastClaimedPhID; if (_phID > _lastClaimedPhID) { // calculate the gu Shares using these two input uint256 _guShares; for (uint i = (_lastClaimedPhID + 1); i < _phID; i++) { _guShares = (((phrase_[i].mask).mul(plyrPhas_[_pID][i].eth))/1e18).add(_guShares); // update record plyr_[_pID].lastClaimedPhID = i; phrase_[i].guGiven = _guShares.add(phrase_[i].guGiven); plyrPhas_[_pID][i].guRewarded = _guShares.add(plyrPhas_[_pID][i].guRewarded); } // put gu in player plyr_[_pID].gu = _guShares.add(plyr_[_pID].gu); // zero out their earnings by updating mask plyr_[_pID].maskGu = ((allMaskGu_.mul(_guShares)) / 1e18).add(plyr_[_pID].maskGu); allGuGiven_ = _guShares.add(allGuGiven_); } } function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } function randomNum(uint256 _tracker) private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < _tracker) return(true); else return(false); } function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID) private { // pay 2% out to community rewards uint256 _com = _eth / 100; address(WALLET_ETH_COM1).transfer(_com); // 1% address(WALLET_ETH_COM2).transfer(_com); // 1% // distribute 10% share to affiliate (8% + 2%) uint256 _aff = _eth / 10; // check: affiliate must not be self, and must have an ID if (_affID != _pID && _affID != 0) { plyr_[_affID].aff = (_aff.mul(8)/10).add(plyr_[_affID].aff); // distribute 8% to 1st aff uint256 _affID2 = plyr_[_affID].laff; // get 2nd aff if (_affID2 != _pID && _affID2 != 0) { plyr_[_affID2].aff = (_aff.mul(2)/10).add(plyr_[_affID2].aff); // distribute 2% to 2nd aff } } else { plyr_[1].aff = _aff.add(plyr_[_affID].aff); } } function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys) private { // calculate gen share uint256 _gen = (_eth.mul(40)) / 100; // 40% // calculate jcg share uint256 _jcg = (_eth.mul(20)) / 100; // 20% // toss 3% into airdrop pot uint256 _air = (_eth.mul(3)) / 100; airDropPot_ = airDropPot_.add(_air); // toss 5% into leeksteal pot uint256 _steal = (_eth / 20); leekStealPot_ = leekStealPot_.add(_steal); // update eth balance (eth = eth - (2% com share + 3% airdrop + 5% leekSteal + 10% aff share)) _eth = _eth.sub(((_eth.mul(20)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen).sub(_jcg); // distribute gen n jcg share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dustKey = updateKeyMasks(_rID, _pID, _gen, _keys); uint256 _dustGu = updateGuMasks(_pID, _jcg); // add eth to pot round_[_rID].pot = _pot.add(_dustKey).add(_dustGu).add(round_[_rID].pot); } // update profit to key-holders function updateKeyMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1e18)) / (round_[_rID].keys); round_[_rID].maskKey = _ppt.add(round_[_rID].maskKey); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1e18); plyrRnds_[_pID][_rID].maskKey = (((round_[_rID].maskKey.mul(_keys)) / (1e18)).sub(_pearn)).add(plyrRnds_[_pID][_rID].maskKey); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1e18))); } // update profit to gu-holders function updateGuMasks(uint256 _pID, uint256 _jcg) private returns(uint256) { if (allGuGiven_ > 0) { // calc profit per gu & round mask based on this buy: (dust goes to pot) uint256 _ppg = (_jcg.mul(1e18)) / allGuGiven_; allMaskGu_ = _ppg.add(allMaskGu_); // calculate & return dust return (_jcg.sub((_ppg.mul(allGuGiven_)) / (1e18))); } else { return _jcg; } } function withdrawEarnings(uint256 _pID, bool isWithdraw) whenNotPaused_3 private returns(uint256) { uint256 _rID = plyr_[_pID].lrnd; updateGenGuVault(_pID); updateReferralGu(_pID); checkDoubledProfit(_pID, _rID); updateGenVault(_pID, _rID); // from all vaults uint256 _earnings = plyr_[_pID].gen.add(plyr_[_pID].win).add(plyr_[_pID].genGu).add(plyr_[_pID].aff).add(plyr_[_pID].refund); if (_earnings > 0) { if (isWithdraw) { plyrRnds_[_pID][_rID].winWithdraw = plyr_[_pID].win.add(plyrRnds_[_pID][_rID].winWithdraw); plyrRnds_[_pID][_rID].genWithdraw = plyr_[_pID].gen.add(plyrRnds_[_pID][_rID].genWithdraw); // for doubled profit plyrRnds_[_pID][_rID].genGuWithdraw = plyr_[_pID].genGu.add(plyrRnds_[_pID][_rID].genGuWithdraw); plyrRnds_[_pID][_rID].affWithdraw = plyr_[_pID].aff.add(plyrRnds_[_pID][_rID].affWithdraw); plyrRnds_[_pID][_rID].refundWithdraw = plyr_[_pID].refund.add(plyrRnds_[_pID][_rID].refundWithdraw); plyr_[_pID].withdraw = _earnings.add(plyr_[_pID].withdraw); round_[_rID].withdraw = _earnings.add(round_[_rID].withdraw); } plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].genGu = 0; plyr_[_pID].aff = 0; plyr_[_pID].refund = 0; } return(_earnings); } bool public activated_ = false; function activate() onlyOwner public { // can only be ran once require(activated_ == false); // activate the contract activated_ = true; contractStartDate_ = now; // lets start first round rID_ = 1; round_[1].strt = now; round_[1].end = now + rndInit_; } function leekStealGo() private { // get a number for today dayNum uint leekStealToday_ = (now.sub(round_[rID_].strt)) / 1 days; if (dayStealTime_[leekStealToday_] == 0) // if there hasn&#39;t a winner today, proceed { leekStealTracker_++; if (randomNum(leekStealTracker_) == true) { dayStealTime_[leekStealToday_] = now; leekStealOn_ = true; } } } function stealTheLeek() whenNotPaused_4 public { if (leekStealOn_) { if (now.sub(dayStealTime_[leekStealToday_]) > 300) // if time passed 5min, turn off and exit { leekStealOn_ = false; } else { // if yes then assign the 1eth, if the pool has 1eth if (leekStealPot_ > 1e18) { uint256 _pID = pIDxAddr_[msg.sender]; // fetch player ID plyr_[_pID].win = plyr_[_pID].win.add(1e18); leekStealPot_ = leekStealPot_.sub(1e18); leekStealWins_[_pID] = leekStealWins_[_pID].add(1e18); } } } } // Getters ==================== function getPrice() public view returns(uint256) { uint256 keys = keysRec(round_[rID_].eth, 1e18); return (1e36 / keys); } function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt).sub(_now) ); else return(0); } function getDisplayGenVault(uint256 _pID) private view returns(uint256) { uint256 _rID = rID_; uint256 _lrnd = plyr_[_pID].lrnd; uint256 _genVault = plyr_[_pID].gen; uint256 _genEarning = calcUnMaskedKeyEarnings(_pID, _lrnd); uint256 _doubleProfit = (plyrRnds_[_pID][_rID].eth).mul(2); uint256 _displayGenVault = _genVault.add(_genEarning); if (_genVault.add(_genEarning) > _doubleProfit) _displayGenVault = _doubleProfit; return _displayGenVault; } function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256, uint256, uint256) { uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { uint256 _winVault; if (round_[_rID].plyr == _pID) // if player is winner { _winVault = (plyr_[_pID].win).add( ((round_[_rID].pot).mul(40)) / 100 ); } else { _winVault = plyr_[_pID].win; } return ( _winVault, getDisplayGenVault(_pID), (plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)), plyr_[_pID].aff, plyr_[_pID].refund ); // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, getDisplayGenVault(_pID), (plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)), plyr_[_pID].aff, plyr_[_pID].refund ); } } function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( _rID, //0 round_[_rID].allkeys, //1 round_[_rID].keys, //2 allGuGiven_, //3 round_[_rID].end, //4 round_[_rID].strt, //5 round_[_rID].pot, //6 plyr_[round_[_rID].plyr].addr, //7 round_[_rID].eth, //8 airDropTracker_ + (airDropPot_ * 1000) //9 ); } function getCurrentPhraseInfo() public view returns(uint256, uint256, uint256, uint256, uint256) { // setup local phID uint256 _phID = phID_; return ( _phID, //0 phrase_[_phID].eth, //1 phrase_[_phID].guGiven, //2 phrase_[_phID].minEthRequired, //3 phrase_[_phID].guPoolAllocation //4 ); } function getPlayerInfoByAddress(address _addr) public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { // setup local rID, phID uint256 _rID = rID_; uint256 _phID = phID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, // 0 plyrRnds_[_pID][_rID].keys, //1 plyr_[_pID].gu, //2 plyr_[_pID].laff, //3 (plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd)).add(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth, //6 totalIn for the round plyrPhas_[_pID][_phID].eth, //7 curr phrase referral eth plyr_[_pID].referEth, // 8 total referral eth plyr_[_pID].withdraw // 9 totalOut ); } function getPlayerWithdrawal(uint256 _pID, uint256 _rID) public view returns(uint256, uint256, uint256, uint256, uint256) { return ( plyrRnds_[_pID][_rID].winWithdraw, //0 plyrRnds_[_pID][_rID].genWithdraw, //1 plyrRnds_[_pID][_rID].genGuWithdraw, //2 plyrRnds_[_pID][_rID].affWithdraw, //3 plyrRnds_[_pID][_rID].refundWithdraw //4 ); } } library Datasets { struct Player { address addr; // player address uint256 win; // winnings vault uint256 gen; // general vault uint256 genGu; // general gu vault uint256 aff; // affiliate vault uint256 refund; // refund vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used uint256 withdraw; // sum of withdraw uint256 maskGu; // player mask gu: for sharing eth-profit by holding gu uint256 gu; uint256 guProfit; // record profit by gu uint256 referEth; // total referral eth uint256 lastClaimedPhID; // at which phID player has claimed the remaining gu } struct PlayerRounds { uint256 eth; // eth player has added to round uint256 keys; // keys uint256 keyProfit; // record key profit uint256 maskKey; // player mask key: for sharing eth-profit by holding keys uint256 winWithdraw; // eth withdraw from gen vault uint256 genWithdraw; // eth withdraw from gen vault uint256 genGuWithdraw; // eth withdraw from gen vault uint256 affWithdraw; // eth withdraw from gen vault uint256 refundWithdraw; // eth withdraw from gen vault } struct Round { uint256 plyr; // pID of player in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 allkeys; // all keys uint256 keys; // active keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 maskKey; // global mask on key shares: for sharing eth-profit by holding keys uint256 playCtr; // play counter for playOrders uint256 withdraw; } struct PlayerPhrases { uint256 eth; // amount of eth in of the referral uint256 guRewarded; // if have taken the gu through referral } struct Phrase { uint256 eth; // amount of total eth in of the referral uint256 guGiven; // amount of gu distributed uint256 mask; // a rate of remainGu per ethIn shares: for sharing gu-reward by referral eth uint256 minEthRequired; // min refer.eth to get 1 gu uint256 guPoolAllocation; // total number of gu } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
total referral eth
uint256 referEth;
2,160,837
[ 1, 4963, 1278, 29084, 13750, 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, 3639, 2254, 5034, 8884, 41, 451, 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 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./interfaces/IERC20MintBurn.sol"; import "./interfaces/IJamonVesting.sol"; interface IJamonShareVault { function totalStaked() external returns (uint256); } /** * @title JamonVesting * @notice Lock JamonV2 token rewards for 12 months. */ contract JamonVesting is IJamonVesting, Ownable, ReentrancyGuard, Pausable { //---------- Libraries ----------// using SafeMath for uint256; using SafeERC20 for IERC20MintBurn; using Counters for Counters.Counter; //---------- Contracts ----------// IERC20MintBurn private immutable jamonV2; // JamonV2 ERC20 contract IJamonShareVault private JamonShareVault; // JamonShare ERC20 contract address private bonus; // Address of Bonus contract //---------- Variables ----------// uint256 private vestingSchedulesTotalAmount; // Total JamonV2 token vested uint256 private constant month = 2629743 ; // 1 Month Timestamp. Counters.Counter private deposits; // Counter for a control of deposits, max 12 deposits one per month. uint256 public lastDeposit; // Last deposit in timestamp //---------- Storage -----------// struct VestingSchedule { bool initialized; // beneficiary of tokens after they are released address beneficiary; // cliff period in seconds uint256 cliff; // start time of the vesting period uint256 start; // total amount of tokens to be released at the end of the vesting uint256 amountTotal; // amount of tokens released uint256 released; } bytes32[] private vestingSchedulesIds; mapping(bytes32 => VestingSchedule) private vestingSchedules; mapping(address => uint256) private holdersVestingCount; //---------- Events -----------// event Vested(address indexed beneficiary, uint256 amount); event Released(address indexed beneficiary, uint256 amount); //---------- Constructor ----------// constructor(address jamonv2_) { require(jamonv2_ != address(0x0), "Invalid address"); jamonV2 = IERC20MintBurn(jamonv2_); lastDeposit = block.timestamp.add(40 days); } function initialize(address bonus_, address jsVault_) external onlyOwner { require(bonus == address(0x0), "Already initialized"); require( bonus_ != address(0x0) && jsVault_ != address(0x0), "Invalid address" ); bonus = bonus_; JamonShareVault = IJamonShareVault(jsVault_); } //---------- Modifiers ----------// /** * @dev Reverts if the vesting schedule does not exist. */ modifier onlyIfVestingSchedule(bytes32 vestingScheduleId) { require(vestingSchedules[vestingScheduleId].initialized == true, "Invalid Id"); _; } /** * @dev Reverts if the vesting schedule does not exist. */ modifier onlyBonus() { require(_msgSender() == bonus, "Forbidden address"); _; } //----------- Internal Functions -----------// /** * @dev Computes the releasable amount of tokens for a vesting schedule. * @return the amount of releasable tokens */ function _computeReleasableAmount(VestingSchedule memory vestingSchedule) internal view returns (uint256) { uint256 currentTime = getCurrentTime(); if ((currentTime < vestingSchedule.cliff)) { return 0; } else if (currentTime >= vestingSchedule.start.add(month.mul(12))) { return vestingSchedule.amountTotal.sub(vestingSchedule.released); } else { uint256 timeFromStart = currentTime.sub(vestingSchedule.start); uint256 vestedSlicePeriods = timeFromStart.div(month); uint256 vestedSeconds = vestedSlicePeriods.mul(month); uint256 vestedAmount = vestingSchedule .amountTotal .mul(vestedSeconds) .div(month.mul(12)); vestedAmount = vestedAmount.sub(vestingSchedule.released); return vestedAmount; } } function getCurrentTime() internal view virtual returns (uint256) { return block.timestamp; } //----------- External Functions -----------// /** * @dev Returns the number of deposits sended to Jamon Share Vault. * @return the number of deposits to JamonShareVault */ function depositsCount() external view override returns (uint256) { return deposits.current(); } /** * @dev Returns the number of vesting schedules associated to a beneficiary. * @return the number of vesting schedules */ function getVestingSchedulesCountByBeneficiary(address _beneficiary) external view returns (uint256) { return holdersVestingCount[_beneficiary]; } /** * @dev Returns the vesting schedule id at the given index. * @return the vesting id */ function getVestingIdAtIndex(uint256 index) external view returns (bytes32) { require( index < getVestingSchedulesCount(), "JamonVesting: index out of bounds" ); return vestingSchedulesIds[index]; } /** * @notice Returns the vesting schedule information for a given holder and index. * @return the vesting schedule structure information */ function getVestingScheduleByAddressAndIndex(address holder, uint256 index) external view returns (VestingSchedule memory) { return getVestingSchedule( computeVestingScheduleIdForAddressAndIndex(holder, index) ); } /** * @notice Returns the total amount of vesting schedules. * @return the total amount of vesting schedules */ function getVestingSchedulesTotalAmount() external view returns (uint256) { return vestingSchedulesTotalAmount; } /** * @dev Returns the address of the ERC20 token managed by the vesting contract. */ function getToken() external view returns (address) { return address(jamonV2); } /** * @notice Creates a new vesting schedule for a beneficiary. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _amount total amount of tokens to be released at the end of the vesting */ function createVestingSchedule(address _beneficiary, uint256 _amount) public override whenNotPaused onlyBonus { require(_amount > 0, "JamonVesting: amount must be > 0"); bytes32 vestingScheduleId = this.computeNextVestingScheduleIdForHolder( _beneficiary ); uint256 start = block.timestamp; uint256 cliff = start.add(month); vestingSchedules[vestingScheduleId] = VestingSchedule( true, _beneficiary, cliff, start, _amount, 0 ); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.add(_amount); vestingSchedulesIds.push(vestingScheduleId); uint256 currentVestingCount = holdersVestingCount[_beneficiary]; holdersVestingCount[_beneficiary] = currentVestingCount.add(1); } /** * @notice Release vested amount of tokens. * @param vestingScheduleId the vesting schedule identifier * @param amount the amount to release */ function release(bytes32 vestingScheduleId, uint256 amount) public nonReentrant whenNotPaused onlyIfVestingSchedule(vestingScheduleId) { VestingSchedule storage v = vestingSchedules[vestingScheduleId]; bool isBeneficiary = msg.sender == v.beneficiary; require( isBeneficiary, "JamonVesting: only beneficiary and owner can release vested tokens" ); uint256 vestedAmount = _computeReleasableAmount(v); require( vestedAmount >= amount, "JamonVesting: cannot release tokens, not enough vested tokens" ); v.released = v.released.add(amount); address payable beneficiaryPayable = payable(v.beneficiary); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount.sub(amount); if (v.released >= v.amountTotal) { delete vestingSchedules[vestingScheduleId]; } jamonV2.mint(beneficiaryPayable, amount); emit Released(beneficiaryPayable, amount); } /** * @dev Returns the number of vesting schedules managed by this contract. * @return the number of vesting schedules */ function getVestingSchedulesCount() public view returns (uint256) { return vestingSchedulesIds.length; } /** * @notice Computes the vested amount of tokens for the given vesting schedule identifier. * @return the vested amount */ function computeReleasableAmount(bytes32 vestingScheduleId) public view onlyIfVestingSchedule(vestingScheduleId) returns (uint256) { VestingSchedule storage vestingSchedule = vestingSchedules[ vestingScheduleId ]; return _computeReleasableAmount(vestingSchedule); } /** * @notice Returns the vesting schedule information for a given identifier. * @return the vesting schedule structure information */ function getVestingSchedule(bytes32 vestingScheduleId) public view returns (VestingSchedule memory) { return vestingSchedules[vestingScheduleId]; } /** * @dev Computes the next vesting schedule identifier for a given holder address. */ function computeNextVestingScheduleIdForHolder(address holder) public view returns (bytes32) { return computeVestingScheduleIdForAddressAndIndex( holder, holdersVestingCount[holder] ); } /** * @dev Returns the last vesting schedule for a given holder address. */ function getLastVestingScheduleForHolder(address holder) public view returns (VestingSchedule memory) { return vestingSchedules[ computeVestingScheduleIdForAddressAndIndex( holder, holdersVestingCount[holder] - 1 ) ]; } /** * @dev Computes the vesting schedule identifier for an address and an index. */ function computeVestingScheduleIdForAddressAndIndex( address holder, uint256 index ) public pure returns (bytes32) { return keccak256(abi.encodePacked(holder, index)); } function depositToVault() external nonReentrant whenNotPaused { require(lastDeposit.add(month) < block.timestamp, "Is soon"); require(deposits.current() < 12, "All deposits done"); lastDeposit = block.timestamp; deposits.increment(); uint256 totalStaked = JamonShareVault.totalStaked(); uint256 toVault = totalStaked.mul(50); jamonV2.mint(address(JamonShareVault), toVault); } /** * @notice Functions for pause and unpause the contract. */ function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } }
----------- External Functions -----------* @dev Returns the number of deposits sended to Jamon Share Vault. @return the number of deposits to JamonShareVault/
function depositsCount() external view override returns (uint256) { return deposits.current(); }
984,133
[ 1, 13849, 11352, 15486, 300, 15392, 225, 2860, 326, 1300, 434, 443, 917, 1282, 272, 3934, 358, 804, 301, 265, 25805, 17329, 18, 327, 326, 1300, 434, 443, 917, 1282, 358, 804, 301, 265, 9535, 12003, 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, 443, 917, 1282, 1380, 1435, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 443, 917, 1282, 18, 2972, 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 ]
//Address: 0x1d97bccc6296aac6f0be796c7e8cb270eca4c6c6 //Contract name: AquaToken //Balance: 0 Ether //Verification Date: 3/31/2018 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.20; contract Owned { address public owner; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface Token { function totalSupply() constant external returns (uint256); function transfer(address receiver, uint amount) external returns (bool success); function burn(uint256 _value) external returns (bool success); function startTrading() external; } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } interface AquaPriceOracle { function getAudCentWeiPrice() external constant returns (uint); function getAquaTokenAudCentsPrice() external constant returns (uint); event NewPrice(uint _audCentWeiPrice, uint _aquaTokenAudCentsPrice); } /* file: LibCLL.sol ver: 0.4.0 updated:31-Mar-2016 author: Darryl Morris email: o0ragman0o AT gmail.com A Solidity library for implementing a data indexing regime using a circular linked list. This library provisions lookup, navigation and key/index storage functionality which can be used in conjunction with an array or mapping. NOTICE: This library uses internal functions only and so cannot be compiled and deployed independently from its calling contract. This software 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 MIT Licence for further details. <https://opensource.org/licenses/MIT>. */ // LibCLL using `uint` keys library LibCLLu { string constant public VERSION = "LibCLLu 0.4.0"; uint constant NULL = 0; uint constant HEAD = 0; bool constant PREV = false; bool constant NEXT = true; struct CLL{ mapping (uint => mapping (bool => uint)) cll; } // n: node id d: direction r: return node id // Return existential state of a node. n == HEAD returns list existence. function exists(CLL storage self, uint n) internal constant returns (bool) { if (self.cll[n][PREV] != HEAD || self.cll[n][NEXT] != HEAD) return true; if (n == HEAD) return false; if (self.cll[HEAD][NEXT] == n) return true; return false; } // Returns the number of elements in the list function sizeOf(CLL storage self) internal constant returns (uint r) { uint i = step(self, HEAD, NEXT); while (i != HEAD) { i = step(self, i, NEXT); r++; } return; } // Returns the links of a node as and array function getNode(CLL storage self, uint n) internal constant returns (uint[2]) { return [self.cll[n][PREV], self.cll[n][NEXT]]; } // Returns the link of a node `n` in direction `d`. function step(CLL storage self, uint n, bool d) internal constant returns (uint) { return self.cll[n][d]; } // Can be used before `insert` to build an ordered list // `a` an existing node to search from, e.g. HEAD. // `b` value to seek // `r` first node beyond `b` in direction `d` function seek(CLL storage self, uint a, uint b, bool d) internal constant returns (uint r) { r = step(self, a, d); while ((b!=r) && ((b < r) != d)) r = self.cll[r][d]; return; } // Creates a bidirectional link between two nodes on direction `d` function stitch(CLL storage self, uint a, uint b, bool d) internal { self.cll[b][!d] = a; self.cll[a][d] = b; } // Insert node `b` beside existing node `a` in direction `d`. function insert (CLL storage self, uint a, uint b, bool d) internal { uint c = self.cll[a][d]; stitch (self, a, b, d); stitch (self, b, c, d); } function remove(CLL storage self, uint n) internal returns (uint) { if (n == NULL) return; stitch(self, self.cll[n][PREV], self.cll[n][NEXT], NEXT); delete self.cll[n][PREV]; delete self.cll[n][NEXT]; return n; } function push(CLL storage self, uint n, bool d) internal { insert(self, HEAD, n, d); } function pop(CLL storage self, bool d) internal returns (uint) { return remove(self, step(self, HEAD, d)); } } // LibCLL using `int` keys library LibCLLi { string constant public VERSION = "LibCLLi 0.4.0"; int constant NULL = 0; int constant HEAD = 0; bool constant PREV = false; bool constant NEXT = true; struct CLL{ mapping (int => mapping (bool => int)) cll; } // n: node id d: direction r: return node id // Return existential state of a node. n == HEAD returns list existence. function exists(CLL storage self, int n) internal constant returns (bool) { if (self.cll[n][PREV] != HEAD || self.cll[n][NEXT] != HEAD) return true; if (n == HEAD) return false; if (self.cll[HEAD][NEXT] == n) return true; return false; } // Returns the number of elements in the list function sizeOf(CLL storage self) internal constant returns (uint r) { int i = step(self, HEAD, NEXT); while (i != HEAD) { i = step(self, i, NEXT); r++; } return; } // Returns the links of a node as and array function getNode(CLL storage self, int n) internal constant returns (int[2]) { return [self.cll[n][PREV], self.cll[n][NEXT]]; } // Returns the link of a node `n` in direction `d`. function step(CLL storage self, int n, bool d) internal constant returns (int) { return self.cll[n][d]; } // Can be used before `insert` to build an ordered list // `a` an existing node to search from, e.g. HEAD. // `b` value to seek // `r` first node beyond `b` in direction `d` function seek(CLL storage self, int a, int b, bool d) internal constant returns (int r) { r = step(self, a, d); while ((b!=r) && ((b < r) != d)) r = self.cll[r][d]; return; } // Creates a bidirectional link between two nodes on direction `d` function stitch(CLL storage self, int a, int b, bool d) internal { self.cll[b][!d] = a; self.cll[a][d] = b; } // Insert node `b` beside existing node `a` in direction `d`. function insert (CLL storage self, int a, int b, bool d) internal { int c = self.cll[a][d]; stitch (self, a, b, d); stitch (self, b, c, d); } function remove(CLL storage self, int n) internal returns (int) { if (n == NULL) return; stitch(self, self.cll[n][PREV], self.cll[n][NEXT], NEXT); delete self.cll[n][PREV]; delete self.cll[n][NEXT]; return n; } function push(CLL storage self, int n, bool d) internal { insert(self, HEAD, n, d); } function pop(CLL storage self, bool d) internal returns (int) { return remove(self, step(self, HEAD, d)); } } // LibCLL using `address` keys library LibCLLa { string constant public VERSION = "LibCLLa 0.4.0"; address constant NULL = 0; address constant HEAD = 0; bool constant PREV = false; bool constant NEXT = true; struct CLL{ mapping (address => mapping (bool => address)) cll; } // n: node id d: direction r: return node id // Return existential state of a node. n == HEAD returns list existence. function exists(CLL storage self, address n) internal constant returns (bool) { if (self.cll[n][PREV] != HEAD || self.cll[n][NEXT] != HEAD) return true; if (n == HEAD) return false; if (self.cll[HEAD][NEXT] == n) return true; return false; } // Returns the number of elements in the list function sizeOf(CLL storage self) internal constant returns (uint r) { address i = step(self, HEAD, NEXT); while (i != HEAD) { i = step(self, i, NEXT); r++; } return; } // Returns the links of a node as and array function getNode(CLL storage self, address n) internal constant returns (address[2]) { return [self.cll[n][PREV], self.cll[n][NEXT]]; } // Returns the link of a node `n` in direction `d`. function step(CLL storage self, address n, bool d) internal constant returns (address) { return self.cll[n][d]; } // Can be used before `insert` to build an ordered list // `a` an existing node to search from, e.g. HEAD. // `b` value to seek // `r` first node beyond `b` in direction `d` function seek(CLL storage self, address a, address b, bool d) internal constant returns (address r) { r = step(self, a, d); while ((b!=r) && ((b < r) != d)) r = self.cll[r][d]; return; } // Creates a bidirectional link between two nodes on direction `d` function stitch(CLL storage self, address a, address b, bool d) internal { self.cll[b][!d] = a; self.cll[a][d] = b; } // Insert node `b` beside existing node `a` in direction `d`. function insert (CLL storage self, address a, address b, bool d) internal { address c = self.cll[a][d]; stitch (self, a, b, d); stitch (self, b, c, d); } function remove(CLL storage self, address n) internal returns (address) { if (n == NULL) return; stitch(self, self.cll[n][PREV], self.cll[n][NEXT], NEXT); delete self.cll[n][PREV]; delete self.cll[n][NEXT]; return n; } function push(CLL storage self, address n, bool d) internal { insert(self, HEAD, n, d); } function pop(CLL storage self, bool d) internal returns (address) { return remove(self, step(self, HEAD, d)); } } library LibHoldings { using LibCLLa for LibCLLa.CLL; bool constant PREV = false; bool constant NEXT = true; struct Holding { uint totalTokens; uint lockedTokens; uint weiBalance; uint lastRewardNumber; } struct HoldingsSet { LibCLLa.CLL keys; mapping (address => Holding) holdings; } function exists(HoldingsSet storage self, address holder) internal constant returns (bool) { return self.keys.exists(holder); } function add(HoldingsSet storage self, address holder, Holding h) internal { self.keys.push(holder, PREV); self.holdings[holder] = h; } function get(HoldingsSet storage self, address holder) constant internal returns (Holding storage) { require(self.keys.exists(holder)); return self.holdings[holder]; } function remove(HoldingsSet storage self, address holder) internal { require(self.keys.exists(holder)); delete self.holdings[holder]; self.keys.remove(holder); } function firstHolder(HoldingsSet storage self) internal constant returns (address) { return self.keys.step(0x0, NEXT); } function nextHolder(HoldingsSet storage self, address currentHolder) internal constant returns (address) { return self.keys.step(currentHolder, NEXT); } } library LibRedemptions { using LibCLLu for LibCLLu.CLL; bool constant PREV = false; bool constant NEXT = true; struct Redemption { uint256 Id; address holderAddress; uint256 numberOfTokens; } struct RedemptionsQueue { uint256 redemptionRequestsCounter; LibCLLu.CLL keys; mapping (uint => Redemption) queue; } function exists(RedemptionsQueue storage self, uint id) internal constant returns (bool) { return self.keys.exists(id); } function add(RedemptionsQueue storage self, address holder, uint _numberOfTokens) internal returns(uint) { Redemption memory r = Redemption({ Id: ++self.redemptionRequestsCounter, holderAddress: holder, numberOfTokens: _numberOfTokens }); self.queue[r.Id] = r; self.keys.push(r.Id, PREV); return r.Id; } function get(RedemptionsQueue storage self, uint id) internal constant returns (Redemption storage) { require(self.keys.exists(id)); return self.queue[id]; } function remove(RedemptionsQueue storage self, uint id) internal { require(self.keys.exists(id)); delete self.queue[id]; self.keys.remove(id); } function firstRedemption(RedemptionsQueue storage self) internal constant returns (uint) { return self.keys.step(0x0, NEXT); } function nextRedemption(RedemptionsQueue storage self, uint currentId) internal constant returns (uint) { return self.keys.step(currentId, NEXT); } } contract AquaToken is Owned, Token { //imports using SafeMath for uint256; using LibHoldings for LibHoldings.Holding; using LibHoldings for LibHoldings.HoldingsSet; using LibRedemptions for LibRedemptions.Redemption; using LibRedemptions for LibRedemptions.RedemptionsQueue; //inner types struct DistributionContext { uint distributionAmount; uint receivedRedemptionAmount; uint redemptionAmount; uint tokenPriceWei; uint currentRedemptionId; uint totalRewardAmount; } struct WindUpContext { uint totalWindUpAmount; uint tokenReward; uint paidReward; address currenHolderAddress; } //constants bool constant PREV = false; bool constant NEXT = true; //state enum TokenStatus { OnSale, Trading, Distributing, WindingUp } ///Status of the token contract TokenStatus public tokenStatus; ///Aqua Price Oracle smart contract AquaPriceOracle public priceOracle; LibHoldings.HoldingsSet internal holdings; uint256 internal totalSupplyOfTokens; LibRedemptions.RedemptionsQueue redemptionsQueue; ///The whole percentage number (0-100) of the total distributable profit ///amount available for token redemption in each profit distribution round uint8 public redemptionPercentageOfDistribution; mapping (address => mapping (address => uint256)) internal allowances; uint [] internal rewards; DistributionContext internal distCtx; WindUpContext internal windUpCtx; //ERC-20 ///Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); ///Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); ///Token name string public name; ///Token symbol string public symbol; ///Number of decimals uint8 public decimals; ///Returns total supply of Aqua Tokens function totalSupply() constant external returns (uint256) { return totalSupplyOfTokens; } /// Get the token balance for address _owner function balanceOf(address _owner) public constant returns (uint256 balance) { if (!holdings.exists(_owner)) return 0; LibHoldings.Holding storage h = holdings.get(_owner); return h.totalTokens.sub(h.lockedTokens); } ///Transfer the balance from owner's account to another account function transfer(address _to, uint256 _value) external returns (bool success) { return _transfer(msg.sender, _to, _value); } /// Send _value amount of tokens from address _from to address _to /// The transferFrom method is used for a withdraw workflow, allowing contracts to send /// tokens on your behalf, for example to "deposit" to a contract address and/or to charge /// fees in sub-currencies; the command should fail unless the _from account has /// deliberately authorized the sender of the message via some mechanism; function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowances[_from][msg.sender]); // Check allowance allowances[_from][msg.sender] = allowances[_from][msg.sender].sub( _value); return _transfer(_from, _to, _value); } /// Allow _spender to withdraw from your account, multiple times, up to the _value amount. /// If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _value) public returns (bool success) { if (tokenStatus == TokenStatus.OnSale) { require(msg.sender == owner); } allowances[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// Returns the amount that _spender is allowed to withdraw from _owner account. function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowances[_owner][_spender]; } //custom public interface ///Event is fired when holder requests to redeem their tokens ///@param holder Account address of token holder requesting redemption ///@param _numberOfTokens Number of tokens requested ///@param _requestId ID assigned to the redemption request event RequestRedemption(address holder, uint256 _numberOfTokens, uint _requestId); ///Event is fired when holder cancels redemption request with ID = _requestId ///@param holder Account address of token holder cancelling redemption request ///@param _numberOfTokens Number of tokens affected ///@param _requestId ID of the redemption request that was cancelled event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId); ///Event occurs when the redemption request is redeemed. ///@param holder Account address of the token holder whose tokens were redeemed ///@param _requestId The ID of the redemption request ///@param _numberOfTokens The number of tokens redeemed ///@param amount The redeemed amount in Wei event HolderRedemption(address holder, uint _requestId, uint256 _numberOfTokens, uint amount); ///Event occurs when profit distribution is triggered ///@param amount Total amount (in Wei) available for this profit distribution round event DistributionStarted(uint amount); ///Event occurs when profit distribution round completes ///@param redeemedAmount Total amount (in wei) redeemed in this distribution round ///@param rewardedAmount Total amount rewarded as dividends in this distribution round ///@param remainingAmount Any minor remaining amount (due to rounding errors) that has been distributed back to iAqua event DistributionCompleted(uint redeemedAmount, uint rewardedAmount, uint remainingAmount); ///Event is triggered when token holder withdraws their balance ///@param holderAddress Address of the token holder account ///@param amount Amount in wei that has been withdrawn ///@param hasRemainingBalance True if there is still remaining balance event WithdrawBalance(address holderAddress, uint amount, bool hasRemainingBalance); ///Occurs when contract owner (iAqua) repeatedly calls continueDistribution to progress redemption and ///dividend payments during profit distribution round ///@param _continue True if the distribution hasn’t completed as yet event ContinueDistribution(bool _continue); ///The event is fired when wind-up procedure starts ///@param amount Total amount in Wei available for final distribution among token holders event WindingUpStarted(uint amount); ///Event is triggered when smart contract transitions into Trading state when trading and token transfers is allowed event StartTrading(); ///Event is triggered when a token holders destroys their tokens ///@param from Account address of the token holder ///@param numberOfTokens Number of tokens burned (permanently destroyed) event Burn(address indexed from, uint256 numberOfTokens); /// Constructor initializes the contract ///@param initialSupply Initial supply of tokens ///@param tokenName Display name if the token ///@param tokenSymbol Token symbol ///@param decimalUnits Number of decimal points for token holding display ///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round function AquaToken(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits, uint8 _redemptionPercentageOfDistribution, address _priceOracle ) public { totalSupplyOfTokens = initialSupply; holdings.add(msg.sender, LibHoldings.Holding({ totalTokens : initialSupply, lockedTokens : 0, lastRewardNumber : 0, weiBalance : 0 })); name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution; priceOracle = AquaPriceOracle(_priceOracle); owner = msg.sender; tokenStatus = TokenStatus.OnSale; rewards.push(0); } ///Called by token owner enable trading with tokens function startTrading() onlyOwner external { require(tokenStatus == TokenStatus.OnSale); tokenStatus = TokenStatus.Trading; StartTrading(); } ///Token holders can call this function to request to redeem (sell back to ///the company) part or all of their tokens ///@param _numberOfTokens Number of tokens to redeem ///@return Redemption request ID (required in order to cancel this redemption request) function requestRedemption(uint256 _numberOfTokens) public returns (uint) { require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0); LibHoldings.Holding storage h = holdings.get(msg.sender); require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens); h.lockedTokens = h.lockedTokens.add(_numberOfTokens); RequestRedemption(msg.sender, _numberOfTokens, redemptionId); return redemptionId; } ///Token holders can call this function to cancel a redemption request they ///previously submitted using requestRedemption function ///@param _requestId Redemption request ID function cancelRedemptionRequest(uint256 _requestId) public { require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId)); LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId); require(r.holderAddress == msg.sender); LibHoldings.Holding storage h = holdings.get(msg.sender); h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens); uint numberOfTokens = r.numberOfTokens; redemptionsQueue.remove(_requestId); CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId); } ///The function is used to enumerate redemption requests. It returns the first redemption request ID. ///@return First redemption request ID function firstRedemptionRequest() public constant returns (uint) { return redemptionsQueue.firstRedemption(); } ///The function is used to enumerate redemption requests. It returns the ///next redemption request ID following the supplied one. ///@param _currentRedemptionId Current redemption request ID ///@return Next redemption request ID function nextRedemptionRequest(uint _currentRedemptionId) public constant returns (uint) { return redemptionsQueue.nextRedemption(_currentRedemptionId); } ///The function returns redemption request details for the supplied redemption request ID ///@param _requestId Redemption request ID ///@return _holderAddress Token holder account address ///@return _numberOfTokens Number of tokens requested to redeem function getRedemptionRequest(uint _requestId) public constant returns (address _holderAddress, uint256 _numberOfTokens) { LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId); _holderAddress = r.holderAddress; _numberOfTokens = r.numberOfTokens; } ///The function is used to enumerate token holders. It returns the first ///token holder (that the enumeration starts from) ///@return Account address of the first token holder function firstHolder() public constant returns (address) { return holdings.firstHolder(); } ///The function is used to enumerate token holders. It returns the address ///of the next token holder given the token holder address. ///@param _currentHolder Account address of the token holder ///@return Account address of the next token holder function nextHolder(address _currentHolder) public constant returns (address) { return holdings.nextHolder(_currentHolder); } ///The function returns token holder details given token holder account address ///@param _holder Account address of a token holder ///@return totalTokens Total tokens held by this token holder ///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed ///@return weiBalance Wei balance of the token holder available for withdrawal. function getHolding(address _holder) public constant returns (uint totalTokens, uint lockedTokens, uint weiBalance) { if (!holdings.exists(_holder)) { totalTokens = 0; lockedTokens = 0; weiBalance = 0; return; } LibHoldings.Holding storage h = holdings.get(_holder); totalTokens = h.totalTokens; lockedTokens = h.lockedTokens; uint stepsMade; (weiBalance, stepsMade) = calcFullWeiBalance(h, 0); return; } ///Token owner calls this function to start profit distribution round function startDistribuion() onlyOwner public payable { require(tokenStatus == TokenStatus.Trading); tokenStatus = TokenStatus.Distributing; startRedemption(msg.value); DistributionStarted(msg.value); } ///Token owner calls this function to progress profit distribution round ///@param maxNumbeOfSteps Maximum number of steps in this progression ///@return False in case profit distribution round has completed function continueDistribution(uint maxNumbeOfSteps) public returns (bool) { require(tokenStatus == TokenStatus.Distributing); if (continueRedeeming(maxNumbeOfSteps)) { ContinueDistribution(true); return true; } uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens ); rewards.push(tokenReward); uint paidReward = tokenReward.mul(totalSupplyOfTokens); uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward); if (unusedDistributionAmount > 0) { if (!holdings.exists(owner)) { holdings.add(owner, LibHoldings.Holding({ totalTokens : 0, lockedTokens : 0, lastRewardNumber : rewards.length.sub(1), weiBalance : unusedDistributionAmount })); } else { LibHoldings.Holding storage ownerHolding = holdings.get(owner); ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount); } } tokenStatus = TokenStatus.Trading; DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount), paidReward, unusedDistributionAmount); ContinueDistribution(false); return false; } ///Token holder can call this function to withdraw their balance (dividend ///and redemption payments) while limiting the number of operations (in the ///extremely unlikely case when withdrawBalance function exceeds gas limit) ///@param maxSteps Maximum number of steps to take while withdrawing holder balance function withdrawBalanceMaxSteps(uint maxSteps) public { require(holdings.exists(msg.sender)); LibHoldings.Holding storage h = holdings.get(msg.sender); uint updatedBalance; uint stepsMade; (updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps); h.weiBalance = 0; h.lastRewardNumber = h.lastRewardNumber.add(stepsMade); bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1); if (h.totalTokens == 0 && h.weiBalance == 0) holdings.remove(msg.sender); msg.sender.transfer(updatedBalance); WithdrawBalance(msg.sender, updatedBalance, balanceRemainig); } ///Token holder can call this function to withdraw their balance (dividend ///and redemption payments) function withdrawBalance() public { withdrawBalanceMaxSteps(0); } ///Set allowance for other address and notify ///Allows _spender to spend no more than _value tokens on your behalf, and then ping the contract about it ///@param _spender The address authorized to spend ///@param _value the max amount they can spend ///@param _extraData some extra information to send to the approved contract function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { TokenRecipient spender = TokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } ///Token holders can call this method to permanently destroy their tokens. ///WARNING: Burned tokens cannot be recovered! ///@param numberOfTokens Number of tokens to burn (permanently destroy) ///@return True if operation succeeds function burn(uint256 numberOfTokens) external returns (bool success) { require(holdings.exists(msg.sender)); if (numberOfTokens == 0) { Burn(msg.sender, numberOfTokens); return true; } LibHoldings.Holding storage fromHolding = holdings.get(msg.sender); require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough updateWeiBalance(fromHolding, 0); fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0) holdings.remove(msg.sender); totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens); Burn(msg.sender, numberOfTokens); return true; } ///Token owner to call this to initiate final distribution in case of project wind-up function windUp() onlyOwner public payable { require(tokenStatus == TokenStatus.Trading); tokenStatus = TokenStatus.WindingUp; uint totalWindUpAmount = msg.value; uint tokenReward = msg.value.div(totalSupplyOfTokens); rewards.push(tokenReward); uint paidReward = tokenReward.mul(totalSupplyOfTokens); uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward); if (unusedWindUpAmount > 0) { if (!holdings.exists(owner)) { holdings.add(owner, LibHoldings.Holding({ totalTokens : 0, lockedTokens : 0, lastRewardNumber : rewards.length.sub(1), weiBalance : unusedWindUpAmount })); } else { LibHoldings.Holding storage ownerHolding = holdings.get(owner); ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount); } } WindingUpStarted(msg.value); } //internal functions function calcFullWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal constant returns(uint updatedBalance, uint stepsMade) { uint fromRewardIdx = holding.lastRewardNumber.add(1); updatedBalance = holding.weiBalance; if (fromRewardIdx == rewards.length) { stepsMade = 0; return; } uint toRewardIdx; if (maxSteps == 0) { toRewardIdx = rewards.length.sub( 1); } else { toRewardIdx = fromRewardIdx.add( maxSteps ).sub(1); if (toRewardIdx > rewards.length.sub(1)) { toRewardIdx = rewards.length.sub(1); } } for(uint idx = fromRewardIdx; idx <= toRewardIdx; idx = idx.add(1)) { updatedBalance = updatedBalance.add( rewards[idx].mul( holding.totalTokens ) ); } stepsMade = toRewardIdx.sub( fromRewardIdx ).add( 1 ); return; } function updateWeiBalance(LibHoldings.Holding storage holding, uint maxSteps) internal returns(uint updatedBalance, uint stepsMade) { (updatedBalance, stepsMade) = calcFullWeiBalance(holding, maxSteps); if (stepsMade == 0) return; holding.weiBalance = updatedBalance; holding.lastRewardNumber = holding.lastRewardNumber.add(stepsMade); } function startRedemption(uint distributionAmount) internal { distCtx.distributionAmount = distributionAmount; distCtx.receivedRedemptionAmount = (distCtx.distributionAmount.mul(redemptionPercentageOfDistribution)).div(100); distCtx.redemptionAmount = distCtx.receivedRedemptionAmount; distCtx.tokenPriceWei = priceOracle.getAquaTokenAudCentsPrice().mul(priceOracle.getAudCentWeiPrice()); distCtx.currentRedemptionId = redemptionsQueue.firstRedemption(); } function continueRedeeming(uint maxNumbeOfSteps) internal returns (bool) { uint remainingNoSteps = maxNumbeOfSteps; uint currentId = distCtx.currentRedemptionId; uint redemptionAmount = distCtx.redemptionAmount; uint totalRedeemedTokens = 0; while(currentId != 0 && redemptionAmount > 0) { if (remainingNoSteps == 0) { distCtx.currentRedemptionId = currentId; distCtx.redemptionAmount = redemptionAmount; if (totalRedeemedTokens > 0) { totalSupplyOfTokens = totalSupplyOfTokens.sub( totalRedeemedTokens ); } return true; } if (redemptionAmount.div(distCtx.tokenPriceWei) < 1) break; LibRedemptions.Redemption storage r = redemptionsQueue.get(currentId); LibHoldings.Holding storage holding = holdings.get(r.holderAddress); uint updatedBalance; uint stepsMade; (updatedBalance, stepsMade) = updateWeiBalance(holding, remainingNoSteps); remainingNoSteps = remainingNoSteps.sub(stepsMade); if (remainingNoSteps == 0) { distCtx.currentRedemptionId = currentId; distCtx.redemptionAmount = redemptionAmount; if (totalRedeemedTokens > 0) { totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens); } return true; } uint holderTokensToRedeem = redemptionAmount.div(distCtx.tokenPriceWei); if (holderTokensToRedeem > r.numberOfTokens) holderTokensToRedeem = r.numberOfTokens; uint holderRedemption = holderTokensToRedeem.mul(distCtx.tokenPriceWei); holding.weiBalance = holding.weiBalance.add( holderRedemption ); redemptionAmount = redemptionAmount.sub( holderRedemption ); r.numberOfTokens = r.numberOfTokens.sub( holderTokensToRedeem ); holding.totalTokens = holding.totalTokens.sub(holderTokensToRedeem); holding.lockedTokens = holding.lockedTokens.sub(holderTokensToRedeem); totalRedeemedTokens = totalRedeemedTokens.add( holderTokensToRedeem ); uint nextId = redemptionsQueue.nextRedemption(currentId); HolderRedemption(r.holderAddress, currentId, holderTokensToRedeem, holderRedemption); if (r.numberOfTokens == 0) redemptionsQueue.remove(currentId); currentId = nextId; remainingNoSteps = remainingNoSteps.sub(1); } distCtx.currentRedemptionId = currentId; distCtx.redemptionAmount = redemptionAmount; totalSupplyOfTokens = totalSupplyOfTokens.sub(totalRedeemedTokens); distCtx.totalRewardAmount = distCtx.distributionAmount.sub(distCtx.receivedRedemptionAmount).add(distCtx.redemptionAmount); return false; } function _transfer(address _from, address _to, uint _value) internal returns (bool success) { require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead if (tokenStatus == TokenStatus.OnSale) { require(_from == owner); } if (_value == 0) { Transfer(_from, _to, _value); return true; } require(holdings.exists(_from)); LibHoldings.Holding storage fromHolding = holdings.get(_from); require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= _value); // Check if the sender has enough if (!holdings.exists(_to)) { holdings.add(_to, LibHoldings.Holding({ totalTokens : _value, lockedTokens : 0, lastRewardNumber : rewards.length.sub(1), weiBalance : 0 })); } else { LibHoldings.Holding storage toHolding = holdings.get(_to); require(toHolding.totalTokens.add(_value) >= toHolding.totalTokens); // Check for overflows updateWeiBalance(toHolding, 0); toHolding.totalTokens = toHolding.totalTokens.add(_value); } updateWeiBalance(fromHolding, 0); fromHolding.totalTokens = fromHolding.totalTokens.sub(_value); // Subtract from the sender if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0) holdings.remove(_from); Transfer(_from, _to, _value); return true; } }
Event is fired when holder cancels redemption request with ID = _requestId@param holder Account address of token holder cancelling redemption request@param _numberOfTokens Number of tokens affected@param _requestId ID of the redemption request that was cancelled
event CancelRedemptionRequest(address holder, uint256 _numberOfTokens, uint256 _requestId);
5,511,098
[ 1, 1133, 353, 15950, 1347, 10438, 3755, 87, 283, 19117, 375, 590, 598, 1599, 273, 389, 2293, 548, 10438, 6590, 1758, 434, 1147, 10438, 848, 3855, 310, 283, 19117, 375, 590, 389, 2696, 951, 5157, 3588, 434, 2430, 9844, 389, 2293, 548, 1599, 434, 326, 283, 19117, 375, 590, 716, 1703, 13927, 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, 871, 10347, 426, 19117, 375, 691, 12, 2867, 10438, 16, 2254, 5034, 389, 2696, 951, 5157, 16, 2254, 5034, 389, 2293, 548, 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 ]
pragma solidity 0.5.17; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {TBTCDepositToken} from "./TBTCDepositToken.sol"; import {FeeRebateToken} from "./FeeRebateToken.sol"; import {TBTCToken} from "./TBTCToken.sol"; import {TBTCConstants} from "./TBTCConstants.sol"; import "../deposit/Deposit.sol"; import "./TBTCSystemAuthority.sol"; /// @title Vending Machine /// @notice The Vending Machine swaps TDTs (`TBTCDepositToken`) /// to TBTC (`TBTCToken`) and vice versa. /// @dev The Vending Machine should have exclusive TBTC and FRT (`FeeRebateToken`) minting /// privileges. contract VendingMachine is TBTCSystemAuthority{ using SafeMath for uint256; TBTCToken tbtcToken; TBTCDepositToken tbtcDepositToken; FeeRebateToken feeRebateToken; uint256 createdAt; constructor(address _systemAddress) TBTCSystemAuthority(_systemAddress) public { createdAt = block.timestamp; } /// @notice Set external contracts needed by the Vending Machine. /// @dev Addresses are used to update the local contract instance. /// @param _tbtcToken TBTCToken contract. More info in `TBTCToken`. /// @param _tbtcDepositToken TBTCDepositToken (TDT) contract. More info in `TBTCDepositToken`. /// @param _feeRebateToken FeeRebateToken (FRT) contract. More info in `FeeRebateToken`. function setExternalAddresses( TBTCToken _tbtcToken, TBTCDepositToken _tbtcDepositToken, FeeRebateToken _feeRebateToken ) external onlyTbtcSystem { tbtcToken = _tbtcToken; tbtcDepositToken = _tbtcDepositToken; feeRebateToken = _feeRebateToken; } /// @notice Burns TBTC and transfers the tBTC Deposit Token to the caller /// as long as it is qualified. /// @dev We burn the lotSize of the Deposit in order to maintain /// the TBTC supply peg in the Vending Machine. VendingMachine must be approved /// by the caller to burn the required amount. /// @param _tdtId ID of tBTC Deposit Token to buy. function tbtcToTdt(uint256 _tdtId) external { require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist"); require(isQualified(address(_tdtId)), "Deposit must be qualified"); uint256 depositValue = Deposit(address(uint160(_tdtId))).lotSizeTbtc(); require(tbtcToken.balanceOf(msg.sender) >= depositValue, "Not enough TBTC for TDT exchange"); tbtcToken.burnFrom(msg.sender, depositValue); // TODO do we need the owner check below? transferFrom can be approved for a user, which might be an interesting use case. require(tbtcDepositToken.ownerOf(_tdtId) == address(this), "Deposit is locked"); tbtcDepositToken.transferFrom(address(this), msg.sender, _tdtId); } /// @notice Transfer the tBTC Deposit Token and mint TBTC. /// @dev Transfers TDT from caller to vending machine, and mints TBTC to caller. /// Vending Machine must be approved to transfer TDT by the caller. /// @param _tdtId ID of tBTC Deposit Token to sell. function tdtToTbtc(uint256 _tdtId) public { require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist"); require(isQualified(address(_tdtId)), "Deposit must be qualified"); tbtcDepositToken.transferFrom(msg.sender, address(this), _tdtId); Deposit deposit = Deposit(address(uint160(_tdtId))); uint256 signerFee = deposit.signerFeeTbtc(); uint256 depositValue = deposit.lotSizeTbtc(); require(canMint(depositValue), "Can't mint more than the max supply cap"); // If the backing Deposit does not have a signer fee in escrow, mint it. if(tbtcToken.balanceOf(address(_tdtId)) < signerFee) { tbtcToken.mint(msg.sender, depositValue.sub(signerFee)); tbtcToken.mint(address(_tdtId), signerFee); } else{ tbtcToken.mint(msg.sender, depositValue); } // owner of the TDT during first TBTC mint receives the FRT if(!feeRebateToken.exists(_tdtId)){ feeRebateToken.mint(msg.sender, _tdtId); } } /// @notice Return whether an amount of TBTC can be minted according to the supply cap /// schedule /// @dev This function is also used by TBTCSystem to decide whether to allow a new deposit. /// @return True if the amount can be minted without hitting the max supply, false otherwise. function canMint(uint256 amount) public view returns (bool) { return getMintedSupply().add(amount) < getMaxSupply(); } /// @notice Determines whether a deposit is qualified for minting TBTC. /// @param _depositAddress The address of the deposit function isQualified(address payable _depositAddress) public view returns (bool) { return Deposit(_depositAddress).inActive(); } /// @notice Return the minted TBTC supply in weitoshis (BTC * 10 ** 18). function getMintedSupply() public view returns (uint256) { return tbtcToken.totalSupply(); } /// @notice Get the maximum TBTC token supply based on the age of the /// contract deployment. The supply cap starts at 2 BTC for the two /// days, 100 for the first week, 250 for the next, then 500, 750, /// 1000, 1500, 2000, 2500, and 3000... finally removing the minting /// restriction after 9 weeks and returning 21M BTC as a sanity /// check. /// @return The max supply in weitoshis (BTC * 10 ** 18). function getMaxSupply() public view returns (uint256) { uint256 age = block.timestamp - createdAt; if(age < 2 days) { return 2 * 10 ** 18; } if (age < 7 days) { return 100 * 10 ** 18; } if (age < 14 days) { return 250 * 10 ** 18; } if (age < 21 days) { return 500 * 10 ** 18; } if (age < 28 days) { return 750 * 10 ** 18; } if (age < 35 days) { return 1000 * 10 ** 18; } if (age < 42 days) { return 1500 * 10 ** 18; } if (age < 49 days) { return 2000 * 10 ** 18; } if (age < 56 days) { return 2500 * 10 ** 18; } if (age < 63 days) { return 3000 * 10 ** 18; } return 21e6 * 10 ** 18; } // WRAPPERS /// @notice Qualifies a deposit and mints TBTC. /// @dev User must allow VendingManchine to transfer TDT. function unqualifiedDepositToTbtc( address payable _depositAddress, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters Deposit _d = Deposit(_depositAddress); _d.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); tdtToTbtc(uint256(_depositAddress)); } /// @notice Redeems a Deposit by purchasing a TDT with TBTC for _finalRecipient, /// and using the TDT to redeem corresponding Deposit as _finalRecipient. /// This function will revert if the Deposit is not in ACTIVE state. /// @dev Vending Machine transfers TBTC allowance to Deposit. /// @param _depositAddress The address of the Deposit to redeem. /// @param _outputValueBytes The 8-byte Bitcoin transaction output size in Little Endian. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. function tbtcToBtc( address payable _depositAddress, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters require(tbtcDepositToken.exists(uint256(_depositAddress)), "tBTC Deposit Token does not exist"); Deposit _d = Deposit(_depositAddress); tbtcToken.burnFrom(msg.sender, _d.lotSizeTbtc()); tbtcDepositToken.approve(_depositAddress, uint256(_depositAddress)); uint256 tbtcOwed = _d.getOwnerRedemptionTbtcRequirement(msg.sender); if(tbtcOwed != 0){ tbtcToken.transferFrom(msg.sender, address(this), tbtcOwed); tbtcToken.approve(_depositAddress, tbtcOwed); } _d.transferAndRequestRedemption(_outputValueBytes, _redeemerOutputScript, msg.sender); } } 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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity 0.5.17; /** * @title Keep interface */ interface ITBTCSystem { // expected behavior: // return the price of 1 sat in wei // these are the native units of the deposit contract function fetchBitcoinPrice() external view returns (uint256); // passthrough requests for the oracle function fetchRelayCurrentDifficulty() external view returns (uint256); function fetchRelayPreviousDifficulty() external view returns (uint256); function getNewDepositFeeEstimate() external view returns (uint256); function getAllowNewDeposits() external view returns (bool); function isAllowedLotSize(uint64 _requestedLotSizeSatoshis) external view returns (bool); function requestNewKeep(uint64 _requestedLotSizeSatoshis, uint256 _maxSecuredLifetime) external payable returns (address); function getSignerFeeDivisor() external view returns (uint16); function getInitialCollateralizedPercent() external view returns (uint16); function getUndercollateralizedThresholdPercent() external view returns (uint16); function getSeverelyUndercollateralizedThresholdPercent() external view returns (uint16); } pragma solidity 0.5.17; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositFunding} from "./DepositFunding.sol"; import {DepositRedemption} from "./DepositRedemption.sol"; import {DepositStates} from "./DepositStates.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; import "../system/DepositFactoryAuthority.sol"; // solium-disable function-order // Below, a few functions must be public to allow bytes memory parameters, but // their being so triggers errors because public functions should be grouped // below external functions. Since these would be external if it were possible, // we ignore the issue. /// @title tBTC Deposit /// @notice This is the main contract for tBTC. It is the state machine that /// (through various libraries) handles bitcoin funding, bitcoin-spv /// proofs, redemption, liquidation, and fraud logic. /// @dev This contract presents a public API that exposes the following /// libraries: /// /// - `DepositFunding` /// - `DepositLiquidaton` /// - `DepositRedemption`, /// - `DepositStates` /// - `DepositUtils` /// - `OutsourceDepositLogging` /// - `TBTCConstants` /// /// Where these libraries require deposit state, this contract's state /// variable `self` is used. `self` is a struct of type /// `DepositUtils.Deposit` that contains all aspects of the deposit state /// itself. contract Deposit is DepositFactoryAuthority { using DepositRedemption for DepositUtils.Deposit; using DepositFunding for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; DepositUtils.Deposit self; /// @dev Deposit should only be _constructed_ once. New deposits are created /// using the `DepositFactory.createDeposit` method, and are clones of /// the constructed deposit. The factory will set the initial values /// for a new clone using `initializeDeposit`. constructor () public { // The constructed Deposit will never be used, so the deposit factory // address can be anything. Clones are updated as per above. initialize(address(0xdeadbeef)); } /// @notice Deposits do not accept arbitrary ETH. function () external payable { require(msg.data.length == 0, "Deposit contract was called with unknown function selector."); } //----------------------------- METADATA LOOKUP ------------------------------// /// @notice Get this deposit's BTC lot size in satoshis. /// @return uint64 lot size in satoshis. function lotSizeSatoshis() external view returns (uint64){ return self.lotSizeSatoshis; } /// @notice Get this deposit's lot size in TBTC. /// @dev This is the same as lotSizeSatoshis(), but is multiplied to scale /// to 18 decimal places. /// @return uint256 lot size in TBTC precision (max 18 decimal places). function lotSizeTbtc() external view returns (uint256){ return self.lotSizeTbtc(); } /// @notice Get the signer fee for this deposit, in TBTC. /// @dev This is the one-time fee required by the signers to perform the /// tasks needed to maintain a decentralized and trustless model for /// tBTC. It is a percentage of the deposit's lot size. /// @return Fee amount in TBTC. function signerFeeTbtc() external view returns (uint256) { return self.signerFeeTbtc(); } /// @notice Get the integer representing the current state. /// @dev We implement this because contracts don't handle foreign enums /// well. See `DepositStates` for more info on states. /// @return The 0-indexed state from the DepositStates enum. function currentState() external view returns (uint256) { return uint256(self.currentState); } /// @notice Check if the Deposit is in ACTIVE state. /// @return True if state is ACTIVE, false otherwise. function inActive() external view returns (bool) { return self.inActive(); } /// @notice Get the contract address of the BondedECDSAKeep associated with /// this Deposit. /// @dev The keep contract address is saved on Deposit initialization. /// @return Address of the Keep contract. function keepAddress() external view returns (address) { return self.keepAddress; } /// @notice Retrieve the remaining term of the deposit in seconds. /// @dev The value accuracy is not guaranteed since block.timestmap can be /// lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at /// term. function remainingTerm() external view returns(uint256){ return self.remainingTerm(); } /// @notice Get the current collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value the /// signers currently must hold as bond. /// @return The current collateralization level for this deposit. function collateralizationPercentage() external view returns (uint256) { return self.collateralizationPercentage(); } /// @notice Get the initial collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value /// the signers hold initially. It is set at creation time. /// @return The initial collateralization level for this deposit. function initialCollateralizedPercent() external view returns (uint16) { return self.initialCollateralizedPercent; } /// @notice Get the undercollateralization level for this Deposit. /// @dev This collateralization level is semi-critical. If the /// collateralization level falls below this percentage the Deposit can /// be courtesy-called by calling `notifyCourtesyCall`. This value /// represents the percentage of the backing BTC value the signers must /// hold as bond in order to not be undercollateralized. It is set at /// creation time. Note that the value for new deposits in TBTCSystem /// can be changed by governance, but the value for a particular /// deposit is static once the deposit is created. /// @return The undercollateralized level for this deposit. function undercollateralizedThresholdPercent() external view returns (uint16) { return self.undercollateralizedThresholdPercent; } /// @notice Get the severe undercollateralization level for this Deposit. /// @dev This collateralization level is critical. If the collateralization /// level falls below this percentage the Deposit can get liquidated. /// This value represents the percentage of the backing BTC value the /// signers must hold as bond in order to not be severely /// undercollateralized. It is set at creation time. Note that the /// value for new deposits in TBTCSystem can be changed by governance, /// but the value for a particular deposit is static once the deposit /// is created. /// @return The severely undercollateralized level for this deposit. function severelyUndercollateralizedThresholdPercent() external view returns (uint16) { return self.severelyUndercollateralizedThresholdPercent; } /// @notice Get the value of the funding UTXO. /// @dev This call will revert if the deposit is not in a state where the /// UTXO info should be valid. In particular, before funding proof is /// successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), this value /// would not be valid. /// @return The value of the funding UTXO in satoshis. function utxoValue() external view returns (uint256){ require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return self.utxoValue(); } /// @notice Returns information associated with the funding UXTO. /// @dev This call will revert if the deposit is not in a state where the /// funding info should be valid. In particular, before funding proof /// is successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), none of /// these values are set or valid. /// @return A tuple of (uxtoValueBytes, fundedAt, uxtoOutpoint). function fundingInfo() external view returns (bytes8 utxoValueBytes, uint256 fundedAt, bytes memory utxoOutpoint) { require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return (self.utxoValueBytes, self.fundedAt, self.utxoOutpoint); } /// @notice Calculates the amount of value at auction right now. /// @dev This call will revert if the deposit is not in a state where an /// auction is currently in progress. /// @return The value in wei that would be received in exchange for the /// deposit's lot size in TBTC if `purchaseSignerBondsAtAuction` /// were called at the time this function is called. function auctionValue() external view returns (uint256) { require( self.inSignerLiquidation(), "Deposit has no funds currently at auction" ); return self.auctionValue(); } /// @notice Get caller's ETH withdraw allowance. /// @dev Generally ETH is only available to withdraw after the deposit /// reaches a closed state. The amount reported is for the sender, and /// can be withdrawn using `withdrawFunds` if the deposit is in an end /// state. /// @return The withdraw allowance in wei. function withdrawableAmount() external view returns (uint256) { return self.getWithdrawableAmount(); } //------------------------------ FUNDING FLOW --------------------------------// /// @notice Notify the contract that signing group setup has timed out if /// retrieveSignerPubkey is not successfully called within the /// allotted time. /// @dev This is considered a signer fault, and the signers' bonds are used /// to make the deposit setup fee available for withdrawal by the TDT /// holder as a refund. The remainder of the signers' bonds are /// returned to the bonding pool and the signers are released from any /// further responsibilities. Reverts if the deposit is not awaiting /// signer setup or if the signing group formation timeout has not /// elapsed. function notifySignerSetupFailed() external { self.notifySignerSetupFailed(); } /// @notice Notify the contract that the ECDSA keep has generated a public /// key so the deposit contract can pull it in. /// @dev Stores the pubkey as 2 bytestrings, X and Y. Emits a /// RegisteredPubkey event with the two components. Reverts if the /// deposit is not awaiting signer setup, if the generated public key /// is unset or has incorrect length, or if the public key has a 0 /// X or Y value. function retrieveSignerPubkey() external { self.retrieveSignerPubkey(); } /// @notice Notify the contract that the funding phase of the deposit has /// timed out if `provideBTCFundingProof` is not successfully called /// within the allotted time. Any sent BTC is left under control of /// the signer group, and the funder can use `requestFunderAbort` to /// request an at-signer-discretion return of any BTC sent to a /// deposit that has been notified of a funding timeout. /// @dev This is considered a funder fault, and the funder's payment for /// opening the deposit is not refunded. Emits a SetupFailed event. /// Reverts if the funding timeout has not yet elapsed, or if the /// deposit is not currently awaiting funding proof. function notifyFundingTimedOut() external { self.notifyFundingTimedOut(); } /// @notice Requests a funder abort for a failed-funding deposit; that is, /// requests the return of a sent UTXO to _abortOutputScript. It /// imposes no requirements on the signing group. Signers should /// send their UTXO to the requested output script, but do so at /// their discretion and with no penalty for failing to do so. This /// can be used for example when a UTXO is sent that is the wrong /// size for the lot. /// @dev This is a self-admitted funder fault, and is only be callable by /// the TDT holder. This function emits the FunderAbortRequested event, /// but stores no additional state. /// @param _abortOutputScript The output script the funder wishes to request /// a return of their UTXO to. function requestFunderAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters require( self.depositOwner() == msg.sender, "Only TDT holder can request funder abort" ); self.requestFunderAbort(_abortOutputScript); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key to prove fraud during funding. Note that during /// funding no signature has been requested from the signers, so /// any signature is effectively fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideFundingECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideFundingECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Anyone may submit a funding proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// to the signer-controlled private key corresopnding to this /// deposit. This will move the deposit into an active state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector /// (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideBTCFundingProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //---------------------------- LIQUIDATION FLOW ------------------------------// /// @notice Notify the contract that the signers are undercollateralized. /// @dev This call will revert if the signers are not in fact /// undercollateralized according to the price feed. After /// TBTCConstants.COURTESY_CALL_DURATION, courtesy call times out and /// regular abort liquidation occurs; see /// `notifyCourtesyTimedOut`. function notifyCourtesyCall() external { self.notifyCourtesyCall(); } /// @notice Notify the contract that the signers' bond value has recovered /// enough to be considered sufficiently collateralized. /// @dev This call will revert if collateral is still below the /// undercollateralized threshold according to the price feed. function exitCourtesyCall() external { self.exitCourtesyCall(); } /// @notice Notify the contract that the courtesy period has expired and the /// deposit should move into liquidation. /// @dev This call will revert if the courtesy call period has not in fact /// expired or is not in the courtesy call state. Courtesy call /// expiration is treated as an abort, and is handled by seizing signer /// bonds and putting them up for auction for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for 50% of any bond left after the /// auction is completed. function notifyCourtesyCallExpired() external { self.notifyCourtesyCallExpired(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @dev This call will revert if the signers are not in fact severely /// undercollateralized according to the price feed. Severe /// undercollateralization is treated as an abort, and is handled by /// seizing signer bonds and putting them up for auction in exchange /// for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and is /// eligible for 50% of any bond left after the auction is completed. function notifyUndercollateralizedLiquidation() external { self.notifyUndercollateralizedLiquidation(); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key that was not requested to prove fraud. A redemption /// request and a redemption fee increase are the only ways to /// request a signature from the signers. /// @dev This call will revert if the underlying keep cannot verify that /// there was fraud. Fraud is handled by seizing signer bonds and /// putting them up for auction in exchange for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for any bond left after the auction is /// completed. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Notify the contract that the signers have failed to produce a /// signature for a redemption request in the allotted time. /// @dev This is considered an abort, and is punished by seizing signer /// bonds and putting them up for auction. Emits a LiquidationStarted /// event and a Liquidated event and sends the full signer bond to the /// redeemer. Reverts if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. The caller /// is captured as the liquidation initiator, and is eligible for 50% /// of any bond left after the auction is completed. function notifyRedemptionSignatureTimedOut() external { self.notifyRedemptionSignatureTimedOut(); } /// @notice Notify the contract that the deposit has failed to receive a /// redemption proof in the allotted time. /// @dev This call will revert if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. This is /// considered an abort, and is punished by seizing signer bonds and /// putting them up for auction for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and /// is eligible for 50% of any bond left after the auction is /// completed. function notifyRedemptionProofTimedOut() external { self.notifyRedemptionProofTimedOut(); } /// @notice Closes an auction and purchases the signer bonds by transferring /// the lot size in TBTC to the redeemer, if there is one, or to the /// TDT holder if not. Any bond amount that is not currently up for /// auction is either made available for the liquidation initiator /// to withdraw (for fraud) or split 50-50 between the initiator and /// the signers (for abort or collateralization issues). /// @dev The amount of ETH given for the transferred TBTC can be read using /// the `auctionValue` function; note, however, that the function's /// value is only static during the specific block it is queried, as it /// varies by block timestamp. function purchaseSignerBondsAtAuction() external { self.purchaseSignerBondsAtAuction(); } //---------------------------- REDEMPTION FLOW -------------------------------// /// @notice Get TBTC amount required for redemption by a specified /// _redeemer. /// @dev This call will revert if redemption is not possible by _redeemer. /// @param _redeemer The deposit redeemer whose TBTC requirement is being /// requested. /// @return The amount in TBTC needed by the `_redeemer` to redeem the /// deposit. function getRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, false); return tbtcPayment; } /// @notice Get TBTC amount required for redemption assuming _redeemer /// is this deposit's owner (TDT holder). /// @param _redeemer The assumed owner of the deposit's TDT . /// @return The amount in TBTC needed to redeem the deposit. function getOwnerRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, true); return tbtcPayment; } /// @notice Requests redemption of this deposit, meaning the transmission, /// by the signers, of the deposit's UTXO to the specified Bitocin /// output script. Requires approving the deposit to spend the /// amount of TBTC needed to redeem. /// @dev The amount of TBTC needed to redeem can be looked up using the /// `getRedemptionTbtcRequirement` or `getOwnerRedemptionTbtcRequirement` /// functions. /// @param _outputValueBytes The 8-byte little-endian output size. The /// difference between this value and the lot size of the deposit /// will be paid as a fee to the Bitcoin miners when the signed /// transaction is broadcast. /// @param _redeemerOutputScript The redeemer's length-prefixed output /// script. function requestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters self.requestRedemption(_outputValueBytes, _redeemerOutputScript); } /// @notice Anyone may provide a withdrawal signature if it was requested. /// @dev The signers will be penalized if this function is not called /// correctly within `TBTCConstants.REDEMPTION_SIGNATURE_TIMEOUT` /// seconds of a redemption request or fee increase being received. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. Should be in the low half of secp256k1 /// curve's order. function provideRedemptionSignature( uint8 _v, bytes32 _r, bytes32 _s ) external { self.provideRedemptionSignature(_v, _r, _s); } /// @notice Anyone may request a signature for a transaction with an /// increased Bitcoin transaction fee. /// @dev This call will revert if the fee is already at its maximum, or if /// the new requested fee is not a multiple of the initial requested /// fee. Transaction fees can only be bumped by the amount of the /// initial requested fee. Calling this sends the deposit back to /// the `AWAITING_WITHDRAWAL_SIGNATURE` state and requires the signers /// to `provideRedemptionSignature` for the new output value in a /// timely fashion. /// @param _previousOutputValueBytes The previous output's value. /// @param _newOutputValueBytes The new output's value. function increaseRedemptionFee( bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) external { self.increaseRedemptionFee(_previousOutputValueBytes, _newOutputValueBytes); } /// @notice Anyone may submit a redemption proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// from the signer-controlled private key corresponding to this /// deposit to the requested redemption output script. This will /// move the deposit into a redeemed state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. Signers can have their bonds seized if this is not /// called within `TBTCConstants.REDEMPTION_PROOF_TIMEOUT` seconds of /// a redemption signature being provided. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideRedemptionProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideRedemptionProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //--------------------------- MUTATING HELPERS -------------------------------// /// @notice This function can only be called by the deposit factory; use /// `DepositFactory.createDeposit` to create a new deposit. /// @dev Initializes a new deposit clone with the base state for the /// deposit. /// @param _tbtcSystem `TBTCSystem` contract. More info in `TBTCSystem`. /// @param _tbtcToken `TBTCToken` contract. More info in TBTCToken`. /// @param _tbtcDepositToken `TBTCDepositToken` (TDT) contract. More info in /// `TBTCDepositToken`. /// @param _feeRebateToken `FeeRebateToken` (FRT) contract. More info in /// `FeeRebateToken`. /// @param _vendingMachineAddress `VendingMachine` address. More info in /// `VendingMachine`. /// @param _lotSizeSatoshis The minimum amount of satoshi the funder is /// required to send. This is also the amount of /// TBTC the TDT holder will be eligible to mint: /// (10**7 satoshi == 0.1 BTC == 0.1 TBTC). function initializeDeposit( ITBTCSystem _tbtcSystem, TBTCToken _tbtcToken, IERC721 _tbtcDepositToken, FeeRebateToken _feeRebateToken, address _vendingMachineAddress, uint64 _lotSizeSatoshis ) public onlyFactory payable { self.tbtcSystem = _tbtcSystem; self.tbtcToken = _tbtcToken; self.tbtcDepositToken = _tbtcDepositToken; self.feeRebateToken = _feeRebateToken; self.vendingMachineAddress = _vendingMachineAddress; self.initialize(_lotSizeSatoshis); } /// @notice This function can only be called by the vending machine. /// @dev Performs the same action as requestRedemption, but transfers /// ownership of the deposit to the specified _finalRecipient. Used as /// a utility helper for the vending machine's shortcut /// TBTC->redemption path. /// @param _outputValueBytes The 8-byte little-endian output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { // not external to allow bytes memory parameters require( msg.sender == self.vendingMachineAddress, "Only the vending machine can call transferAndRequestRedemption" ); self.transferAndRequestRedemption( _outputValueBytes, _redeemerOutputScript, _finalRecipient ); } /// @notice Withdraw the ETH balance of the deposit allotted to the caller. /// @dev Withdrawals can only happen when a contract is in an end-state. function withdrawFunds() external { self.withdrawFunds(); } } pragma solidity 0.5.17; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {DepositStates} from "./DepositStates.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; library DepositLiquidation { using BTCUtils for bytes; using BytesLib for bytes; using SafeMath for uint256; using SafeMath for uint64; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Notifies the keep contract of fraud. Reverts if not fraud. /// @dev Calls out to the keep contract. this could get expensive if preimage /// is large. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. function submitSignatureFraud( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage); } /// @notice Determines the collateralization percentage of the signing group. /// @dev Compares the bond value and lot value. /// @param _d Deposit storage pointer. /// @return Collateralization percentage as uint. function collateralizationPercentage(DepositUtils.Deposit storage _d) public view returns (uint256) { // Determine value of the lot in wei uint256 _satoshiPrice = _d.fetchBitcoinPrice(); uint64 _lotSizeSatoshis = _d.lotSizeSatoshis; uint256 _lotValue = _lotSizeSatoshis.mul(_satoshiPrice); // Amount of wei the signers have uint256 _bondValue = _d.fetchBondAmount(); // This converts into a percentage return (_bondValue.mul(100).div(_lotValue)); } /// @dev Starts signer liquidation by seizing signer bonds. /// If the deposit is currently being redeemed, the redeemer /// receives the full bond value; otherwise, a falling price auction /// begins to buy 1 TBTC in exchange for a portion of the seized bonds; /// see purchaseSignerBondsAtAuction(). /// @param _wasFraud True if liquidation is being started due to fraud, false if for any other reason. /// @param _d Deposit storage pointer. function startLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) internal { _d.logStartedLiquidation(_wasFraud); uint256 seized = _d.seizeSignerBonds(); address redeemerAddress = _d.redeemerAddress; // Reclaim used state for gas savings _d.redemptionTeardown(); // If we see fraud in the redemption flow, we shouldn't go to auction. // Instead give the full signer bond directly to the redeemer. if (_d.inRedemption() && _wasFraud) { _d.setLiquidated(); _d.enableWithdrawal(redeemerAddress, seized); _d.logLiquidated(); return; } _d.liquidationInitiator = msg.sender; _d.liquidationInitiated = block.timestamp; // Store the timestamp for auction if(_wasFraud){ _d.setFraudLiquidationInProgress(); } else{ _d.setLiquidationInProgress(); } } /// @notice Anyone can provide a signature that was not requested to prove fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters require( !_d.inFunding(), "Use provideFundingECDSAFraudProof instead" ); require( !_d.inSignerLiquidation(), "Signer liquidation already in progress" ); require(!_d.inEndState(), "Contract has halted"); submitSignatureFraud(_d, _v, _r, _s, _signedDigest, _preimage); startLiquidation(_d, true); } /// @notice Closes an auction and purchases the signer bonds. Payout to buyer, funder, then signers if not fraud. /// @dev For interface, reading auctionValue will give a past value. the current is better. /// @param _d Deposit storage pointer. function purchaseSignerBondsAtAuction(DepositUtils.Deposit storage _d) external { bool _wasFraud = _d.inFraudLiquidationInProgress(); require(_d.inSignerLiquidation(), "No active auction"); _d.setLiquidated(); _d.logLiquidated(); // Send the TBTC to the redeemer if they exist, otherwise to the TDT // holder. If the TDT holder is the Vending Machine, burn it to maintain // the peg. This is because, if there is a redeemer set here, the TDT // holder has already been made whole at redemption request time. address tbtcRecipient = _d.redeemerAddress; if (tbtcRecipient == address(0)) { tbtcRecipient = _d.depositOwner(); } uint256 lotSizeTbtc = _d.lotSizeTbtc(); require(_d.tbtcToken.balanceOf(msg.sender) >= lotSizeTbtc, "Not enough TBTC to cover outstanding debt"); if(tbtcRecipient == _d.vendingMachineAddress){ _d.tbtcToken.burnFrom(msg.sender, lotSizeTbtc); // burn minimal amount to cover size } else{ _d.tbtcToken.transferFrom(msg.sender, tbtcRecipient, lotSizeTbtc); } // Distribute funds to auction buyer uint256 valueToDistribute = _d.auctionValue(); _d.enableWithdrawal(msg.sender, valueToDistribute); // Send any TBTC left to the Fee Rebate Token holder _d.distributeFeeRebate(); // For fraud, pay remainder to the liquidation initiator. // For non-fraud, split 50-50 between initiator and signers. if the transfer amount is 1, // division will yield a 0 value which causes a revert; instead, // we simply ignore such a tiny amount and leave some wei dust in escrow uint256 contractEthBalance = address(this).balance; address payable initiator = _d.liquidationInitiator; if (initiator == address(0)){ initiator = address(0xdead); } if (contractEthBalance > valueToDistribute + 1) { uint256 remainingUnallocated = contractEthBalance.sub(valueToDistribute); if (_wasFraud) { _d.enableWithdrawal(initiator, remainingUnallocated); } else { // There will always be a liquidation initiator. uint256 split = remainingUnallocated.div(2); _d.pushFundsToKeepGroup(split); _d.enableWithdrawal(initiator, remainingUnallocated.sub(split)); } } } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyCourtesyCall(DepositUtils.Deposit storage _d) external { require(_d.inActive(), "Can only courtesy call from active state"); require(collateralizationPercentage(_d) < _d.undercollateralizedThresholdPercent, "Signers have sufficient collateral"); _d.courtesyCallInitiated = block.timestamp; _d.setCourtesyCall(); _d.logCourtesyCalled(); } /// @notice Goes from courtesy call to active. /// @dev Only callable if collateral is sufficient and the deposit is not expiring. /// @param _d Deposit storage pointer. function exitCourtesyCall(DepositUtils.Deposit storage _d) external { require(_d.inCourtesyCall(), "Not currently in courtesy call"); require(collateralizationPercentage(_d) >= _d.undercollateralizedThresholdPercent, "Deposit is still undercollateralized"); _d.setActive(); _d.logExitedCourtesyCall(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyUndercollateralizedLiquidation(DepositUtils.Deposit storage _d) external { require(_d.inRedeemableState(), "Deposit not in active or courtesy call"); require(collateralizationPercentage(_d) < _d.severelyUndercollateralizedThresholdPercent, "Deposit has sufficient collateral"); startLiquidation(_d, false); } /// @notice Notifies the contract that the courtesy period has elapsed. /// @dev This is treated as an abort, rather than fraud. /// @param _d Deposit storage pointer. function notifyCourtesyCallExpired(DepositUtils.Deposit storage _d) external { require(_d.inCourtesyCall(), "Not in a courtesy call period"); require(block.timestamp >= _d.courtesyCallInitiated.add(TBTCConstants.getCourtesyCallTimeout()), "Courtesy period has not elapsed"); startLiquidation(_d, false); } } pragma solidity ^0.5.10; /** @title BitcoinSPV */ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {SafeMath} from "./SafeMath.sol"; library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; // The target at minimum Difficulty. Also the target of the genesis block uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000; uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /* ***** */ /* UTILS */ /* ***** */ /// @notice Determines the length of a VarInt in bytes /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length /// @param _flag The first byte of a VarInt /// @return The number of non-flag bytes in the VarInt function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) { if (uint8(_flag[0]) == 0xff) { return 8; // one-byte flag, 8 bytes data } if (uint8(_flag[0]) == 0xfe) { return 4; // one-byte flag, 4 bytes data } if (uint8(_flag[0]) == 0xfd) { return 2; // one-byte flag, 2 bytes data } return 0; // flag is data } /// @notice Parse a VarInt into its data length and the number it represents /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes. /// Caller SHOULD explicitly handle this case (or bubble it up) /// @param _b A byte-string starting with a VarInt /// @return number of bytes in the encoding (not counting the tag), the encoded int function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) { uint8 _dataLen = determineVarIntDataLength(_b); if (_dataLen == 0) { return (0, uint8(_b[0])); } if (_b.length < 1 + _dataLen) { return (ERR_BAD_ARG, 0); } uint256 _number = bytesToUint(reverseEndianness(_b.slice(1, _dataLen))); return (_dataLen, _number); } /// @notice Changes the endianness of a byte array /// @dev Returns a new, backwards, bytes /// @param _b The bytes to reverse /// @return The reversed bytes function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) { bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } /// @notice Changes the endianness of a uint256 /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel /// @param _b The unsigned integer to reverse /// @return The reversed value function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /// @notice Converts big-endian bytes to a uint /// @dev Traverses the byte array and sums the bytes /// @param _b The big-endian bytes-encoded integer /// @return The integer representation function bytesToUint(bytes memory _b) internal pure returns (uint256) { uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } /// @notice Get the last _num bytes from a byte array /// @param _b The byte array to slice /// @param _num The number of bytes to extract from the end /// @return The last _num bytes of _b function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { uint256 _start = _b.length.sub(_num); return _b.slice(_start, _num); } /// @notice Implements bitcoin's hash160 (rmd160(sha2())) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash160(bytes memory _b) internal pure returns (bytes memory) { return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash256(bytes memory _b) internal pure returns (bytes32) { return sha256(abi.encodePacked(sha256(_b))); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev sha2 is precompiled smart contract located at address(2) /// @param _b The pre-image /// @return The digest function hash256View(bytes memory _b) internal view returns (bytes32 res) { // solium-disable-next-line security/no-inline-assembly assembly { let ptr := mload(0x40) pop(staticcall(gas, 2, add(_b, 32), mload(_b), ptr, 32)) pop(staticcall(gas, 2, ptr, 32, ptr, 32)) res := mload(ptr) } } /* ************ */ /* Legacy Input */ /* ************ */ /// @notice Extracts the nth input from the vin (0-indexed) /// @dev Iterates over the vin. If you need to extract several, write a custom function /// @param _vin The vin as a tightly-packed byte array /// @param _index The 0-indexed location of the input to extract /// @return The input as a byte array function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _nIns; (_varIntDataLen, _nIns) = parseVarInt(_vin); require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing"); require(_index < _nIns, "Vin read overrun"); bytes memory _remaining; uint256 _len = 0; uint256 _offset = 1 + _varIntDataLen; for (uint256 _i = 0; _i < _index; _i ++) { _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig"); _offset = _offset + _len; } _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _vin.slice(_offset, _len); } /// @notice Determines whether an input is legacy /// @dev False if no scriptSig, otherwise True /// @param _input The input /// @return True for legacy, False for witness function isLegacyInput(bytes memory _input) internal pure returns (bool) { return _input.keccak256Slice(36, 1) != keccak256(hex"00"); } /// @notice Determines the length of a scriptSig in an input /// @dev Will return 0 if passed a witness input. /// @param _input The LEGACY input /// @return The length of the script sig function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) { if (_input.length < 37) { return (ERR_BAD_ARG, 0); } bytes memory _afterOutpoint = _input.slice(36, _input.length - 36); uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = parseVarInt(_afterOutpoint); return (_varIntDataLen, _scriptSigLen); } /// @notice Determines the length of an input from its scriptSig /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence /// @param _input The input /// @return The length of the input in bytes function determineInputLength(bytes memory _input) internal pure returns (uint256) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); if (_varIntDataLen == ERR_BAD_ARG) { return ERR_BAD_ARG; } return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The LEGACY input /// @return The sequence bytes (LE uint) function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _input.slice(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } /// @notice Extracts the sequence from the input /// @dev Sequence is a 4-byte little-endian number /// @param _input The LEGACY input /// @return The sequence number (big-endian uint) function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLELegacy(_input); bytes memory _beSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_beSequence)); } /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx /// @dev Will return hex"00" if passed a witness input /// @param _input The LEGACY input /// @return The length-prepended scriptSig function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen); } /* ************* */ /* Witness Input */ /* ************* */ /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The WITNESS input /// @return The sequence bytes (LE uint) function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(37, 4); } /// @notice Extracts the sequence from the input in a tx /// @dev Sequence is a 4-byte little-endian number /// @param _input The WITNESS input /// @return The sequence number (big-endian uint) function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLEWitness(_input); bytes memory _inputeSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_inputeSequence)); } /// @notice Extracts the outpoint from the input in a tx /// @dev 32-byte tx id with 4-byte index /// @param _input The input /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index) function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(0, 36); } /// @notice Extracts the outpoint tx id from an input /// @dev 32-byte tx id /// @param _input The input /// @return The tx id (little-endian bytes) function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) { return _input.slice(0, 32).toBytes32(); } /// @notice Extracts the LE tx input index from the input in a tx /// @dev 4-byte tx index /// @param _input The input /// @return The tx index (little-endian bytes) function extractTxIndexLE(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(32, 4); } /* ****** */ /* Output */ /* ****** */ /// @notice Determines the length of an output /// @dev Works with any properly formatted output /// @param _output The output /// @return The length indicated by the prefix, error if invalid length function determineOutputLength(bytes memory _output) internal pure returns (uint256) { if (_output.length < 9) { return ERR_BAD_ARG; } bytes memory _afterValue = _output.slice(8, _output.length - 8); uint256 _varIntDataLen; uint256 _scriptPubkeyLength; (_varIntDataLen, _scriptPubkeyLength) = parseVarInt(_afterValue); if (_varIntDataLen == ERR_BAD_ARG) { return ERR_BAD_ARG; } // 8-byte value, 1-byte for tag itself return 8 + 1 + _varIntDataLen + _scriptPubkeyLength; } /// @notice Extracts the output at a given index in the TxOuts vector /// @dev Iterates over the vout. If you need to extract multiple, write a custom function /// @param _vout The _vout to extract from /// @param _index The 0-indexed location of the output to extract /// @return The specified output function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _nOuts; (_varIntDataLen, _nOuts) = parseVarInt(_vout); require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing"); require(_index < _nOuts, "Vout read overrun"); bytes memory _remaining; uint256 _len = 0; uint256 _offset = 1 + _varIntDataLen; for (uint256 _i = 0; _i < _index; _i ++) { _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); _offset += _len; } _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); return _vout.slice(_offset, _len); } /// @notice Extracts the value bytes from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value as LE bytes function extractValueLE(bytes memory _output) internal pure returns (bytes memory) { return _output.slice(0, 8); } /// @notice Extracts the value from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value function extractValue(bytes memory _output) internal pure returns (uint64) { bytes memory _leValue = extractValueLE(_output); bytes memory _beValue = reverseEndianness(_leValue); return uint64(bytesToUint(_beValue)); } /// @notice Extracts the data from an op return output /// @dev Returns hex"" if no data or not an op return /// @param _output The output /// @return Any data contained in the opreturn output, null if not an op return function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) { if (_output.keccak256Slice(9, 1) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.slice(10, 1); return _output.slice(11, bytesToUint(_dataLen)); } /// @notice Extracts the hash from the output script /// @dev Determines type by the length prefix and validates format /// @param _output The output /// @return The hash committed to by the pk_script, or null for errors function extractHash(bytes memory _output) internal pure returns (bytes memory) { uint8 _scriptLen = uint8(_output[8]); // don't have to worry about overflow here. // if _scriptLen + 9 overflows, then output.length would have to be < 9 // for this check to pass. if it's < 9, then we errored when assigning // _scriptLen if (_scriptLen + 9 != _output.length) { return hex""; } if (uint8(_output[9]) == 0) { if (_scriptLen < 2) { return hex""; } uint256 _payloadLen = uint8(_output[10]); // Check for maliciously formatted witness outputs. // No need to worry about underflow as long b/c of the `< 2` check if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) { return hex""; } return _output.slice(11, _payloadLen); } else { bytes32 _tag = _output.keccak256Slice(8, 3); // p2pkh if (_tag == keccak256(hex"1976a9")) { // Check for maliciously formatted p2pkh // No need to worry about underflow, b/c of _scriptLen check if (uint8(_output[11]) != 0x14 || _output.keccak256Slice(_output.length - 2, 2) != keccak256(hex"88ac")) { return hex""; } return _output.slice(12, 20); //p2sh } else if (_tag == keccak256(hex"17a914")) { // Check for maliciously formatted p2sh // No need to worry about underflow, b/c of _scriptLen check if (uint8(_output[_output.length - 1]) != 0x87) { return hex""; } return _output.slice(11, 20); } } return hex""; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */ } /* ********** */ /* Witness TX */ /* ********** */ /// @notice Checks that the vin passed up is properly formatted /// @dev Consider a vin with a valid vout in its scriptsig /// @param _vin Raw bytes length-prefixed input vector /// @return True if it represents a validly formatted vin function validateVin(bytes memory _vin) internal pure returns (bool) { uint256 _varIntDataLen; uint256 _nIns; (_varIntDataLen, _nIns) = parseVarInt(_vin); // Not valid if it says there are too many or no inputs if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) { return false; } uint256 _offset = 1 + _varIntDataLen; for (uint256 i = 0; i < _nIns; i++) { // If we're at the end, but still expect more if (_offset >= _vin.length) { return false; } // Grab the next input and determine its length. bytes memory _next = _vin.slice(_offset, _vin.length - _offset); uint256 _nextLen = determineInputLength(_next); if (_nextLen == ERR_BAD_ARG) { return false; } // Increase the offset by that much _offset += _nextLen; } // Returns false if we're not exactly at the end return _offset == _vin.length; } /// @notice Checks that the vout passed up is properly formatted /// @dev Consider a vout with a valid scriptpubkey /// @param _vout Raw bytes length-prefixed output vector /// @return True if it represents a validly formatted vout function validateVout(bytes memory _vout) internal pure returns (bool) { uint256 _varIntDataLen; uint256 _nOuts; (_varIntDataLen, _nOuts) = parseVarInt(_vout); // Not valid if it says there are too many or no outputs if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) { return false; } uint256 _offset = 1 + _varIntDataLen; for (uint256 i = 0; i < _nOuts; i++) { // If we're at the end, but still expect more if (_offset >= _vout.length) { return false; } // Grab the next output and determine its length. // Increase the offset by that much bytes memory _next = _vout.slice(_offset, _vout.length - _offset); uint256 _nextLen = determineOutputLength(_next); if (_nextLen == ERR_BAD_ARG) { return false; } _offset += _nextLen; } // Returns false if we're not exactly at the end return _offset == _vout.length; } /* ************ */ /* Block Header */ /* ************ */ /// @notice Extracts the transaction merkle root from a block header /// @dev Use verifyHash256Merkle to verify proofs with this root /// @param _header The header /// @return The merkle root (little-endian) function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(36, 32); } /// @notice Extracts the target from a block header /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent /// @param _header The header /// @return The target threshold function extractTarget(bytes memory _header) internal pure returns (uint256) { bytes memory _m = _header.slice(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = bytesToUint(reverseEndianness(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } /// @notice Calculate difficulty from the difficulty 1 target and current target /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet /// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent /// @param _target The current target /// @return The block difficulty (bdiff) function calculateDifficulty(uint256 _target) internal pure returns (uint256) { // Difficulty 1 calculated from 0x1d00ffff return DIFF1_TARGET.div(_target); } /// @notice Extracts the previous block's hash from a block header /// @dev Block headers do NOT include block number :( /// @param _header The header /// @return The previous block's hash (little-endian) function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(4, 32); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (little-endian bytes) function extractTimestampLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(68, 4); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (uint) function extractTimestamp(bytes memory _header) internal pure returns (uint32) { return uint32(bytesToUint(reverseEndianness(extractTimestampLE(_header)))); } /// @notice Extracts the expected difficulty from a block header /// @dev Does NOT verify the work /// @param _header The header /// @return The difficulty as an integer function extractDifficulty(bytes memory _header) internal pure returns (uint256) { return calculateDifficulty(extractTarget(_header)); } /// @notice Concatenates and hashes two inputs for merkle proving /// @param _a The first hash /// @param _b The second hash /// @return The double-sha256 of the concatenated hashes function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { return hash256(abi.encodePacked(_a, _b)); } /// @notice Verifies a Bitcoin-style merkle tree /// @dev Leaves are 0-indexed. /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root /// @param _index The index of the leaf /// @return true if the proof is valid, else false function verifyHash256Merkle(bytes memory _proof, uint _index) internal pure returns (bool) { // Not an even number of hashes if (_proof.length % 32 != 0) { return false; } // Special case for coinbase-only blocks if (_proof.length == 32) { return true; } // Should never occur if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.slice(_proof.length - 32, 32).toBytes32(); bytes32 _current = _proof.slice(0, 32).toBytes32(); for (uint i = 1; i < (_proof.length.div(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _hash256MerkleStep(_proof.slice(i * 32, 32), abi.encodePacked(_current)); } else { _current = _hash256MerkleStep(abi.encodePacked(_current), _proof.slice(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } /* NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72 NB: We get a full-bitlength target from this. For comparison with header-encoded targets we need to mask it with the header target e.g. (full & truncated) == truncated */ /// @notice performs the bitcoin difficulty retarget /// @dev implements the Bitcoin algorithm precisely /// @param _previousTarget the target of the previous period /// @param _firstTimestamp the timestamp of the first block in the difficulty period /// @param _secondTimestamp the timestamp of the last block in the difficulty period /// @return the new period's target threshold function retargetAlgorithm( uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp); // Normalize ratio to factor of 4 if very long or very short if (_elapsedTime < RETARGET_PERIOD.div(4)) { _elapsedTime = RETARGET_PERIOD.div(4); } if (_elapsedTime > RETARGET_PERIOD.mul(4)) { _elapsedTime = RETARGET_PERIOD.mul(4); } /* NB: high targets e.g. ffff0020 can cause overflows here so we divide it by 256**2, then multiply by 256**2 later we know the target is evenly divisible by 256**2, so this isn't an issue */ uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime); return _adjusted.div(RETARGET_PERIOD).mul(65536); } } pragma solidity ^0.5.10; /* https://github.com/GNSPS/solidity-bytes-utils/ This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <https://unlicense.org> */ /** @title BytesLib **/ /** @author https://github.com/GNSPS **/ library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) { if (_length == 0) { return hex""; } uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { // Alloc bytes array with additional 32 bytes afterspace and assign it's size res := mload(0x40) mstore(0x40, add(add(res, 64), _length)) mstore(res, _length) // Compute distance between source and destination pointers let diff := sub(res, add(_bytes, _start)) for { let src := add(add(_bytes, 32), _start) let end := add(src, _length) } lt(src, end) { src := add(src, 32) } { mstore(add(src, diff), mload(src)) } } } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { uint _totalLen = _start + 20; require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint _totalLen = _start + 32; require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } function toBytes32(bytes memory _source) pure internal returns (bytes32 result) { if (_source.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) { uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { result := keccak256(add(add(_bytes, 32), _start), _length) } } } pragma solidity ^0.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @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; require(c / _a == _b, "Overflow during multiplication."); 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) { require(_b <= _a, "Underflow during subtraction."); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; require(c >= _a, "Overflow during addition."); return c; } } pragma solidity 0.5.17; import {DepositUtils} from "./DepositUtils.sol"; library DepositStates { enum States { // DOES NOT EXIST YET START, // FUNDING FLOW AWAITING_SIGNER_SETUP, AWAITING_BTC_FUNDING_PROOF, // FAILED SETUP FAILED_SETUP, // ACTIVE ACTIVE, // includes courtesy call // REDEMPTION FLOW AWAITING_WITHDRAWAL_SIGNATURE, AWAITING_WITHDRAWAL_PROOF, REDEEMED, // SIGNER LIQUIDATION FLOW COURTESY_CALL, FRAUD_LIQUIDATION_IN_PROGRESS, LIQUIDATION_IN_PROGRESS, LIQUIDATED } /// @notice Check if the contract is currently in the funding flow. /// @dev This checks on the funding flow happy path, not the fraud path. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the funding flow else False. function inFunding(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.AWAITING_SIGNER_SETUP) || _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF) ); } /// @notice Check if the contract is currently in the signer liquidation flow. /// @dev This could be caused by fraud, or by an unfilled margin call. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the liquidaton flow else False. function inSignerLiquidation(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS) || _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS) ); } /// @notice Check if the contract is currently in the redepmtion flow. /// @dev This checks on the redemption flow, not the REDEEMED termination state. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the redemption flow else False. function inRedemption(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE) || _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF) ); } /// @notice Check if the contract has halted. /// @dev This checks on any halt state, regardless of triggering circumstances. /// @param _d Deposit storage pointer. /// @return True if contract has halted permanently. function inEndState(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.LIQUIDATED) || _d.currentState == uint8(States.REDEEMED) || _d.currentState == uint8(States.FAILED_SETUP) ); } /// @notice Check if the contract is available for a redemption request. /// @dev Redemption is available from active and courtesy call. /// @param _d Deposit storage pointer. /// @return True if available, False otherwise. function inRedeemableState(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.ACTIVE) || _d.currentState == uint8(States.COURTESY_CALL) ); } /// @notice Check if the contract is currently in the start state (awaiting setup). /// @dev This checks on the funding flow happy path, not the fraud path. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the start state else False. function inStart(DepositUtils.Deposit storage _d) public view returns (bool) { return (_d.currentState == uint8(States.START)); } function inAwaitingSignerSetup(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_SIGNER_SETUP); } function inAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF); } function inFailedSetup(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.FAILED_SETUP); } function inActive(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.ACTIVE); } function inAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE); } function inAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF); } function inRedeemed(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.REDEEMED); } function inCourtesyCall(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.COURTESY_CALL); } function inFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS); } function inLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS); } function inLiquidated(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.LIQUIDATED); } function setAwaitingSignerSetup(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_SIGNER_SETUP); } function setAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_BTC_FUNDING_PROOF); } function setFailedSetup(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.FAILED_SETUP); } function setActive(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.ACTIVE); } function setAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_WITHDRAWAL_SIGNATURE); } function setAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_WITHDRAWAL_PROOF); } function setRedeemed(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.REDEEMED); } function setCourtesyCall(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.COURTESY_CALL); } function setFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS); } function setLiquidationInProgress(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.LIQUIDATION_IN_PROGRESS); } function setLiquidated(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.LIQUIDATED); } } pragma solidity 0.5.17; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {DepositStates} from "./DepositStates.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; library DepositUtils { using SafeMath for uint256; using SafeMath for uint64; using BytesLib for bytes; using BTCUtils for bytes; using BTCUtils for uint256; using ValidateSPV for bytes; using ValidateSPV for bytes32; using DepositStates for DepositUtils.Deposit; struct Deposit { // SET DURING CONSTRUCTION ITBTCSystem tbtcSystem; TBTCToken tbtcToken; IERC721 tbtcDepositToken; FeeRebateToken feeRebateToken; address vendingMachineAddress; uint64 lotSizeSatoshis; uint8 currentState; uint16 signerFeeDivisor; uint16 initialCollateralizedPercent; uint16 undercollateralizedThresholdPercent; uint16 severelyUndercollateralizedThresholdPercent; uint256 keepSetupFee; // SET ON FRAUD uint256 liquidationInitiated; // Timestamp of when liquidation starts uint256 courtesyCallInitiated; // When the courtesy call is issued address payable liquidationInitiator; // written when we request a keep address keepAddress; // The address of our keep contract uint256 signingGroupRequestedAt; // timestamp of signing group request // written when we get a keep result uint256 fundingProofTimerStart; // start of the funding proof period. reused for funding fraud proof period bytes32 signingGroupPubkeyX; // The X coordinate of the signing group's pubkey bytes32 signingGroupPubkeyY; // The Y coordinate of the signing group's pubkey // INITIALLY WRITTEN BY REDEMPTION FLOW address payable redeemerAddress; // The redeemer's address, used as fallback for fraud in redemption bytes redeemerOutputScript; // The redeemer output script uint256 initialRedemptionFee; // the initial fee as requested uint256 latestRedemptionFee; // the fee currently required by a redemption transaction uint256 withdrawalRequestTime; // the most recent withdrawal request timestamp bytes32 lastRequestedDigest; // the digest most recently requested for signing // written when we get funded bytes8 utxoValueBytes; // LE uint. the size of the deposit UTXO in satoshis uint256 fundedAt; // timestamp when funding proof was received bytes utxoOutpoint; // the 36-byte outpoint of the custodied UTXO /// @dev Map of ETH balances an address can withdraw after contract reaches ends-state. mapping(address => uint256) withdrawableAmounts; /// @dev Map of timestamps representing when transaction digests were approved for signing mapping (bytes32 => uint256) approvedDigests; } /// @notice Closes keep associated with the deposit. /// @dev Should be called when the keep is no longer needed and the signing /// group can disband. function closeKeep(DepositUtils.Deposit storage _d) internal { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.closeKeep(); } /// @notice Gets the current block difficulty. /// @dev Calls the light relay and gets the current block difficulty. /// @return The difficulty. function currentBlockDifficulty(Deposit storage _d) public view returns (uint256) { return _d.tbtcSystem.fetchRelayCurrentDifficulty(); } /// @notice Gets the previous block difficulty. /// @dev Calls the light relay and gets the previous block difficulty. /// @return The difficulty. function previousBlockDifficulty(Deposit storage _d) public view returns (uint256) { return _d.tbtcSystem.fetchRelayPreviousDifficulty(); } /// @notice Evaluates the header difficulties in a proof. /// @dev Uses the light oracle to source recent difficulty. /// @param _bitcoinHeaders The header chain to evaluate. /// @return True if acceptable, otherwise revert. function evaluateProofDifficulty(Deposit storage _d, bytes memory _bitcoinHeaders) public view { uint256 _reqDiff; uint256 _current = currentBlockDifficulty(_d); uint256 _previous = previousBlockDifficulty(_d); uint256 _firstHeaderDiff = _bitcoinHeaders.extractTarget().calculateDifficulty(); if (_firstHeaderDiff == _current) { _reqDiff = _current; } else if (_firstHeaderDiff == _previous) { _reqDiff = _previous; } else { revert("not at current or previous difficulty"); } uint256 _observedDiff = _bitcoinHeaders.validateHeaderChain(); require(_observedDiff != ValidateSPV.getErrBadLength(), "Invalid length of the headers chain"); require(_observedDiff != ValidateSPV.getErrInvalidChain(), "Invalid headers chain"); require(_observedDiff != ValidateSPV.getErrLowWork(), "Insufficient work in a header"); require( _observedDiff >= _reqDiff.mul(TBTCConstants.getTxProofDifficultyFactor()), "Insufficient accumulated difficulty in header chain" ); } /// @notice Syntactically check an SPV proof for a bitcoin transaction with its hash (ID). /// @dev Stateless SPV Proof verification documented elsewhere (see https://github.com/summa-tx/bitcoin-spv). /// @param _d Deposit storage pointer. /// @param _txId The bitcoin txid of the tx that is purportedly included in the header chain. /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block. /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed). /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers. function checkProofFromTxId( Deposit storage _d, bytes32 _txId, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public view{ require( _txId.prove( _bitcoinHeaders.extractMerkleRootLE().toBytes32(), _merkleProof, _txIndexInBlock ), "Tx merkle proof is not valid for provided header and txId"); evaluateProofDifficulty(_d, _bitcoinHeaders); } /// @notice Find and validate funding output in transaction output vector using the index. /// @dev Gets `_fundingOutputIndex` output from the output vector and validates if it is /// a p2wpkh output with public key hash matching this deposit's public key hash. /// @param _d Deposit storage pointer. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC outputs. /// @param _fundingOutputIndex Index of funding output in _txOutputVector. /// @return Funding value. function findAndParseFundingOutput( DepositUtils.Deposit storage _d, bytes memory _txOutputVector, uint8 _fundingOutputIndex ) public view returns (bytes8) { bytes8 _valueBytes; bytes memory _output; // Find the output paying the signer PKH _output = _txOutputVector.extractOutputAtIndex(_fundingOutputIndex); require( keccak256(_output.extractHash()) == keccak256(abi.encodePacked(signerPKH(_d))), "Could not identify output funding the required public key hash" ); require( _output.length == 31 && _output.keccak256Slice(8, 23) == keccak256(abi.encodePacked(hex"160014", signerPKH(_d))), "Funding transaction output type unsupported: only p2wpkh outputs are supported" ); _valueBytes = bytes8(_output.slice(0, 8).toBytes32()); return _valueBytes; } /// @notice Validates the funding tx and parses information from it. /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first. /// @return The 8-byte LE UTXO size in satoshi, the 36byte outpoint. function validateAndParseFundingSPVProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public view returns (bytes8 _valueBytes, bytes memory _utxoOutpoint){ // not external to allow bytes memory parameters require(_txInputVector.validateVin(), "invalid input vector provided"); require(_txOutputVector.validateVout(), "invalid output vector provided"); bytes32 txID = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); _valueBytes = findAndParseFundingOutput(_d, _txOutputVector, _fundingOutputIndex); require(bytes8LEToUint(_valueBytes) >= _d.lotSizeSatoshis, "Deposit too small"); checkProofFromTxId(_d, txID, _merkleProof, _txIndexInBlock, _bitcoinHeaders); // The utxoOutpoint is the LE txID plus the index of the output as a 4-byte LE int // _fundingOutputIndex is a uint8, so we know it is only 1 byte // Therefore, pad with 3 more bytes _utxoOutpoint = abi.encodePacked(txID, _fundingOutputIndex, hex"000000"); } /// @notice Retreive the remaining term of the deposit /// @dev The return value is not guaranteed since block.timestmap can be lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at term function remainingTerm(DepositUtils.Deposit storage _d) public view returns(uint256){ uint256 endOfTerm = _d.fundedAt.add(TBTCConstants.getDepositTerm()); if(block.timestamp < endOfTerm ) { return endOfTerm.sub(block.timestamp); } return 0; } /// @notice Calculates the amount of value at auction right now. /// @dev We calculate the % of the auction that has elapsed, then scale the value up. /// @param _d Deposit storage pointer. /// @return The value in wei to distribute in the auction at the current time. function auctionValue(Deposit storage _d) external view returns (uint256) { uint256 _elapsed = block.timestamp.sub(_d.liquidationInitiated); uint256 _available = address(this).balance; if (_elapsed > TBTCConstants.getAuctionDuration()) { return _available; } // This should make a smooth flow from base% to 100% uint256 _basePercentage = getAuctionBasePercentage(_d); uint256 _elapsedPercentage = uint256(100).sub(_basePercentage).mul(_elapsed).div(TBTCConstants.getAuctionDuration()); uint256 _percentage = _basePercentage.add(_elapsedPercentage); return _available.mul(_percentage).div(100); } /// @notice Gets the lot size in erc20 decimal places (max 18) /// @return uint256 lot size in 10**18 decimals. function lotSizeTbtc(Deposit storage _d) public view returns (uint256){ return _d.lotSizeSatoshis.mul(TBTCConstants.getSatoshiMultiplier()); } /// @notice Determines the fees due to the signers for work performed. /// @dev Signers are paid based on the TBTC issued. /// @return Accumulated fees in 10**18 decimals. function signerFeeTbtc(Deposit storage _d) public view returns (uint256) { return lotSizeTbtc(_d).div(_d.signerFeeDivisor); } /// @notice Determines the prefix to the compressed public key. /// @dev The prefix encodes the parity of the Y coordinate. /// @param _pubkeyY The Y coordinate of the public key. /// @return The 1-byte prefix for the compressed key. function determineCompressionPrefix(bytes32 _pubkeyY) public pure returns (bytes memory) { if(uint256(_pubkeyY) & 1 == 1) { return hex"03"; // Odd Y } else { return hex"02"; // Even Y } } /// @notice Compresses a public key. /// @dev Converts the 64-byte key to a 33-byte key, bitcoin-style. /// @param _pubkeyX The X coordinate of the public key. /// @param _pubkeyY The Y coordinate of the public key. /// @return The 33-byte compressed pubkey. function compressPubkey(bytes32 _pubkeyX, bytes32 _pubkeyY) public pure returns (bytes memory) { return abi.encodePacked(determineCompressionPrefix(_pubkeyY), _pubkeyX); } /// @notice Returns the packed public key (64 bytes) for the signing group. /// @dev We store it as 2 bytes32, (2 slots) then repack it on demand. /// @return 64 byte public key. function signerPubkey(Deposit storage _d) external view returns (bytes memory) { return abi.encodePacked(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY); } /// @notice Returns the Bitcoin pubkeyhash (hash160) for the signing group. /// @dev This is used in bitcoin output scripts for the signers. /// @return 20-bytes public key hash. function signerPKH(Deposit storage _d) public view returns (bytes20) { bytes memory _pubkey = compressPubkey(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY); bytes memory _digest = _pubkey.hash160(); return bytes20(_digest.toAddress(0)); // dirty solidity hack } /// @notice Returns the size of the deposit UTXO in satoshi. /// @dev We store the deposit as bytes8 to make signature checking easier. /// @return UTXO value in satoshi. function utxoValue(Deposit storage _d) external view returns (uint256) { return bytes8LEToUint(_d.utxoValueBytes); } /// @notice Gets the current price of Bitcoin in Ether. /// @dev Polls the price feed via the system contract. /// @return The current price of 1 sat in wei. function fetchBitcoinPrice(Deposit storage _d) external view returns (uint256) { return _d.tbtcSystem.fetchBitcoinPrice(); } /// @notice Fetches the Keep's bond amount in wei. /// @dev Calls the keep contract to do so. /// @return The amount of bonded ETH in wei. function fetchBondAmount(Deposit storage _d) external view returns (uint256) { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); return _keep.checkBondAmount(); } /// @notice Convert a LE bytes8 to a uint256. /// @dev Do this by converting to bytes, then reversing endianness, then converting to int. /// @return The uint256 represented in LE by the bytes8. function bytes8LEToUint(bytes8 _b) public pure returns (uint256) { return abi.encodePacked(_b).reverseEndianness().bytesToUint(); } /// @notice Gets timestamp of digest approval for signing. /// @dev Identifies entry in the recorded approvals by keep ID and digest pair. /// @param _digest Digest to check approval for. /// @return Timestamp from the moment of recording the digest for signing. /// Returns 0 if the digest was not approved for signing. function wasDigestApprovedForSigning(Deposit storage _d, bytes32 _digest) external view returns (uint256) { return _d.approvedDigests[_digest]; } /// @notice Looks up the Fee Rebate Token holder. /// @return The current token holder if the Token exists. /// address(0) if the token does not exist. function feeRebateTokenHolder(Deposit storage _d) public view returns (address payable) { address tokenHolder = address(0); if(_d.feeRebateToken.exists(uint256(address(this)))){ tokenHolder = address(uint160(_d.feeRebateToken.ownerOf(uint256(address(this))))); } return address(uint160(tokenHolder)); } /// @notice Looks up the deposit beneficiary by calling the tBTC system. /// @dev We cast the address to a uint256 to match the 721 standard. /// @return The current deposit beneficiary. function depositOwner(Deposit storage _d) public view returns (address payable) { return address(uint160(_d.tbtcDepositToken.ownerOf(uint256(address(this))))); } /// @notice Deletes state after termination of redemption process. /// @dev We keep around the redeemer address so we can pay them out. function redemptionTeardown(Deposit storage _d) public { _d.redeemerOutputScript = ""; _d.initialRedemptionFee = 0; _d.withdrawalRequestTime = 0; _d.lastRequestedDigest = bytes32(0); } /// @notice Get the starting percentage of the bond at auction. /// @dev This will return the same value regardless of collateral price. /// @return The percentage of the InitialCollateralizationPercent that will result /// in a 100% bond value base auction given perfect collateralization. function getAuctionBasePercentage(Deposit storage _d) internal view returns (uint256) { return uint256(10000).div(_d.initialCollateralizedPercent); } /// @notice Seize the signer bond from the keep contract. /// @dev we check our balance before and after. /// @return The amount seized in wei. function seizeSignerBonds(Deposit storage _d) internal returns (uint256) { uint256 _preCallBalance = address(this).balance; IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.seizeSignerBonds(); uint256 _postCallBalance = address(this).balance; require(_postCallBalance > _preCallBalance, "No funds received, unexpected"); return _postCallBalance.sub(_preCallBalance); } /// @notice Adds a given amount to the withdraw allowance for the address. /// @dev Withdrawals can only happen when a contract is in an end-state. function enableWithdrawal(DepositUtils.Deposit storage _d, address _withdrawer, uint256 _amount) internal { _d.withdrawableAmounts[_withdrawer] = _d.withdrawableAmounts[_withdrawer].add(_amount); } /// @notice Withdraw caller's allowance. /// @dev Withdrawals can only happen when a contract is in an end-state. function withdrawFunds(DepositUtils.Deposit storage _d) internal { uint256 available = _d.withdrawableAmounts[msg.sender]; require(_d.inEndState(), "Contract not yet terminated"); require(available > 0, "Nothing to withdraw"); require(address(this).balance >= available, "Insufficient contract balance"); // zero-out to prevent reentrancy _d.withdrawableAmounts[msg.sender] = 0; /* solium-disable-next-line security/no-call-value */ (bool ok,) = msg.sender.call.value(available)(""); require( ok, "Failed to send withdrawable amount to sender" ); } /// @notice Get the caller's withdraw allowance. /// @return The caller's withdraw allowance in wei. function getWithdrawableAmount(DepositUtils.Deposit storage _d) internal view returns (uint256) { return _d.withdrawableAmounts[msg.sender]; } /// @notice Distributes the fee rebate to the Fee Rebate Token owner. /// @dev Whenever this is called we are shutting down. function distributeFeeRebate(Deposit storage _d) internal { address rebateTokenHolder = feeRebateTokenHolder(_d); // exit the function if there is nobody to send the rebate to if(rebateTokenHolder == address(0)){ return; } // pay out the rebate if it is available if(_d.tbtcToken.balanceOf(address(this)) >= signerFeeTbtc(_d)) { _d.tbtcToken.transfer(rebateTokenHolder, signerFeeTbtc(_d)); } } /// @notice Pushes ether held by the deposit to the signer group. /// @dev Ether is returned to signing group members bonds. /// @param _ethValue The amount of ether to send. function pushFundsToKeepGroup(Deposit storage _d, uint256 _ethValue) internal { require(address(this).balance >= _ethValue, "Not enough funds to send"); if(_ethValue > 0){ IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.returnPartialSignerBonds.value(_ethValue)(); } } /// @notice Calculate TBTC amount required for redemption by a specified /// _redeemer. If _assumeRedeemerHoldTdt is true, return the /// requirement as if the redeemer holds this deposit's TDT. /// @dev Will revert if redemption is not possible by the current owner and /// _assumeRedeemerHoldsTdt was not set. Setting /// _assumeRedeemerHoldsTdt only when appropriate is the responsibility /// of the caller; as such, this function should NEVER be publicly /// exposed. /// @param _redeemer The account that should be treated as redeeming this /// deposit for the purposes of this calculation. /// @param _assumeRedeemerHoldsTdt If true, the calculation assumes that the /// specified redeemer holds the TDT. If false, the calculation /// checks the deposit owner against the specified _redeemer. Note /// that this parameter should be false for all mutating calls to /// preserve system correctness. /// @return A tuple of the amount the redeemer owes to the deposit to /// initiate redemption, the amount that is owed to the TDT holder /// when redemption is initiated, and the amount that is owed to the /// FRT holder when redemption is initiated. function calculateRedemptionTbtcAmounts( DepositUtils.Deposit storage _d, address _redeemer, bool _assumeRedeemerHoldsTdt ) internal view returns ( uint256 owedToDeposit, uint256 owedToTdtHolder, uint256 owedToFrtHolder ) { bool redeemerHoldsTdt = _assumeRedeemerHoldsTdt || depositOwner(_d) == _redeemer; bool preTerm = remainingTerm(_d) > 0 && !_d.inCourtesyCall(); require( redeemerHoldsTdt || !preTerm, "Only TDT holder can redeem unless deposit is at-term or in COURTESY_CALL" ); bool frtExists = feeRebateTokenHolder(_d) != address(0); bool redeemerHoldsFrt = feeRebateTokenHolder(_d) == _redeemer; uint256 signerFee = signerFeeTbtc(_d); uint256 feeEscrow = calculateRedemptionFeeEscrow( signerFee, preTerm, frtExists, redeemerHoldsTdt, redeemerHoldsFrt ); // Base redemption + fee = total we need to have escrowed to start // redemption. owedToDeposit = calculateBaseRedemptionCharge( lotSizeTbtc(_d), redeemerHoldsTdt ).add(feeEscrow); // Adjust the amount owed to the deposit based on any balance the // deposit already has. uint256 balance = _d.tbtcToken.balanceOf(address(this)); if (owedToDeposit > balance) { owedToDeposit = owedToDeposit.sub(balance); } else { owedToDeposit = 0; } // Pre-term, the FRT rebate is payed out, but if the redeemer holds the // FRT, the amount has already been subtracted from what is owed to the // deposit at this point (by calculateRedemptionFeeEscrow). This allows // the redeemer to simply *not pay* the fee rebate, rather than having // them pay it only to have it immediately returned. if (preTerm && frtExists && !redeemerHoldsFrt) { owedToFrtHolder = signerFee; } // The TDT holder gets any leftover balance. owedToTdtHolder = balance.add(owedToDeposit).sub(signerFee).sub(owedToFrtHolder); return (owedToDeposit, owedToTdtHolder, owedToFrtHolder); } /// @notice Get the base TBTC amount needed to redeem. /// @param _lotSize The lot size to use for the base redemption charge. /// @param _redeemerHoldsTdt True if the redeemer is the TDT holder. /// @return The amount in TBTC. function calculateBaseRedemptionCharge( uint256 _lotSize, bool _redeemerHoldsTdt ) internal pure returns (uint256){ if (_redeemerHoldsTdt) { return 0; } return _lotSize; } /// @notice Get fees owed for redemption /// @param signerFee The value of the signer fee for fee calculations. /// @param _preTerm True if the Deposit is at-term or in courtesy_call. /// @param _frtExists True if the FRT exists. /// @param _redeemerHoldsTdt True if the the redeemer holds the TDT. /// @param _redeemerHoldsFrt True if the redeemer holds the FRT. /// @return The fees owed in TBTC. function calculateRedemptionFeeEscrow( uint256 signerFee, bool _preTerm, bool _frtExists, bool _redeemerHoldsTdt, bool _redeemerHoldsFrt ) internal pure returns (uint256) { // Escrow the fee rebate so the FRT holder can be repaids, unless the // redeemer holds the FRT, in which case we simply don't require the // rebate from them. bool escrowRequiresFeeRebate = _preTerm && _frtExists && ! _redeemerHoldsFrt; bool escrowRequiresFee = _preTerm || // If the FRT exists at term/courtesy call, the fee is // "required", but should already be escrowed before redemption. _frtExists || // The TDT holder always owes fees if there is no FRT. _redeemerHoldsTdt; uint256 feeEscrow = 0; if (escrowRequiresFee) { feeEscrow += signerFee; } if (escrowRequiresFeeRebate) { feeEscrow += signerFee; } return feeEscrow; } } pragma solidity 0.5.17; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositStates} from "./DepositStates.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; library DepositFunding { using SafeMath for uint256; using SafeMath for uint64; using BTCUtils for bytes; using BytesLib for bytes; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Deletes state after funding. /// @dev This is called when we go to ACTIVE or setup fails without fraud. function fundingTeardown(DepositUtils.Deposit storage _d) internal { _d.signingGroupRequestedAt = 0; _d.fundingProofTimerStart = 0; } /// @notice Deletes state after the funding ECDSA fraud process. /// @dev This is only called as we transition to setup failed. function fundingFraudTeardown(DepositUtils.Deposit storage _d) internal { _d.keepAddress = address(0); _d.signingGroupRequestedAt = 0; _d.fundingProofTimerStart = 0; _d.signingGroupPubkeyX = bytes32(0); _d.signingGroupPubkeyY = bytes32(0); } /// @notice Internally called function to set up a newly created Deposit /// instance. This should not be called by developers, use /// `DepositFactory.createDeposit` to create a new deposit. /// @dev If called directly, the transaction will revert since the call will /// be executed on an already set-up instance. /// @param _d Deposit storage pointer. /// @param _lotSizeSatoshis Lot size in satoshis. function initialize( DepositUtils.Deposit storage _d, uint64 _lotSizeSatoshis ) public { require(_d.tbtcSystem.getAllowNewDeposits(), "New deposits aren't allowed."); require(_d.inStart(), "Deposit setup already requested"); _d.lotSizeSatoshis = _lotSizeSatoshis; _d.keepSetupFee = _d.tbtcSystem.getNewDepositFeeEstimate(); // Note: this is a library, and library functions cannot be marked as // payable. Thus, we disable Solium's check that msg.value can only be // used in a payable function---this restriction actually applies to the // caller of this `initialize` function, Deposit.initializeDeposit. /* solium-disable-next-line value-in-payable */ _d.keepAddress = _d.tbtcSystem.requestNewKeep.value(msg.value)( _lotSizeSatoshis, TBTCConstants.getDepositTerm() ); require(_d.fetchBondAmount() >= _d.keepSetupFee, "Insufficient signer bonds to cover setup fee"); _d.signerFeeDivisor = _d.tbtcSystem.getSignerFeeDivisor(); _d.undercollateralizedThresholdPercent = _d.tbtcSystem.getUndercollateralizedThresholdPercent(); _d.severelyUndercollateralizedThresholdPercent = _d.tbtcSystem.getSeverelyUndercollateralizedThresholdPercent(); _d.initialCollateralizedPercent = _d.tbtcSystem.getInitialCollateralizedPercent(); _d.signingGroupRequestedAt = block.timestamp; _d.setAwaitingSignerSetup(); _d.logCreated(_d.keepAddress); } /// @notice Anyone may notify the contract that signing group setup has timed out. /// @param _d Deposit storage pointer. function notifySignerSetupFailed(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingSignerSetup(), "Not awaiting setup"); require( block.timestamp > _d.signingGroupRequestedAt.add(TBTCConstants.getSigningGroupFormationTimeout()), "Signing group formation timeout not yet elapsed" ); // refund the deposit owner the cost to create a new Deposit at the time the Deposit was opened. uint256 _seized = _d.seizeSignerBonds(); if(_seized >= _d.keepSetupFee){ /* solium-disable-next-line security/no-send */ _d.enableWithdrawal(_d.depositOwner(), _d.keepSetupFee); _d.pushFundsToKeepGroup(_seized.sub(_d.keepSetupFee)); } _d.setFailedSetup(); _d.logSetupFailed(); fundingTeardown(_d); } /// @notice we poll the Keep contract to retrieve our pubkey. /// @dev We store the pubkey as 2 bytestrings, X and Y. /// @param _d Deposit storage pointer. /// @return True if successful, otherwise revert. function retrieveSignerPubkey(DepositUtils.Deposit storage _d) public { require(_d.inAwaitingSignerSetup(), "Not currently awaiting signer setup"); bytes memory _publicKey = IBondedECDSAKeep(_d.keepAddress).getPublicKey(); require(_publicKey.length == 64, "public key not set or not 64-bytes long"); _d.signingGroupPubkeyX = _publicKey.slice(0, 32).toBytes32(); _d.signingGroupPubkeyY = _publicKey.slice(32, 32).toBytes32(); require(_d.signingGroupPubkeyY != bytes32(0) && _d.signingGroupPubkeyX != bytes32(0), "Keep returned bad pubkey"); _d.fundingProofTimerStart = block.timestamp; _d.setAwaitingBTCFundingProof(); _d.logRegisteredPubkey( _d.signingGroupPubkeyX, _d.signingGroupPubkeyY); } /// @notice Anyone may notify the contract that the funder has failed to /// prove that they have sent BTC in time. /// @dev This is considered a funder fault, and the funder's payment for /// opening the deposit is not refunded. Reverts if the funding timeout /// has not yet elapsed, or if the deposit is not currently awaiting /// funding proof. /// @param _d Deposit storage pointer. function notifyFundingTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingBTCFundingProof(), "Funding timeout has not started"); require( block.timestamp > _d.fundingProofTimerStart.add(TBTCConstants.getFundingTimeout()), "Funding timeout has not elapsed." ); _d.setFailedSetup(); _d.logSetupFailed(); _d.closeKeep(); fundingTeardown(_d); } /// @notice Requests a funder abort for a failed-funding deposit; that is, /// requests return of a sent UTXO to `_abortOutputScript`. This can /// be used for example when a UTXO is sent that is the wrong size /// for the lot. Must be called after setup fails for any reason, /// and imposes no requirement or incentive on the signing group to /// return the UTXO. /// @dev This is a self-admitted funder fault, and should only be callable /// by the TDT holder. /// @param _d Deposit storage pointer. /// @param _abortOutputScript The output script the funder wishes to request /// a return of their UTXO to. function requestFunderAbort( DepositUtils.Deposit storage _d, bytes memory _abortOutputScript ) public { // not external to allow bytes memory parameters require( _d.inFailedSetup(), "The deposit has not failed funding" ); _d.logFunderRequestedAbort(_abortOutputScript); } /// @notice Anyone can provide a signature that was not requested to prove fraud during funding. /// @dev Calls out to the keep to verify if there was fraud. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. /// @return True if successful, otherwise revert. function provideFundingECDSAFraudProof( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters require( _d.inAwaitingBTCFundingProof(), "Signer fraud during funding flow only available while awaiting funding" ); _d.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage); _d.logFraudDuringSetup(); // Allow deposit owner to withdraw seized bonds after contract termination. uint256 _seized = _d.seizeSignerBonds(); _d.enableWithdrawal(_d.depositOwner(), _seized); fundingFraudTeardown(_d); _d.setFailedSetup(); _d.logSetupFailed(); } /// @notice Anyone may notify the deposit of a funding proof to activate the deposit. /// This is the happy-path of the funding flow. It means that we have succeeded. /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first. function provideBTCFundingProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters require(_d.inAwaitingBTCFundingProof(), "Not awaiting funding"); bytes8 _valueBytes; bytes memory _utxoOutpoint; (_valueBytes, _utxoOutpoint) = _d.validateAndParseFundingSPVProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); // Write down the UTXO info and set to active. Congratulations :) _d.utxoValueBytes = _valueBytes; _d.utxoOutpoint = _utxoOutpoint; _d.fundedAt = block.timestamp; bytes32 _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); fundingTeardown(_d); _d.setActive(); _d.logFunded(_txid); } } pragma solidity 0.5.17; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {CheckBitcoinSigs} from "@summa-tx/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositStates} from "./DepositStates.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {DepositLiquidation} from "./DepositLiquidation.sol"; library DepositRedemption { using SafeMath for uint256; using CheckBitcoinSigs for bytes; using BytesLib for bytes; using BTCUtils for bytes; using ValidateSPV for bytes; using ValidateSPV for bytes32; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Pushes signer fee to the Keep group by transferring it to the Keep address. /// @dev Approves the keep contract, then expects it to call transferFrom. function distributeSignerFee(DepositUtils.Deposit storage _d) internal { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _d.tbtcToken.approve(_d.keepAddress, _d.signerFeeTbtc()); _keep.distributeERC20Reward(address(_d.tbtcToken), _d.signerFeeTbtc()); } /// @notice Approves digest for signing by a keep. /// @dev Calls given keep to sign the digest. Records a current timestamp /// for given digest. /// @param _digest Digest to approve. function approveDigest(DepositUtils.Deposit storage _d, bytes32 _digest) internal { IBondedECDSAKeep(_d.keepAddress).sign(_digest); _d.approvedDigests[_digest] = block.timestamp; } /// @notice Handles TBTC requirements for redemption. /// @dev Burns or transfers depending on term and supply-peg impact. /// Once these transfers complete, the deposit balance should be /// sufficient to pay out signer fees once the redemption transaction /// is proven on the Bitcoin side. function performRedemptionTbtcTransfers(DepositUtils.Deposit storage _d) internal { address tdtHolder = _d.depositOwner(); address frtHolder = _d.feeRebateTokenHolder(); address vendingMachineAddress = _d.vendingMachineAddress; ( uint256 tbtcOwedToDeposit, uint256 tbtcOwedToTdtHolder, uint256 tbtcOwedToFrtHolder ) = _d.calculateRedemptionTbtcAmounts(_d.redeemerAddress, false); if(tbtcOwedToDeposit > 0){ _d.tbtcToken.transferFrom(msg.sender, address(this), tbtcOwedToDeposit); } if(tbtcOwedToTdtHolder > 0){ if(tdtHolder == vendingMachineAddress){ _d.tbtcToken.burn(tbtcOwedToTdtHolder); } else { _d.tbtcToken.transfer(tdtHolder, tbtcOwedToTdtHolder); } } if(tbtcOwedToFrtHolder > 0){ _d.tbtcToken.transfer(frtHolder, tbtcOwedToFrtHolder); } } function _requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _redeemer ) internal { require(_d.inRedeemableState(), "Redemption only available from Active or Courtesy state"); bytes memory _output = abi.encodePacked(_outputValueBytes, _redeemerOutputScript); require(_output.extractHash().length > 0, "Output script must be a standard type"); // set redeemerAddress early to enable direct access by other functions _d.redeemerAddress = _redeemer; performRedemptionTbtcTransfers(_d); // Convert the 8-byte LE ints to uint256 uint256 _outputValue = abi.encodePacked(_outputValueBytes).reverseEndianness().bytesToUint(); uint256 _requestedFee = _d.utxoValue().sub(_outputValue); require(_requestedFee >= TBTCConstants.getMinimumRedemptionFee(), "Fee is too low"); require( _requestedFee < _d.utxoValue() / 2, "Initial fee cannot exceed half of the deposit's value" ); // Calculate the sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _outputValueBytes, _redeemerOutputScript); // write all request details _d.redeemerOutputScript = _redeemerOutputScript; _d.initialRedemptionFee = _requestedFee; _d.latestRedemptionFee = _requestedFee; _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( _redeemer, _sighash, _d.utxoValue(), _redeemerOutputScript, _requestedFee, _d.utxoOutpoint); } /// @notice Anyone can request redemption as long as they can. /// approve the TDT transfer to the final recipient. /// @dev The redeemer specifies details about the Bitcoin redemption tx and pays for the redemption /// on behalf of _finalRecipient. /// @param _d Deposit storage pointer. /// @param _outputValueBytes The 8-byte LE output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { // not external to allow bytes memory parameters _d.tbtcDepositToken.transferFrom(msg.sender, _finalRecipient, uint256(address(this))); _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, _finalRecipient); } /// @notice Only TDT holder can request redemption, /// unless Deposit is expired or in COURTESY_CALL. /// @dev The redeemer specifies details about the Bitcoin redemption transaction. /// @param _d Deposit storage pointer. /// @param _outputValueBytes The 8-byte LE output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. function requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, msg.sender); } /// @notice Anyone may provide a withdrawal signature if it was requested. /// @dev The signers will be penalized if this (or provideRedemptionProof) is not called. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. Should be in the low half of secp256k1 curve's order. function provideRedemptionSignature( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s ) external { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); // If we're outside of the signature window, we COULD punish signers here // Instead, we consider this a no-harm-no-foul situation. // The signers have not stolen funds. Most likely they've just inconvenienced someone // Validate `s` value for a malleability concern described in EIP-2. // Only signatures with `s` value in the lower half of the secp256k1 // curve's order are considered valid. require( uint256(_s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Malleable signature - s should be in the low half of secp256k1 curve's order" ); // The signature must be valid on the pubkey require( _d.signerPubkey().checkSig( _d.lastRequestedDigest, _v, _r, _s ), "Invalid signature" ); // A signature has been provided, now we wait for fee bump or redemption _d.setAwaitingWithdrawalProof(); _d.logGotRedemptionSignature( _d.lastRequestedDigest, _r, _s); } /// @notice Anyone may notify the contract that a fee bump is needed. /// @dev This sends us back to AWAITING_WITHDRAWAL_SIGNATURE. /// @param _d Deposit storage pointer. /// @param _previousOutputValueBytes The previous output's value. /// @param _newOutputValueBytes The new output's value. function increaseRedemptionFee( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public { require(_d.inAwaitingWithdrawalProof(), "Fee increase only available after signature provided"); require(block.timestamp >= _d.withdrawalRequestTime.add(TBTCConstants.getIncreaseFeeTimer()), "Fee increase not yet permitted"); uint256 _newOutputValue = checkRelationshipToPrevious(_d, _previousOutputValueBytes, _newOutputValueBytes); // If the fee bump shrinks the UTXO value below the minimum allowed // value, clamp it to that minimum. Further fee bumps will be disallowed // by checkRelationshipToPrevious. if (_newOutputValue < TBTCConstants.getMinimumUtxoValue()) { _newOutputValue = TBTCConstants.getMinimumUtxoValue(); } _d.latestRedemptionFee = _d.utxoValue().sub(_newOutputValue); // Calculate the next sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _newOutputValueBytes, _d.redeemerOutputScript); // Ratchet the signature and redemption proof timeouts _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); // Go back to waiting for a signature _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( msg.sender, _sighash, _d.utxoValue(), _d.redeemerOutputScript, _d.latestRedemptionFee, _d.utxoOutpoint); } function checkRelationshipToPrevious( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public view returns (uint256 _newOutputValue){ // Check that we're incrementing the fee by exactly the redeemer's initial fee uint256 _previousOutputValue = DepositUtils.bytes8LEToUint(_previousOutputValueBytes); _newOutputValue = DepositUtils.bytes8LEToUint(_newOutputValueBytes); require(_previousOutputValue.sub(_newOutputValue) == _d.initialRedemptionFee, "Not an allowed fee step"); // Calculate the previous one so we can check that it really is the previous one bytes32 _previousSighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _previousOutputValueBytes, _d.redeemerOutputScript); require( _d.wasDigestApprovedForSigning(_previousSighash) == _d.withdrawalRequestTime, "Provided previous value does not yield previous sighash" ); } /// @notice Anyone may provide a withdrawal proof to prove redemption. /// @dev The signers will be penalized if this is not called. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block. /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed). /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers. function provideRedemptionProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters bytes32 _txid; uint256 _fundingOutputValue; require(_d.inRedemption(), "Redemption proof only allowed from redemption flow"); _fundingOutputValue = redemptionTransactionChecks(_d, _txInputVector, _txOutputVector); _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); _d.checkProofFromTxId(_txid, _merkleProof, _txIndexInBlock, _bitcoinHeaders); require((_d.utxoValue().sub(_fundingOutputValue)) <= _d.latestRedemptionFee, "Incorrect fee amount"); // Transfer TBTC to signers and close the keep. distributeSignerFee(_d); _d.closeKeep(); _d.distributeFeeRebate(); // We're done yey! _d.setRedeemed(); _d.redemptionTeardown(); _d.logRedeemed(_txid); } /// @notice Check the redemption transaction input and output vector to ensure the transaction spends /// the correct UTXO and sends value to the appropriate public key hash. /// @dev We only look at the first input and first output. Revert if we find the wrong UTXO or value recipient. /// It's safe to look at only the first input/output as anything that breaks this can be considered fraud /// and can be caught by ECDSAFraudProof. /// @param _d Deposit storage pointer. /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @return The value sent to the redeemer's public key hash. function redemptionTransactionChecks( DepositUtils.Deposit storage _d, bytes memory _txInputVector, bytes memory _txOutputVector ) public view returns (uint256) { require(_txInputVector.validateVin(), "invalid input vector provided"); require(_txOutputVector.validateVout(), "invalid output vector provided"); bytes memory _input = _txInputVector.slice(1, _txInputVector.length-1); require( keccak256(_input.extractOutpoint()) == keccak256(_d.utxoOutpoint), "Tx spends the wrong UTXO" ); bytes memory _output = _txOutputVector.slice(1, _txOutputVector.length-1); bytes memory _expectedOutputScript = _d.redeemerOutputScript; require(_output.length - 8 >= _d.redeemerOutputScript.length, "Output script is too short to extract the expected script"); require( keccak256(_output.slice(8, _expectedOutputScript.length)) == keccak256(_expectedOutputScript), "Tx sends value to wrong output script" ); return (uint256(_output.extractValue())); } /// @notice Anyone may notify the contract that the signers have failed to produce a signature. /// @dev This is considered fraud, and is punished. /// @param _d Deposit storage pointer. function notifyRedemptionSignatureTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getSignatureTimeout()), "Signature timer has not elapsed"); _d.startLiquidation(false); // not fraud, just failure } /// @notice Anyone may notify the contract that the signers have failed to produce a redemption proof. /// @dev This is considered fraud, and is punished. /// @param _d Deposit storage pointer. function notifyRedemptionProofTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingWithdrawalProof(), "Not currently awaiting a redemption proof"); require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getRedemptionProofTimeout()), "Proof timer has not elapsed"); _d.startLiquidation(false); // not fraud, just failure } } pragma solidity 0.5.17; library TBTCConstants { // This is intended to make it easy to update system params // During testing swap this out with another constats contract // System Parameters uint256 public constant BENEFICIARY_FEE_DIVISOR = 1000; // 1/1000 = 10 bps = 0.1% = 0.001 uint256 public constant SATOSHI_MULTIPLIER = 10 ** 10; // multiplier to convert satoshi to TBTC token units uint256 public constant DEPOSIT_TERM_LENGTH = 180 * 24 * 60 * 60; // 180 days in seconds uint256 public constant TX_PROOF_DIFFICULTY_FACTOR = 6; // confirmations on the Bitcoin chain // Redemption Flow uint256 public constant REDEMPTION_SIGNATURE_TIMEOUT = 2 * 60 * 60; // seconds uint256 public constant INCREASE_FEE_TIMER = 4 * 60 * 60; // seconds uint256 public constant REDEMPTION_PROOF_TIMEOUT = 6 * 60 * 60; // seconds uint256 public constant MINIMUM_REDEMPTION_FEE = 2000; // satoshi uint256 public constant MINIMUM_UTXO_VALUE = 2000; // satoshi // Funding Flow uint256 public constant FUNDING_PROOF_TIMEOUT = 3 * 60 * 60; // seconds uint256 public constant FORMATION_TIMEOUT = 3 * 60 * 60; // seconds // Liquidation Flow uint256 public constant COURTESY_CALL_DURATION = 6 * 60 * 60; // seconds uint256 public constant AUCTION_DURATION = 24 * 60 * 60; // seconds // Getters for easy access function getBeneficiaryRewardDivisor() external pure returns (uint256) { return BENEFICIARY_FEE_DIVISOR; } function getSatoshiMultiplier() external pure returns (uint256) { return SATOSHI_MULTIPLIER; } function getDepositTerm() external pure returns (uint256) { return DEPOSIT_TERM_LENGTH; } function getTxProofDifficultyFactor() external pure returns (uint256) { return TX_PROOF_DIFFICULTY_FACTOR; } function getSignatureTimeout() external pure returns (uint256) { return REDEMPTION_SIGNATURE_TIMEOUT; } function getIncreaseFeeTimer() external pure returns (uint256) { return INCREASE_FEE_TIMER; } function getRedemptionProofTimeout() external pure returns (uint256) { return REDEMPTION_PROOF_TIMEOUT; } function getMinimumRedemptionFee() external pure returns (uint256) { return MINIMUM_REDEMPTION_FEE; } function getMinimumUtxoValue() external pure returns (uint256) { return MINIMUM_UTXO_VALUE; } function getFundingTimeout() external pure returns (uint256) { return FUNDING_PROOF_TIMEOUT; } function getSigningGroupFormationTimeout() external pure returns (uint256) { return FORMATION_TIMEOUT; } function getCourtesyCallTimeout() external pure returns (uint256) { return COURTESY_CALL_DURATION; } function getAuctionDuration() external pure returns (uint256) { return AUCTION_DURATION; } } pragma solidity 0.5.17; import {DepositLog} from "../DepositLog.sol"; import {DepositUtils} from "./DepositUtils.sol"; library OutsourceDepositLogging { /// @notice Fires a Created event. /// @dev `DepositLog.logCreated` fires a Created event with /// _keepAddress, msg.sender and block.timestamp. /// msg.sender will be the calling Deposit's address. /// @param _keepAddress The address of the associated keep. function logCreated(DepositUtils.Deposit storage _d, address _keepAddress) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logCreated(_keepAddress); } /// @notice Fires a RedemptionRequested event. /// @dev This is the only event without an explicit timestamp. /// @param _redeemer The ethereum address of the redeemer. /// @param _digest The calculated sighash digest. /// @param _utxoValue The size of the utxo in sat. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _requestedFee The redeemer or bump-system specified fee. /// @param _outpoint The 36 byte outpoint. /// @return True if successful, else revert. function logRedemptionRequested( DepositUtils.Deposit storage _d, address _redeemer, bytes32 _digest, uint256 _utxoValue, bytes memory _redeemerOutputScript, uint256 _requestedFee, bytes memory _outpoint ) public { // not external to allow bytes memory parameters DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRedemptionRequested( _redeemer, _digest, _utxoValue, _redeemerOutputScript, _requestedFee, _outpoint ); } /// @notice Fires a GotRedemptionSignature event. /// @dev We append the sender, which is the deposit contract that called. /// @param _digest Signed digest. /// @param _r Signature r value. /// @param _s Signature s value. /// @return True if successful, else revert. function logGotRedemptionSignature( DepositUtils.Deposit storage _d, bytes32 _digest, bytes32 _r, bytes32 _s ) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logGotRedemptionSignature( _digest, _r, _s ); } /// @notice Fires a RegisteredPubkey event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logRegisteredPubkey( DepositUtils.Deposit storage _d, bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY ) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRegisteredPubkey( _signingGroupPubkeyX, _signingGroupPubkeyY); } /// @notice Fires a SetupFailed event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logSetupFailed(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logSetupFailed(); } /// @notice Fires a FunderAbortRequested event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFunderRequestedAbort( DepositUtils.Deposit storage _d, bytes memory _abortOutputScript ) public { // not external to allow bytes memory parameters DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFunderRequestedAbort(_abortOutputScript); } /// @notice Fires a FraudDuringSetup event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFraudDuringSetup(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFraudDuringSetup(); } /// @notice Fires a Funded event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFunded(DepositUtils.Deposit storage _d, bytes32 _txid) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFunded(_txid); } /// @notice Fires a CourtesyCalled event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logCourtesyCalled(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logCourtesyCalled(); } /// @notice Fires a StartedLiquidation event. /// @dev We append the sender, which is the deposit contract that called. /// @param _wasFraud True if liquidating for fraud. function logStartedLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logStartedLiquidation(_wasFraud); } /// @notice Fires a Redeemed event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logRedeemed(DepositUtils.Deposit storage _d, bytes32 _txid) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRedeemed(_txid); } /// @notice Fires a Liquidated event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logLiquidated(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logLiquidated(); } /// @notice Fires a ExitedCourtesyCall event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logExitedCourtesyCall(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logExitedCourtesyCall(); } } pragma solidity 0.5.17; import {TBTCDepositToken} from "./system/TBTCDepositToken.sol"; // solium-disable function-order // Below, a few functions must be public to allow bytes memory parameters, but // their being so triggers errors because public functions should be grouped // below external functions. Since these would be external if it were possible, // we ignore the issue. contract DepositLog { /* Logging philosophy: Every state transition should fire a log That log should have ALL necessary info for off-chain actors Everyone should be able to ENTIRELY rely on log messages */ // `TBTCDepositToken` mints a token for every new Deposit. // If a token exists for a given ID, we know it is a valid Deposit address. TBTCDepositToken tbtcDepositToken; // This event is fired when we init the deposit event Created( address indexed _depositContractAddress, address indexed _keepAddress, uint256 _timestamp ); // This log event contains all info needed to rebuild the redemption tx // We index on request and signers and digest event RedemptionRequested( address indexed _depositContractAddress, address indexed _requester, bytes32 indexed _digest, uint256 _utxoValue, bytes _redeemerOutputScript, uint256 _requestedFee, bytes _outpoint ); // This log event contains all info needed to build a witnes // We index the digest so that we can search events for the other log event GotRedemptionSignature( address indexed _depositContractAddress, bytes32 indexed _digest, bytes32 _r, bytes32 _s, uint256 _timestamp ); // This log is fired when the signing group returns a public key event RegisteredPubkey( address indexed _depositContractAddress, bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY, uint256 _timestamp ); // This event is fired when we enter the FAILED_SETUP state for any reason event SetupFailed( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when a funder requests funder abort after // FAILED_SETUP has been reached. Funder abort is a voluntary signer action // to return UTXO(s) that were sent to a signer-controlled wallet despite // the funding proofs having failed. event FunderAbortRequested( address indexed _depositContractAddress, bytes _abortOutputScript ); // This event is fired when we detect an ECDSA fraud before seeing a funding proof event FraudDuringSetup( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when we enter the ACTIVE state event Funded( address indexed _depositContractAddress, bytes32 indexed _txid, uint256 _timestamp ); // This event is called when we enter the COURTESY_CALL state event CourtesyCalled( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when we go from COURTESY_CALL to ACTIVE event ExitedCourtesyCall( address indexed _depositContractAddress, uint256 _timestamp ); // This log event is fired when liquidation event StartedLiquidation( address indexed _depositContractAddress, bool _wasFraud, uint256 _timestamp ); // This event is fired when the Redemption SPV proof is validated event Redeemed( address indexed _depositContractAddress, bytes32 indexed _txid, uint256 _timestamp ); // This event is fired when Liquidation is completed event Liquidated( address indexed _depositContractAddress, uint256 _timestamp ); // // Logging // /// @notice Fires a Created event. /// @dev We append the sender, which is the deposit contract that called. /// @param _keepAddress The address of the associated keep. /// @return True if successful, else revert. function logCreated(address _keepAddress) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Created(msg.sender, _keepAddress, block.timestamp); } /// @notice Fires a RedemptionRequested event. /// @dev This is the only event without an explicit timestamp. /// @param _requester The ethereum address of the requester. /// @param _digest The calculated sighash digest. /// @param _utxoValue The size of the utxo in sat. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _requestedFee The requester or bump-system specified fee. /// @param _outpoint The 36 byte outpoint. /// @return True if successful, else revert. function logRedemptionRequested( address _requester, bytes32 _digest, uint256 _utxoValue, bytes memory _redeemerOutputScript, uint256 _requestedFee, bytes memory _outpoint ) public { // not external to allow bytes memory parameters require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit RedemptionRequested( msg.sender, _requester, _digest, _utxoValue, _redeemerOutputScript, _requestedFee, _outpoint ); } /// @notice Fires a GotRedemptionSignature event. /// @dev We append the sender, which is the deposit contract that called. /// @param _digest signed digest. /// @param _r signature r value. /// @param _s signature s value. function logGotRedemptionSignature(bytes32 _digest, bytes32 _r, bytes32 _s) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit GotRedemptionSignature( msg.sender, _digest, _r, _s, block.timestamp ); } /// @notice Fires a RegisteredPubkey event. /// @dev We append the sender, which is the deposit contract that called. function logRegisteredPubkey( bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY ) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit RegisteredPubkey( msg.sender, _signingGroupPubkeyX, _signingGroupPubkeyY, block.timestamp ); } /// @notice Fires a SetupFailed event. /// @dev We append the sender, which is the deposit contract that called. function logSetupFailed() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit SetupFailed(msg.sender, block.timestamp); } /// @notice Fires a FunderAbortRequested event. /// @dev We append the sender, which is the deposit contract that called. function logFunderRequestedAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit FunderAbortRequested(msg.sender, _abortOutputScript); } /// @notice Fires a FraudDuringSetup event. /// @dev We append the sender, which is the deposit contract that called. function logFraudDuringSetup() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit FraudDuringSetup(msg.sender, block.timestamp); } /// @notice Fires a Funded event. /// @dev We append the sender, which is the deposit contract that called. function logFunded(bytes32 _txid) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Funded(msg.sender, _txid, block.timestamp); } /// @notice Fires a CourtesyCalled event. /// @dev We append the sender, which is the deposit contract that called. function logCourtesyCalled() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit CourtesyCalled(msg.sender, block.timestamp); } /// @notice Fires a StartedLiquidation event. /// @dev We append the sender, which is the deposit contract that called. /// @param _wasFraud True if liquidating for fraud. function logStartedLiquidation(bool _wasFraud) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit StartedLiquidation(msg.sender, _wasFraud, block.timestamp); } /// @notice Fires a Redeemed event /// @dev We append the sender, which is the deposit contract that called. function logRedeemed(bytes32 _txid) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Redeemed(msg.sender, _txid, block.timestamp); } /// @notice Fires a Liquidated event /// @dev We append the sender, which is the deposit contract that called. function logLiquidated() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Liquidated(msg.sender, block.timestamp); } /// @notice Fires a ExitedCourtesyCall event /// @dev We append the sender, which is the deposit contract that called. function logExitedCourtesyCall() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit ExitedCourtesyCall(msg.sender, block.timestamp); } /// @notice Sets the tbtcDepositToken contract. /// @dev The contract is used by `approvedToLog` to check if the /// caller is a Deposit contract. This should only be called once. /// @param _tbtcDepositTokenAddress The address of the tbtcDepositToken. function setTbtcDepositToken(TBTCDepositToken _tbtcDepositTokenAddress) internal { require( address(tbtcDepositToken) == address(0), "tbtcDepositToken is already set" ); tbtcDepositToken = _tbtcDepositTokenAddress; } // // AUTH // /// @notice Checks if an address is an allowed logger. /// @dev checks tbtcDepositToken to see if the caller represents /// an existing deposit. /// We don't require this, so deposits are not bricked if the system borks. /// @param _caller The address of the calling contract. /// @return True if approved, otherwise false. function approvedToLog(address _caller) public view returns (bool) { return tbtcDepositToken.exists(uint256(_caller)); } } pragma solidity 0.5.17; import {ERC721Metadata} from "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; import {DepositFactoryAuthority} from "./DepositFactoryAuthority.sol"; import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; /// @title tBTC Deposit Token for tracking deposit ownership /// @notice The tBTC Deposit Token, commonly referenced as the TDT, is an /// ERC721 non-fungible token whose ownership reflects the ownership /// of its corresponding deposit. Each deposit has one TDT, and vice /// versa. Owning a TDT is equivalent to owning its corresponding /// deposit. TDTs can be transferred freely. tBTC's VendingMachine /// contract takes ownership of TDTs and in exchange returns fungible /// TBTC tokens whose value is backed 1-to-1 by the corresponding /// deposit's BTC. /// @dev Currently, TDTs are minted using the uint256 casting of the /// corresponding deposit contract's address. That is, the TDT's id is /// convertible to the deposit's address and vice versa. TDTs are minted /// automatically by the factory during each deposit's initialization. See /// DepositFactory.createNewDeposit() for more info on how the TDT is minted. contract TBTCDepositToken is ERC721Metadata, DepositFactoryAuthority { constructor(address _depositFactoryAddress) ERC721Metadata("tBTC Deposit Token", "TDT") public { initialize(_depositFactoryAddress); } /// @dev Mints a new token. /// Reverts if the given token ID already exists. /// @param _to The address that will own the minted token /// @param _tokenId uint256 ID of the token to be minted function mint(address _to, uint256 _tokenId) external onlyFactory { _mint(_to, _tokenId); } /// @dev Returns whether the specified token exists. /// @param _tokenId uint256 ID of the token to query the existence of. /// @return bool whether the token exists. function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } /// @notice Allow another address to spend on the caller's behalf. /// Set allowance for other address and notify. /// Allows `_spender` to transfer the specified TDT /// on your behalf and then ping the contract about it. /// @dev The `_spender` should implement the `ITokenRecipient` /// interface below to receive approval notifications. /// @param _spender `ITokenRecipient`-conforming contract authorized to /// operate on the approved token. /// @param _tdtId The TDT they can spend. /// @param _extraData Extra information to send to the approved contract. function approveAndCall( ITokenRecipient _spender, uint256 _tdtId, bytes memory _extraData ) public returns (bool) { // not external to allow bytes memory parameters approve(address(_spender), _tdtId); _spender.receiveApproval(msg.sender, _tdtId, address(this), _extraData); return true; } } /* Authored by Satoshi Nakamoto 🤪 */ pragma solidity 0.5.17; import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import {ERC20Detailed} from "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; import {VendingMachineAuthority} from "./VendingMachineAuthority.sol"; import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; /// @title TBTC Token. /// @notice This is the TBTC ERC20 contract. /// @dev Tokens can only be minted by the `VendingMachine` contract. contract TBTCToken is ERC20Detailed, ERC20, VendingMachineAuthority { /// @dev Constructor, calls ERC20Detailed constructor to set Token info /// ERC20Detailed(TokenName, TokenSymbol, NumberOfDecimals) constructor(address _VendingMachine) ERC20Detailed("tBTC", "TBTC", 18) VendingMachineAuthority(_VendingMachine) public { // solium-disable-previous-line no-empty-blocks } /// @dev Mints an amount of the token and assigns it to an account. /// Uses the internal _mint function. /// @param _account The account that will receive the created tokens. /// @param _amount The amount of tokens that will be created. function mint(address _account, uint256 _amount) public onlyVendingMachine returns (bool) { // NOTE: this is a public function with unchecked minting. _mint(_account, _amount); return true; } /// @dev Burns an amount of the token from the given account's balance. /// 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 of tokens that will be burnt. function burnFrom(address _account, uint256 _amount) public { _burnFrom(_account, _amount); } /// @dev Destroys `amount` tokens from `msg.sender`, reducing the /// total supply. /// @param _amount The amount of tokens that will be burnt. function burn(uint256 _amount) public { _burn(msg.sender, _amount); } /// @notice Set allowance for other address and notify. /// Allows `_spender` to spend no more than `_value` /// tokens on your behalf and then ping the contract about /// it. /// @dev The `_spender` should implement the `ITokenRecipient` /// interface to receive approval notifications. /// @param _spender Address of contract authorized to spend. /// @param _value The max amount they can spend. /// @param _extraData Extra information to send to the approved contract. /// @return true if the `_spender` was successfully approved and acted on /// the approval, false (or revert) otherwise. function approveAndCall(ITokenRecipient _spender, uint256 _value, bytes memory _extraData) public returns (bool) { if (approve(address(_spender), _value)) { _spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } return false; } } pragma solidity 0.5.17; /// @title Deposit Factory Authority /// @notice Contract to secure function calls to the Deposit Factory. /// @dev Secured by setting the depositFactory address and using the onlyFactory /// modifier on functions requiring restriction. contract DepositFactoryAuthority { bool internal _initialized = false; address internal _depositFactory; /// @notice Set the address of the System contract on contract /// initialization. /// @dev Since this function is not access-controlled, it should be called /// transactionally with contract instantiation. In cases where a /// regular contract directly inherits from DepositFactoryAuthority, /// that should happen in the constructor. In cases where the inheritor /// is binstead used via a clone factory, the same function that /// creates a new clone should also trigger initialization. function initialize(address _factory) public { require(_factory != address(0), "Factory cannot be the zero address."); require(! _initialized, "Factory can only be initialized once."); _depositFactory = _factory; _initialized = true; } /// @notice Function modifier ensures modified function is only called by set deposit factory. modifier onlyFactory(){ require(_initialized, "Factory initialization must have been called."); require(msg.sender == _depositFactory, "Caller must be depositFactory contract"); _; } } pragma solidity 0.5.17; /// @title TBTC System Authority. /// @notice Contract to secure function calls to the TBTC System contract. /// @dev The `TBTCSystem` contract address is passed as a constructor parameter. contract TBTCSystemAuthority { address internal tbtcSystemAddress; /// @notice Set the address of the System contract on contract initialization. constructor(address _tbtcSystemAddress) public { tbtcSystemAddress = _tbtcSystemAddress; } /// @notice Function modifier ensures modified function is only called by TBTCSystem. modifier onlyTbtcSystem(){ require(msg.sender == tbtcSystemAddress, "Caller must be tbtcSystem contract"); _; } } pragma solidity 0.5.17; /// @title Vending Machine Authority. /// @notice Contract to secure function calls to the Vending Machine. /// @dev Secured by setting the VendingMachine address and using the /// onlyVendingMachine modifier on functions requiring restriction. contract VendingMachineAuthority { address internal VendingMachine; constructor(address _vendingMachine) public { VendingMachine = _vendingMachine; } /// @notice Function modifier ensures modified function caller address is the vending machine. modifier onlyVendingMachine() { require(msg.sender == VendingMachine, "caller must be the vending machine"); _; } } pragma solidity 0.5.17; /// @title Interface of recipient contract for `approveAndCall` pattern. /// Implementors will be able to be used in an `approveAndCall` /// interaction with a supporting contract, such that a token approval /// can call the contract acting on that approval in a single /// transaction. /// /// See the `FundingScript` and `RedemptionScript` contracts as examples. interface ITokenRecipient { /// Typically called from a token contract's `approveAndCall` method, this /// method will receive the original owner of the token (`_from`), the /// transferred `_value` (in the case of an ERC721, the token id), the token /// address (`_token`), and a blob of `_extraData` that is informally /// specified by the implementor of this method as a way to communicate /// additional parameters. /// /// Token calls to `receiveApproval` should revert if `receiveApproval` /// reverts, and reverts should remove the approval. /// /// @param _from The original owner of the token approved for transfer. /// @param _value For an ERC20, the amount approved for transfer; for an /// ERC721, the id of the token approved for transfer. /// @param _token The address of the contract for the token whose transfer /// was approved. /// @param _extraData An additional data blob forwarded unmodified through /// `approveAndCall`, used to allow the token owner to pass /// additional parameters and data to this method. The structure of /// the extra data is informally specified by the implementor of /// this interface. function receiveApproval( address _from, uint256 _value, address _token, bytes calldata _extraData ) external; } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; import "./VendingMachineAuthority.sol"; /// @title Fee Rebate Token /// @notice The Fee Rebate Token (FRT) is a non fungible token (ERC721) /// the ID of which corresponds to a given deposit address. /// If the corresponding deposit is still active, ownership of this token /// could result in reimbursement of the signer fee paid to open the deposit. /// @dev This token is minted automatically when a TDT (`TBTCDepositToken`) /// is exchanged for TBTC (`TBTCToken`) via the Vending Machine (`VendingMachine`). /// When the Deposit is redeemed, the TDT holder will be reimbursed /// the signer fee if the redeemer is not the TDT holder and Deposit is not /// at-term or in COURTESY_CALL. contract FeeRebateToken is ERC721Metadata, VendingMachineAuthority { constructor(address _vendingMachine) ERC721Metadata("tBTC Fee Rebate Token", "FRT") VendingMachineAuthority(_vendingMachine) public { // solium-disable-previous-line no-empty-blocks } /// @dev Mints a new token. /// Reverts if the given token ID already exists. /// @param _to The address that will own the minted token. /// @param _tokenId uint256 ID of the token to be minted. function mint(address _to, uint256 _tokenId) external onlyVendingMachine { _mint(_to, _tokenId); } /// @dev Returns whether the specified token exists. /// @param _tokenId uint256 ID of the token to query the existence of. /// @return bool whether the token exists. function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } } /** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; /// @title ECDSA Keep /// @notice Contract reflecting an ECDSA keep. contract IBondedECDSAKeep { /// @notice Returns public key of this keep. /// @return Keeps's public key. function getPublicKey() external view returns (bytes memory); /// @notice Returns the amount of the keep's ETH bond in wei. /// @return The amount of the keep's ETH bond in wei. function checkBondAmount() external view returns (uint256); /// @notice Calculates a signature over provided digest by the keep. Note that /// signatures from the keep not explicitly requested by calling `sign` /// will be provable as fraud via `submitSignatureFraud`. /// @param _digest Digest to be signed. function sign(bytes32 _digest) external; /// @notice Distributes ETH reward evenly across keep signer beneficiaries. /// @dev Only the value passed to this function is distributed. function distributeETHReward() external payable; /// @notice Distributes ERC20 reward evenly across keep signer beneficiaries. /// @dev This works with any ERC20 token that implements a transferFrom /// function. /// This function only has authority over pre-approved /// token amount. We don't explicitly check for allowance, SafeMath /// subtraction overflow is enough protection. /// @param _tokenAddress Address of the ERC20 token to distribute. /// @param _value Amount of ERC20 token to distribute. function distributeERC20Reward(address _tokenAddress, uint256 _value) external; /// @notice Seizes the signers' ETH bonds. After seizing bonds keep is /// terminated so it will no longer respond to signing requests. Bonds can /// be seized only when there is no signing in progress or requested signing /// process has timed out. This function seizes all of signers' bonds. /// The application may decide to return part of bonds later after they are /// processed using returnPartialSignerBonds function. function seizeSignerBonds() external; /// @notice Returns partial signer's ETH bonds to the pool as an unbounded /// value. This function is called after bonds have been seized and processed /// by the privileged application after calling seizeSignerBonds function. /// It is entirely up to the application if a part of signers' bonds is /// returned. The application may decide for that but may also decide to /// seize bonds and do not return anything. function returnPartialSignerBonds() external payable; /// @notice Submits a fraud proof for a valid signature from this keep that was /// not first approved via a call to sign. /// @dev The function expects the signed digest to be calculated as a sha256 /// hash of the preimage: `sha256(_preimage)`. /// @param _v Signature's header byte: `27 + recoveryID`. /// @param _r R part of ECDSA signature. /// @param _s S part of ECDSA signature. /// @param _signedDigest Digest for the provided signature. Result of hashing /// the preimage. /// @param _preimage Preimage of the hashed message. /// @return True if fraud, error otherwise. function submitSignatureFraud( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes calldata _preimage ) external returns (bool _isFraud); /// @notice Closes keep when no longer needed. Releases bonds to the keep /// members. Keep can be closed only when there is no signing in progress or /// requested signing process has timed out. /// @dev The function can be called only by the owner of the keep and only /// if the keep has not been already closed. function closeKeep() external; } pragma solidity ^0.5.10; /** @title ValidateSPV*/ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {SafeMath} from "./SafeMath.sol"; import {BTCUtils} from "./BTCUtils.sol"; library ValidateSPV { using BTCUtils for bytes; using BTCUtils for uint256; using BytesLib for bytes; using SafeMath for uint256; enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS } enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD } uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe; uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd; function getErrBadLength() internal pure returns (uint256) { return ERR_BAD_LENGTH; } function getErrInvalidChain() internal pure returns (uint256) { return ERR_INVALID_CHAIN; } function getErrLowWork() internal pure returns (uint256) { return ERR_LOW_WORK; } /// @notice Validates a tx inclusion in the block /// @dev `index` is not a reliable indicator of location within a block /// @param _txid The txid (LE) /// @param _merkleRoot The merkle root (as in the block header) /// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root) /// @param _index The leaf's index in the tree (0-indexed) /// @return true if fully valid, false otherwise function prove( bytes32 _txid, bytes32 _merkleRoot, bytes memory _intermediateNodes, uint _index ) internal pure returns (bool) { // Shortcut the empty-block case if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) { return true; } bytes memory _proof = abi.encodePacked(_txid, _intermediateNodes, _merkleRoot); // If the Merkle proof failed, bubble up error return _proof.verifyHash256Merkle(_index); } /// @notice Hashes transaction to get txid /// @dev Supports Legacy and Witness /// @param _version 4-bytes version /// @param _vin Raw bytes length-prefixed input vector /// @param _vout Raw bytes length-prefixed output vector /// @param _locktime 4-byte tx locktime /// @return 32-byte transaction id, little endian function calculateTxId( bytes memory _version, bytes memory _vin, bytes memory _vout, bytes memory _locktime ) internal pure returns (bytes32) { // Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime) return abi.encodePacked(_version, _vin, _vout, _locktime).hash256(); } /// @notice Checks validity of header chain /// @notice Compares the hash of each header to the prevHash in the next header /// @param _headers Raw byte array of header chain /// @return The total accumulated difficulty of the header chain, or an error code function validateHeaderChain(bytes memory _headers) internal view returns (uint256 _totalDifficulty) { // Check header chain length if (_headers.length % 80 != 0) {return ERR_BAD_LENGTH;} // Initialize header start index bytes32 _digest; _totalDifficulty = 0; for (uint256 _start = 0; _start < _headers.length; _start += 80) { // ith header start index and ith header bytes memory _header = _headers.slice(_start, 80); // After the first header, check that headers are in a chain if (_start != 0) { if (!validateHeaderPrevHash(_header, _digest)) {return ERR_INVALID_CHAIN;} } // ith header target uint256 _target = _header.extractTarget(); // Require that the header has sufficient work _digest = _header.hash256View(); if(uint256(_digest).reverseUint256() > _target) { return ERR_LOW_WORK; } // Add ith header difficulty to difficulty sum _totalDifficulty = _totalDifficulty.add(_target.calculateDifficulty()); } } /// @notice Checks validity of header work /// @param _digest Header digest /// @param _target The target threshold /// @return true if header work is valid, false otherwise function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) { if (_digest == bytes32(0)) {return false;} return (abi.encodePacked(_digest).reverseEndianness().bytesToUint() < _target); } /// @notice Checks validity of header chain /// @dev Compares current header prevHash to previous header's digest /// @param _header The raw bytes header /// @param _prevHeaderDigest The previous header's digest /// @return true if the connect is valid, false otherwise function validateHeaderPrevHash(bytes memory _header, bytes32 _prevHeaderDigest) internal pure returns (bool) { // Extract prevHash of current header bytes32 _prevHash = _header.extractPrevBlockLE().toBytes32(); // Compare prevHash of current header to previous header's digest if (_prevHash != _prevHeaderDigest) {return false;} return true; } } pragma solidity ^0.5.10; /** @title CheckBitcoinSigs */ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {BTCUtils} from "./BTCUtils.sol"; library CheckBitcoinSigs { using BytesLib for bytes; using BTCUtils for bytes; /// @notice Derives an Ethereum Account address from a pubkey /// @dev The address is the last 20 bytes of the keccak256 of the address /// @param _pubkey The public key X & Y. Unprefixed, as a 64-byte array /// @return The account address function accountFromPubkey(bytes memory _pubkey) internal pure returns (address) { require(_pubkey.length == 64, "Pubkey must be 64-byte raw, uncompressed key."); // keccak hash of uncompressed unprefixed pubkey bytes32 _digest = keccak256(_pubkey); return address(uint256(_digest)); } /// @notice Calculates the p2wpkh output script of a pubkey /// @dev Compresses keys to 33 bytes as required by Bitcoin /// @param _pubkey The public key, compressed or uncompressed /// @return The p2wkph output script function p2wpkhFromPubkey(bytes memory _pubkey) internal pure returns (bytes memory) { bytes memory _compressedPubkey; uint8 _prefix; if (_pubkey.length == 64) { _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2; _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(0, 32)); } else if (_pubkey.length == 65) { _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2; _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(1, 32)); } else { _compressedPubkey = _pubkey; } require(_compressedPubkey.length == 33, "Witness PKH requires compressed keys"); bytes memory _pubkeyHash = _compressedPubkey.hash160(); return abi.encodePacked(hex"0014", _pubkeyHash); } /// @notice checks a signed message's validity under a pubkey /// @dev does this using ecrecover because Ethereum has no soul /// @param _pubkey the public key to check (64 bytes) /// @param _digest the message digest signed /// @param _v the signature recovery value /// @param _r the signature r value /// @param _s the signature s value /// @return true if signature is valid, else false function checkSig( bytes memory _pubkey, bytes32 _digest, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns (bool) { require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey"); address _expected = accountFromPubkey(_pubkey); address _actual = ecrecover(_digest, _v, _r, _s); return _actual == _expected; } /// @notice checks a signed message against a bitcoin p2wpkh output script /// @dev does this my verifying the p2wpkh matches an ethereum account /// @param _p2wpkhOutputScript the bitcoin output script /// @param _pubkey the uncompressed, unprefixed public key to check /// @param _digest the message digest signed /// @param _v the signature recovery value /// @param _r the signature r value /// @param _s the signature s value /// @return true if signature is valid, else false function checkBitcoinSig( bytes memory _p2wpkhOutputScript, bytes memory _pubkey, bytes32 _digest, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns (bool) { require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey"); bool _isExpectedSigner = keccak256(p2wpkhFromPubkey(_pubkey)) == keccak256(_p2wpkhOutputScript); // is it the expected signer? if (!_isExpectedSigner) {return false;} bool _sigResult = checkSig(_pubkey, _digest, _v, _r, _s); return _sigResult; } /// @notice checks if a message is the sha256 preimage of a digest /// @dev this is NOT the hash256! this step is necessary for ECDSA security! /// @param _digest the digest /// @param _candidate the purported preimage /// @return true if the preimage matches the digest, else false function isSha256Preimage( bytes memory _candidate, bytes32 _digest ) internal pure returns (bool) { return sha256(_candidate) == _digest; } /// @notice checks if a message is the keccak256 preimage of a digest /// @dev this step is necessary for ECDSA security! /// @param _digest the digest /// @param _candidate the purported preimage /// @return true if the preimage matches the digest, else false function isKeccak256Preimage( bytes memory _candidate, bytes32 _digest ) internal pure returns (bool) { return keccak256(_candidate) == _digest; } /// @notice calculates the signature hash of a Bitcoin transaction with the provided details /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputScript the length-prefixed output script /// @return the double-sha256 (hash256) signature hash as defined by bip143 function wpkhSpendSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes memory _outputScript // lenght-prefixed output script ) internal pure returns (bytes32) { // Fixes elements to easily make a 1-in 1-out sighash digest // Does not support timelocks bytes memory _scriptCode = abi.encodePacked( hex"1976a914", // length, dup, hash160, pkh_length _inputPKH, hex"88ac"); // equal, checksig bytes32 _hashOutputs = abi.encodePacked( _outputValue, // 8-byte LE _outputScript).hash256(); bytes memory _sighashPreimage = abi.encodePacked( hex"01000000", // version _outpoint.hash256(), // hashPrevouts hex"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9", // hashSequence(00000000) _outpoint, // outpoint _scriptCode, // p2wpkh script code _inputValue, // value of the input in 8-byte LE hex"00000000", // input nSequence _hashOutputs, // hash of the single output hex"00000000", // nLockTime hex"01000000" // SIGHASH_ALL ); return _sighashPreimage.hash256(); } /// @notice calculates the signature hash of a Bitcoin transaction with the provided details /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey)) /// @return the double-sha256 (hash256) signature hash as defined by bip143 function wpkhToWpkhSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes20 _outputPKH // 20-byte hash160 ) internal pure returns (bytes32) { return wpkhSpendSighash( _outpoint, _inputPKH, _inputValue, _outputValue, abi.encodePacked( hex"160014", // wpkh tag _outputPKH) ); } /// @notice Preserved for API compatibility with older version /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey)) /// @return the double-sha256 (hash256) signature hash as defined by bip143 function oneInputOneOutputSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes20 _outputPKH // 20-byte hash160 ) internal pure returns (bytes32) { return wpkhToWpkhSighash(_outpoint, _inputPKH, _inputValue, _outputValue, _outputPKH); } } pragma solidity ^0.5.0; 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 `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 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(msg.sender, 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 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } 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. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that 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; } } pragma solidity ^0.5.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either `approve` or `setApproveForAll`. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either `approve` or `setApproveForAll`. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } pragma solidity ^0.5.0; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "../../introspection/ERC165.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity ^0.5.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../drafts/Counters.sol"; import "../../introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use `safeTransferFrom` whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `onERC721Received` on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @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) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity ^0.5.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * [EIP](https://eips.ethereum.org/EIPS/eip-165). * * 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 * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * 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); } pragma solidity ^0.5.0; import "./IERC165.sol"; /** * @dev Implementation of the `IERC165` interface. * * Contracts may inherit from this and call `_registerInterface` to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See `IERC165.supportsInterface`. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See `IERC165.supportsInterface`. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } pragma solidity ^0.5.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); }
@notice Extracts the output at a given index in the TxOuts vector @dev Iterates over the vout. If you need to extract multiple, write a custom function @param _vout The _vout to extract from @param _index The 0-indexed location of the output to extract @return The specified output
function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _nOuts; (_varIntDataLen, _nOuts) = parseVarInt(_vout); require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing"); require(_index < _nOuts, "Vout read overrun"); bytes memory _remaining; uint256 _len = 0; uint256 _offset = 1 + _varIntDataLen; for (uint256 _i = 0; _i < _index; _i ++) { _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); _offset += _len; } _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); return _vout.slice(_offset, _len); }
7,283,246
[ 1, 12809, 326, 876, 622, 279, 864, 770, 316, 326, 6424, 1182, 87, 3806, 2868, 3016, 815, 1879, 326, 331, 659, 18, 971, 1846, 1608, 358, 2608, 3229, 16, 1045, 279, 1679, 445, 225, 389, 90, 659, 377, 1021, 389, 90, 659, 358, 2608, 628, 225, 389, 1615, 565, 1021, 374, 17, 19626, 2117, 434, 326, 876, 358, 2608, 327, 1850, 1021, 1269, 876, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 2608, 1447, 24499, 12, 3890, 3778, 389, 90, 659, 16, 2254, 5034, 389, 1615, 13, 2713, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 2254, 5034, 389, 1401, 1702, 751, 2891, 31, 203, 3639, 2254, 5034, 389, 82, 1182, 87, 31, 203, 203, 3639, 261, 67, 1401, 1702, 751, 2891, 16, 389, 82, 1182, 87, 13, 273, 1109, 1537, 1702, 24899, 90, 659, 1769, 203, 3639, 2583, 24899, 1401, 1702, 751, 2891, 480, 10359, 67, 16234, 67, 10973, 16, 315, 1994, 5713, 318, 4982, 4562, 1702, 5811, 8863, 203, 3639, 2583, 24899, 1615, 411, 389, 82, 1182, 87, 16, 315, 58, 659, 855, 5713, 318, 8863, 203, 203, 3639, 1731, 3778, 389, 17956, 31, 203, 203, 3639, 2254, 5034, 389, 1897, 273, 374, 31, 203, 3639, 2254, 5034, 389, 3348, 273, 404, 397, 389, 1401, 1702, 751, 2891, 31, 203, 203, 3639, 364, 261, 11890, 5034, 389, 77, 273, 374, 31, 389, 77, 411, 389, 1615, 31, 389, 77, 965, 13, 288, 203, 5411, 389, 17956, 273, 389, 90, 659, 18, 6665, 24899, 3348, 16, 389, 90, 659, 18, 2469, 300, 389, 3348, 1769, 203, 5411, 389, 1897, 273, 4199, 1447, 1782, 24899, 17956, 1769, 203, 5411, 2583, 24899, 1897, 480, 10359, 67, 16234, 67, 10973, 16, 315, 6434, 4562, 1702, 316, 2728, 9581, 856, 8863, 203, 5411, 389, 3348, 1011, 389, 1897, 31, 203, 3639, 289, 203, 203, 3639, 389, 17956, 273, 389, 90, 659, 18, 6665, 24899, 3348, 16, 389, 90, 659, 18, 2469, 300, 389, 3348, 1769, 203, 2 ]
pragma solidity 0.5.11; /* * @author Cryptonomica Ltd.(cryptonomica.net), 2019 * Github: https://github.com/Cryptonomica/ * * 'CryptoSharesFactory' is a smart contract for creating smart contract for cryptoshares. * They can be shares of a real corporation. Every share is an ERC20 + ERC223 Token. * Smart contracts with cryptoshares implement: * 1) Shareholders identity verification (via Cryptonomica.net) and shareholders ledger. * 2) Automatic signing of arbitration clause (dispute resolution agreement) by every new shareholder. * 3) Shareholders voting using 'one share - one vote' principle. * 4) Dividends distribution. Dividends can be paid in xEUR tokens (https://xeuro.online) and/or in Ether. * Smart contract can receive Ether and xEUR and distribute them to shareholders. * Shares can be transferred without restrictions from one Ethereum address to another. But only verified Ethereum * address represents shareholder. Every share not owned by registered shareholder address are considered 'in transfer', * shares 'in transfer' can not vote and can not receive dividends. * * 'CryptoSharesFactory' charges fee in Ether for creating cryptoshares smart contracts. */ /* ========= Libraries */ /** * SafeMath library * source: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol * version: 2f9ae97 (2019-05-24) */ library SafeMath { /** * dev: Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * dev: Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * dev: Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ // function mul(uint256 a, uint256 b) internal pure returns (uint256) { // // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // // benefit is lost if 'b' is also tested. // // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 // if (a == 0) { // return 0; // } // uint256 c = a * b; // require(c / a == b, "SafeMath: multiplication overflow"); // return c; // } /** * dev: Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ // function div(uint256 a, uint256 b) internal pure returns (uint256) { // // Solidity only automatically asserts when dividing by 0 // require(b > 0, "SafeMath: division by zero"); // uint256 c = a / b; // // assert(a == b * c + a % b); // There is no case in which this doesn't hold // return c; // } /** * dev: Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ // function mod(uint256 a, uint256 b) internal pure returns (uint256) { // require(b != 0, "SafeMath: modulo by zero"); // return a % b; // } } /** * @title xEUR smart contract * dev: contract with xEUR tokens, that will be used to pay dividends * see: https://xeuro.online */ contract XEuro { // standard ERC20 balanceOf function function balanceOf(address _account) external view returns (uint); // standard ERC20 transfer function function transfer(address _recipient, uint _amount) external returns (bool); } /** * @title Cryptonomica verification smart contract * dev: Contract that provides identity verification information for given ETH address * see: https://www.cryptonomica.net/#!/verifyEthAddress/ */ contract CryptonomicaVerification { /** * @param _address The address to check * @return 0 if key certificate is not revoked, or Unix time of revocation */ function revokedOn(address _address) external view returns (uint unixTime); /** * @param _address The address to check * @return Unix time, if not zero and time is later than now - identity verified */ function keyCertificateValidUntil(address _address) external view returns (uint unixTime); } /** * @title Contract that will work ERC223 'transfer' function * dev: see: https://github.com/ethereum/EIPs/issues/223 */ contract ERC223ReceivingContract { /** * @notice Standard ERC223 function that will handle incoming token transfers. * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes calldata _data) external; } /* * @title Cryptoshares smart contract * @notice Contract to manage shares of a corporation on the blockchain * Shares are implemented as ERC20/ERC223 tokens. * Contract also implements dividends distribution, shareholders voting, dispute resolution agreement */ contract CryptoShares { using SafeMath for uint256; /* * ID of the contract */ uint public contractNumberInTheLedger; /* * description of the organization or project, can be short text or a link to website, white paper, github/gitlab repo */ string public description; /* ---- Identity verification for shareholders */ CryptonomicaVerification public cryptonomicaVerification; /* * @param _address Address to check * keyCertificateValidUntil: if 0, no key certificate registered for this address. * If key certificate not expired and not revoked, identity verification is valid. */ function addressIsVerifiedByCryptonomica(address _address) public view returns (bool){ return cryptonomicaVerification.keyCertificateValidUntil(_address) > now && cryptonomicaVerification.revokedOn(_address) == 0; } /* ---- xEUR contract */ /* * We will pay dividends in xEUR as well as in Ether * see: https://xeuro.online */ XEuro public xEuro; /* --- ERC-20 variables */ string public name; string public symbol; uint8 public constant decimals = 0; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; /** * stored address that deployed this smart contract to blockchain * it used only in 'init' function (only creator can set initial values for the contract) */ address public creator; /** * Constructor * no args constructor make possible to create contracts with code pre-verified on etherscan.io * (once we verify one contract, all next contracts with the same code and constructor args will be verified on etherscan) */ constructor() public { // if deployed via factory contract, creator is the factory contract creator = msg.sender; } /* --- ERC-20 events */ /* * We use Transfer as in ERC20, not as in ERC223 (https://github.com/ethereum/EIPs/issues/223) * because wallets and etherscan used to detect tokens transfers using ERC20 Transfer event */ event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed _owner, address indexed spender, uint value); /* --- Events for interaction with other smart contracts */ /** * @param from Address that sent transaction * @param toContract Receiver (smart contract) * @param extraData Data sent */ event DataSentToAnotherContract( address indexed from, address indexed toContract, bytes indexed extraData ); /* ===== Arbitration (Dispute Resolution) =======*/ // * Every shareholder to be registered has to sign dispute resolution agreement. /** * Arbitration clause (dispute resolution agreement) text * see: https://en.wikipedia.org/wiki/Arbitration_clause * https://en.wikipedia.org/wiki/Arbitration#Arbitration_agreement */ string public disputeResolutionAgreement; /** * Number of signatures under disputeResolution agreement */ uint256 public disputeResolutionAgreementSignaturesCounter; /** * dev: This struct represent a signature under dispute resolution agreement. * * @param signatureNumber Signature id. Corresponds to disputeResolutionAgreementSignaturesCounter value. * @param shareholderId Id of the shareholder that made this signature (signatory). * @param signatoryRepresentedBy Ethereum address of the person, that signed the agreement * @param signatoryName Legal name of the person that signed agreement. This can be a name of a legal or physical person * @param signatoryRegistrationNumber Registration number of legal entity, or ID number of physical person * @param signatoryAddress Address of the signatory (country/State, ZIP/postal code, city, street, house/building number, * apartment/office number) * @param signedOnUnixTime Timestamp of the signature */ struct Signature { uint signatureNumber; uint shareholderId; address signatoryRepresentedBy; string signatoryName; string signatoryRegistrationNumber; string signatoryAddress; uint signedOnUnixTime; } // signature number => signature data (struct) mapping(uint256 => Signature) public disputeResolutionAgreementSignaturesByNumber; // shareholder address => number of signatures made from this address mapping(address => uint) public addressSignaturesCounter; // shareholder address => ( signature number for this shareholder => signature data) mapping(address => mapping(uint => Signature)) public signaturesByAddress; /** * dev: Event to be emitted when Dispute Resolution agreement was signed by a new person (we call this person 'signatory') * * @param signatureNumber Number of the signature (see 'disputeResolutionAgreementSignaturesCounter') * @param signatoryRepresentedBy Ethereum address of the person who signed disputeResolution agreement * @param signatoryName Name of the person who signed disputeResolution agreement * @param signatoryShareholderId Id of the shareholder that made this signature * @param signatoryRegistrationNumber Registration number of legal entity, or ID number of physical person (string) * @param signatoryAddress Address of the signatory (country/State, ZIP/postal code, city, street, house/building number, apartment/office number) * @param signedOnUnixTime Signature timestamp */ event disputeResolutionAgreementSigned( uint256 indexed signatureNumber, address indexed signatoryRepresentedBy, string signatoryName, uint indexed signatoryShareholderId, string signatoryRegistrationNumber, string signatoryAddress, uint signedOnUnixTime ); /** * @dev This is the function to make a signature of the shareholder under arbitration agreement. * The identity of a person (ETH address) who make a signature has to be verified via Cryptonomica.net verification. * This verification identifies the physical person who owns the key of ETH address. It this physical person is * a representative of a legal person or an other physical person, it's a responsibility of a person who makes transaction * (i.e. verified person) to provide correct data of a person he/she represents, if not he/she considered as acting * in his/her own name and not as representative. * * @param _shareholderId Id of the shareholder * @param _signatoryName Name of the person who signed disputeResolution agreement * @param _signatoryRegistrationNumber Registration number of legal entity, or ID number of physical person * @param _signatoryAddress Address of the signatory (country/State, ZIP/postal code, city, street, house/building number, apartment/office number) */ function signDisputeResolutionAgreement( uint _shareholderId, string memory _signatoryName, string memory _signatoryRegistrationNumber, string memory _signatoryAddress ) private { require( addressIsVerifiedByCryptonomica(msg.sender), "Signer has to be verified on Cryptonomica.net" ); disputeResolutionAgreementSignaturesCounter++; addressSignaturesCounter[msg.sender] = addressSignaturesCounter[msg.sender] + 1; disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatureNumber = disputeResolutionAgreementSignaturesCounter; disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].shareholderId = _shareholderId; disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryRepresentedBy = msg.sender; disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryName = _signatoryName; disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryRegistrationNumber = _signatoryRegistrationNumber; disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryAddress = _signatoryAddress; disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signedOnUnixTime = now; signaturesByAddress[msg.sender][addressSignaturesCounter[msg.sender]] = disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter]; emit disputeResolutionAgreementSigned( disputeResolutionAgreementSignaturesCounter, disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryRepresentedBy, disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryName, disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].shareholderId, disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryRegistrationNumber, disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signatoryAddress, disputeResolutionAgreementSignaturesByNumber[disputeResolutionAgreementSignaturesCounter].signedOnUnixTime ); } /* ===== Shareholders management =============== */ /** * dev: counts all shareholders in smart contract history */ uint public shareholdersCounter; /* * Shares hold by registered shareholders, i.e. not "in transfer" * like 'totalSupply' but counts tokens of registered shareholders only */ uint public registeredShares; /** * dev: keeps address for each shareholder ID/number (according to shareholdersCounter) * if zero -> not a registered shareholder */ mapping(address => uint) public shareholderID; /* * @param shareholderID The same as in shareholderID mapping * @param shareholderEthereumAddress Ethereum address of the shareholder * @param shareholderName Legal name of the shareholder, it can be name of the legal person, or fist and last name * for the physical person * @param shareholderRegistrationNumber Registration number of the legal person or personal ID of the physical person * @param shareholderAddress Shareholder's legal address (house number, street, city, zip, country) * @param shareholderIsLegalPerson True if shareholder is a legal person, false if shareholder is a physical person * @param linkToSignersAuthorityToRepresentTheShareholder Link to ledger/register record or to document that * contains information about person's that manages ETH address authority to represent the shareholder. If shareholder * is a physical person that represents himself/herself can contain "no representation" string * @param balanceOf This is the same as balanceOf(shareholderEthereumAddress), stored here for convenience * (to get all shareholder's data in one request) */ struct Shareholder { uint shareholderID; // 1 address payable shareholderEthereumAddress; // 2 string shareholderName; // 3 string shareholderRegistrationNumber; // 4 string shareholderAddress; // 5 bool shareholderIsLegalPerson; // 6 string linkToSignersAuthorityToRepresentTheShareholder; // 7 uint balanceOf; // 8 } mapping(uint => Shareholder) public shareholdersLedgerByIdNumber; mapping(address => Shareholder) public shareholdersLedgerByEthAddress; event shareholderAddedOrUpdated( uint indexed shareholderID, address shareholderEthereumAddress, bool indexed isLegalPerson, string shareholderName, string shareholderRegistrationNumber, string shareholderAddress, uint shares, bool indexed newRegistration ); /* * @notice Using this function a token holder can register himself as shareholder. * Any share (token) not owned of registered shareholder is considered 'in transfer'. * Shares 'in transfer' can not vote and does not receive dividends. * In the ledger (variables: 'shareholderID', 'shareholderEthereumAddress' and so on ) we store data of all * historical shareholders, * and they persist even if a shareholder transferred all his shares and his 'balanceOf' is zero. * @param _isLegalPerson This indicates if new shareholder is a legal person or physical person. * @param _shareholderName Legal name of the shareholder. If this is different from name registered in Cryptonomica * verification smart contract, we consider a person registered in Cryptonomica smart contract representative of the * shareholder. * @param _shareholderRegistrationNumber Registration number of a legal person or personal ID number for physical person. * @param _shareholderAddress Shareholder's legal address (country/state, street, building/house number, apartment/office number) * * we allow allow change/update shareholder data (if entered incorrectly or some data changed) by calling * this function again by existing shareholder */ function registerAsShareholderAndSignArbitrationAgreement( bool _isLegalPerson, string calldata _shareholderName, string calldata _shareholderRegistrationNumber, string calldata _shareholderAddress, string calldata _linkToSignersAuthorityToRepresentTheShareholder ) external returns (bool success){ require( balanceOf[msg.sender] > 0, "To be registered address has to hold at least one token/share" ); require( addressIsVerifiedByCryptonomica(msg.sender), "Shareholder address has to be verified on Cryptonomica" ); bool newShareholder; uint id; if (shareholderID[msg.sender] == 0) { shareholdersCounter++; id = shareholdersCounter; shareholderID[msg.sender] = id; newShareholder = true; /* add these shares to shares of registered shareholders (i.e. not "in transfer"*/ registeredShares = registeredShares.add(balanceOf[msg.sender]); } else { id = shareholderID[msg.sender]; newShareholder = false; } // 1 shareholdersLedgerByIdNumber[id].shareholderID = id; // 2 shareholdersLedgerByIdNumber[id].shareholderEthereumAddress = msg.sender; // 3 shareholdersLedgerByIdNumber[id].shareholderName = _shareholderName; // 4 shareholdersLedgerByIdNumber[id].shareholderRegistrationNumber = _shareholderRegistrationNumber; // 5 shareholdersLedgerByIdNumber[id].shareholderAddress = _shareholderAddress; // 6 shareholdersLedgerByIdNumber[id].shareholderIsLegalPerson = _isLegalPerson; // 7 shareholdersLedgerByIdNumber[id].linkToSignersAuthorityToRepresentTheShareholder = _linkToSignersAuthorityToRepresentTheShareholder; // 8 shareholdersLedgerByIdNumber[id].balanceOf = balanceOf[msg.sender]; /* copy struct */ shareholdersLedgerByEthAddress[msg.sender] = shareholdersLedgerByIdNumber[id]; emit shareholderAddedOrUpdated( shareholdersLedgerByIdNumber[id].shareholderID, shareholdersLedgerByIdNumber[id].shareholderEthereumAddress, shareholdersLedgerByIdNumber[id].shareholderIsLegalPerson, shareholdersLedgerByIdNumber[id].shareholderName, shareholdersLedgerByIdNumber[id].shareholderRegistrationNumber, shareholdersLedgerByIdNumber[id].shareholderAddress, shareholdersLedgerByIdNumber[id].balanceOf, newShareholder ); /* * even if shareholder updates data he makes new signature under dispute resolution agreement */ signDisputeResolutionAgreement( id, shareholdersLedgerByIdNumber[id].shareholderName, shareholdersLedgerByIdNumber[id].shareholderRegistrationNumber, shareholdersLedgerByIdNumber[id].shareholderAddress ); return true; } /* ---------------- Dividends --------------- */ /** * Time in seconds between dividends distribution rounds. * Next round can be started only if the specified number of seconds has elapsed since the end of the previous round. * See: https://en.wikipedia.org/wiki/Dividend#Dividend_frequency */ uint public dividendsPeriod; /* * @param roundIsRunning Shows if this dividends payouts round is running. * @param sumWeiToPayForOneToken Sum in wei to pay for one token in this round. * @param sumXEurToPayForOneToken Sum in xEUR to pay for one token in this round. * @param allRegisteredShareholders Number of all shareholder registered in whole smart contract. * history, at the moment this round was started. * @shareholdersCounter Number (id) of shareholder to whom last payment was made. * On the start it will be 0, and on the end of the round shareholdersCounter == allRegisteredShareholders. * @registeredShares Number of shares that will receive dividends in this round, i.e. number of shares, * hold by registered shareholder (that's all shares minus shares 'in transfer') * @param roundStartedOnUnixTime Timestamp. * @param roundFinishedOnUnixTime Timestamp. * @param weiForTxFees Amount in wei deposited for this round to reward those who make transactions to distribute * dividends. */ struct DividendsRound { bool roundIsRunning; //............0 uint sumWeiToPayForOneToken; //....1 uint sumXEurToPayForOneToken; //...2 uint allRegisteredShareholders; //.3 uint shareholdersCounter; //.......4 uint registeredShares; //..........5 uint roundStartedOnUnixTime; //....6 uint roundFinishedOnUnixTime; //...7 uint weiForTxFees; //..............8 } /** * 'dividendsRoundsCounter' holds the sequence number of the last (or current) round of dividends payout * We record all historical dividends payouts data */ uint public dividendsRoundsCounter; mapping(uint => DividendsRound) public dividendsRound; /* * @param dividendsRound Number of dividends distribution round. * @param startedBy ETH address that started round (if time to pay dividends, can be started by any ETH address) * @param totalWei Sum in wei that has to be distributed in this round. * @param totalXEur Sum in xEUR that has to be distributed in this round. * @param sharesToPayDividendsTo The same as 'registeredShares' in struct DividendsRound. * @param sumWeiToPayForOneShare Sum in wei to pay for one token in this round. * @param sumXEurToPayForOneShare Sum in xEUR to pay for one token in this round. */ event DividendsPaymentsStarted( uint indexed dividendsRound, //..0 address indexed startedBy, //...1 uint totalWei, //................2 uint totalXEur, //...............3 uint sharesToPayDividendsTo, //..4 uint sumWeiToPayForOneShare, //..5 uint sumXEurToPayForOneShare //..6 ); /** * @param dividendsRound Number of dividends distribution round */ event DividendsPaymentsFinished( uint indexed dividendsRound ); /** * dev: Info about the payment in ETH made to next shareholder */ event DividendsPaymentEther ( bool indexed success, address indexed to, uint shareholderID, uint shares, uint sumWei, uint indexed dividendsRound ); /** * dev: Info about the payment in xEUR made to next shareholder */ event DividendsPaymentXEuro ( bool indexed success, address indexed to, uint shareholderID, uint shares, uint sumXEuro, uint indexed dividendsRound ); /* * @notice This function starts dividend payout round, and can be started from ANY address if the time has come. */ function startDividendsPayments() public returns (bool success) { require( dividendsRound[dividendsRoundsCounter].roundIsRunning == false, "Already running" ); // dividendsRound[dividendsRoundsCounter].roundFinishedOnUnixTime is zero for first round // so it can be started right after contract deploy require(now.sub(dividendsRound[dividendsRoundsCounter].roundFinishedOnUnixTime) > dividendsPeriod, "To early to start" ); require(registeredShares > 0, "No registered shares to distribute dividends to" ); uint sumWeiToPayForOneToken = address(this).balance / registeredShares; uint sumXEurToPayForOneToken = xEuro.balanceOf(address(this)) / registeredShares; require( sumWeiToPayForOneToken > 0 || sumXEurToPayForOneToken > 0, "Nothing to pay" ); // here we start the next dividends payout round: dividendsRoundsCounter++; dividendsRound[dividendsRoundsCounter].roundIsRunning = true; dividendsRound[dividendsRoundsCounter].roundStartedOnUnixTime = now; dividendsRound[dividendsRoundsCounter].registeredShares = registeredShares; dividendsRound[dividendsRoundsCounter].allRegisteredShareholders = shareholdersCounter; dividendsRound[dividendsRoundsCounter].sumWeiToPayForOneToken = sumWeiToPayForOneToken; dividendsRound[dividendsRoundsCounter].sumXEurToPayForOneToken = sumXEurToPayForOneToken; emit DividendsPaymentsStarted( dividendsRoundsCounter, msg.sender, address(this).balance, xEuro.balanceOf(address(this)), registeredShares, sumWeiToPayForOneToken, sumXEurToPayForOneToken ); return true; } /* * @dev Reward for tx distributing dividends was paid * @dividendsRoundNumber Number (Id) of dividends round. * @dividendsToShareholderNumber Shareholder ID, to whom payment was made by the transaction * @dividendsToShareholderAddress Shareholder ETH address, to whom payment was made by the transaction * @feePaidTo Address (ETH), who received the reward (this is the address who send tx to pay dividends to above * stated shareholder * @feeInWei Amount of the reward paid. * @paymentSuccesful Shows if fee payment was successful (msg.sender.send == true) */ event FeeForDividendsDistributionTxPaid( uint indexed dividendsRoundNumber, uint dividendsToShareholderNumber, address dividendsToShareholderAddress, address indexed feePaidTo, uint feeInWei, bool feePaymentSuccesful ); /* * @notice This function pays dividends due to the next shareholder. * dev: This functions is intended to be called by external script (bot), but can be also called manually. * External script can be run by any person interested in distributing dividends. * Script code is open source and published on smart contract's web site and/or on Github. * Technically this functions can be run also manually (acceptable option for small number of shareholders) */ function payDividendsToNext() external returns (bool success) { require( dividendsRound[dividendsRoundsCounter].roundIsRunning, "Dividends payments round is not open" ); dividendsRound[dividendsRoundsCounter].shareholdersCounter = dividendsRound[dividendsRoundsCounter].shareholdersCounter + 1; uint nextShareholderToPayDividends = dividendsRound[dividendsRoundsCounter].shareholdersCounter; uint sumWeiToPayForOneToken = dividendsRound[dividendsRoundsCounter].sumWeiToPayForOneToken; uint sumXEurToPayForOneToken = dividendsRound[dividendsRoundsCounter].sumXEurToPayForOneToken; address payable to = shareholdersLedgerByIdNumber[nextShareholderToPayDividends].shareholderEthereumAddress; if (balanceOf[to] > 0) { if (sumWeiToPayForOneToken > 0) { uint sumWeiToPay = sumWeiToPayForOneToken * balanceOf[to]; // 'send' is the low-level counterpart of 'transfer'. // If the execution fails, the current contract will not stop with an exception, but 'send' will return false. // https://solidity.readthedocs.io/en/v0.5.10/types.html?highlight=send#members-of-addresses // So we use 'send' and not 'transfer' to ensure that execution continues even if sending ether fails. bool result = to.send(sumWeiToPay); emit DividendsPaymentEther( result, to, nextShareholderToPayDividends, balanceOf[to], sumWeiToPay, dividendsRoundsCounter ); } if (sumXEurToPayForOneToken > 0) { uint sumXEuroToPay = sumXEurToPayForOneToken * balanceOf[to]; // if (sumXEuroToPay <= xEuro.balanceOf(address(this))) { bool result = xEuro.transfer(to, sumXEuroToPay); emit DividendsPaymentXEuro( result, to, nextShareholderToPayDividends, sumXEuroToPay, nextShareholderToPayDividends, dividendsRoundsCounter ); // } } } // if the round started shareholdersCounter can not be zero // because to start the round we need at least one registered share and thus at least one registered shareholder uint feeForTxCaller = dividendsRound[dividendsRoundsCounter].weiForTxFees / shareholdersCounter; if ( feeForTxCaller > 0 && msg.sender == tx.origin // < msg.sender is not a contract (to prevent reentrancy) ) { // we use send not transfer (returns false, not fail) bool feePaymentSuccessful = msg.sender.send(feeForTxCaller); emit FeeForDividendsDistributionTxPaid( dividendsRoundsCounter, nextShareholderToPayDividends, to, msg.sender, feeForTxCaller, feePaymentSuccessful ); } // if this is the last registered shareholder for this round // then FINISH the round: if (nextShareholderToPayDividends == shareholdersCounter) { dividendsRound[dividendsRoundsCounter].roundIsRunning = false; dividendsRound[dividendsRoundsCounter].roundFinishedOnUnixTime = now; emit DividendsPaymentsFinished( dividendsRoundsCounter ); } return true; } /* * Interested party can provide funds to pay for dividends distribution. * @param forDividendsRound Number (Id) of dividends payout round. * @param sumInWei Sum in wei received. * @param from Address from which sum was received. * @param currentSum Current sum of wei to reward accounts sending dividends distributing transactions. */ event FundsToPayForDividendsDistributionReceived( uint indexed forDividendsRound, uint sumInWei, address indexed from, uint currentSum ); /* * Function to add funds to reward transactions distributing dividends in this round/ */ function fundDividendsPayout() public payable returns (bool success){ /* We allow this only for running round */ require( dividendsRound[dividendsRoundsCounter].roundIsRunning, "Dividends payout is not running" ); dividendsRound[dividendsRoundsCounter].weiForTxFees = dividendsRound[dividendsRoundsCounter].weiForTxFees + msg.value; emit FundsToPayForDividendsDistributionReceived( dividendsRoundsCounter, msg.value, msg.sender, dividendsRound[dividendsRoundsCounter].weiForTxFees // totalSum ); return true; } /* * @dev startDividendsPayments() and fundDividendsPayout() combined for convenience */ function startDividendsPaymentsAndFundDividendsPayout() external payable returns (bool success) { startDividendsPayments(); return fundDividendsPayout(); } /* ============= ERC20 functions ============ */ /** * dev: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#approve * there is an attack: * https://github.com/CORIONplatform/solidity/issues/6, * https://drive.google.com/file/d/0ByMtMw2hul0EN3NCaVFHSFdxRzA/view * but this function is required by ERC-20: * To prevent attack vectors like the one described on https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/ * and discussed on https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 , * clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before * setting it to another value for the same spender. * THOUGH The contract itself shouldn't enforce it, to allow backwards compatibility with contracts deployed before * * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public returns (bool success){ allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @notice Approve another address to spend tokens from the tokenholder account * dev: Overloaded approve function * See https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/ * @param _spender The address which will spend the funds. * @param _currentValue The current value of allowance for spender * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _currentValue, uint _value) external returns (bool success){ require( allowance[msg.sender][_spender] == _currentValue, "Current value in contract is different than provided current value" ); return approve(_spender, _value); } /** * dev: private function that checks and changes balances and allowances for transfer functions */ function _transferFrom(address _from, address _to, uint _value) private returns (bool success) { require( _to != address(0), "_to was 0x0 address" ); require( !dividendsRound[dividendsRoundsCounter].roundIsRunning, "Transfers blocked while dividends are distributed" ); require( _from == msg.sender || _value <= allowance[_from][msg.sender], "Sender not authorized" ); // check if _from account has the required amount, if not, throw an exception require( _value <= balanceOf[_from], "Account doesn't have required amount" ); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); uint fromId = shareholderID[_from]; uint toId = shareholderID[_to]; if (fromId > 0) { shareholdersLedgerByEthAddress[_from].balanceOf = balanceOf[_from]; shareholdersLedgerByIdNumber[fromId].balanceOf = balanceOf[_from]; } if (toId > 0) { shareholdersLedgerByEthAddress[_to].balanceOf = balanceOf[_to]; shareholdersLedgerByIdNumber[toId].balanceOf = balanceOf[_to]; } if (fromId > 0 && toId == 0) { // shares goes from registered address to unregistered address // subtract from 'registeredShares' registeredShares = registeredShares.sub(_value); } else if (fromId == 0 && toId > 0) { // shares goes from unregistered address to registered address // add to 'registeredShares' registeredShares = registeredShares.add(_value); } // If allowance used, change allowances correspondingly if (_from != msg.sender) { allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); } emit Transfer(_from, _to, _value); return true; } /* * dev: Private function, that calls 'tokenFallback' function if token receiver is a contract. */ function _erc223Call(address _to, uint _value, bytes memory _data) private returns (bool success) { uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); emit DataSentToAnotherContract(msg.sender, _to, _data); } return true; } /** * @notice Transfers tokens from one address to another. * Sender can send own tokens or or those tokens that he is allowed to transfer. * dev: Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transferFrom(address _from, address _to, uint _value) public returns (bool success){ _transferFrom(_from, _to, _value); // see: // https://github.com/Dexaran/ERC223-token-standard/pull/54 // https://github.com/Dexaran/ERC223-token-standard/issues/53 bytes memory empty = hex"00000000"; return _erc223Call(_to, _value, empty); } // end of transferFrom /* * @notice Transfer tokens from tx sender address to another address. * The rest is similar to the 'transferFrom' function. */ function transfer(address _to, uint _value) public returns (bool success){ return transferFrom(msg.sender, _to, _value); } /** * @notice (ERC223) Transfers tokens to another address with additional info. * dev: Overloaded 'transfer' function (ERC223 standard) * See: https://github.com/ethereum/EIPs/issues/223 * https://github.com/Dexaran/ERC223-token-standard/blob/Recommended/ERC223_Token.sol * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint _value, bytes calldata _data) external returns (bool success){ _transferFrom(msg.sender, _to, _value); return _erc223Call(_to, _value, _data); } /* ============= VOTING ================ */ /* * This smart contract implements voting for shareholders of ERC20 tokens based on the principle * "one share - one vote" * It requires external script to count votes. * * Rules: * To start a voting an address have to own at lest one share. * To start a voting, voting creator must provide: * 1) text of the proposal, * 2) number of the block on which voting will be finished and results have to be calculated. * * Every proposal for a contract receives a sequence number that serves as a proposal ID. * To vote 'for' or 'against' voter has to provide proposal ID. * * In most scenarios only votes 'for' can be used, who did not voted 'for' can be considered as voted 'against'. * But our dApp also supports votes 'against' * * To calculate results we collect all voted addresses by an external script, which is also open sourced. * Than we check their balances in tokens on resulting block, and and sum up the voices. * Thus, for the results, the number of tokens of the voter at the moment of voting does not matter * (it should just has at least one). * What matters is the number of tokens on the voter's address on the block where the results should calculated. * * It's like https://www.cryptonomica.net/eth-vote/, but: * 1) for this contract only * 2) to start voting or to vote an address has to be registered as a shareholder, not just to have tokens * */ // Counts all voting created in this smart contract uint public votingCounterForContract; // proposal id => text of the proposal mapping(uint => string) public proposalText; // proposal id => number of voters mapping(uint => uint256) public numberOfVotersFor; mapping(uint => uint256) public numberOfVotersAgainst; // proposal id => (voter id => voter address) mapping(uint => mapping(uint256 => address)) public votedFor; mapping(uint => mapping(uint256 => address)) public votedAgainst; // proposal id => (voter address => voter has voted already) mapping(uint => mapping(address => bool)) public boolVotedFor; mapping(uint => mapping(address => bool)) public boolVotedAgainst; // proposal ID => block number mapping(uint => uint) public resultsInBlock; /* * @param proposalId Number of this voting, according to 'votingCounterForContract' * @param by Address that created proposal * @param proposalText Text of the proposal * @param resultsInBlock Block to calculate results of voting. */ event Proposal( uint indexed proposalID, address indexed by, string proposalText, uint indexed resultsInBlock ); // to run function an address has to be registered as a shareholder and own at least one share modifier onlyShareholder() { require( shareholdersLedgerByEthAddress[msg.sender].shareholderID != 0 && balanceOf[msg.sender] > 0, "Only shareholder can do that" ); _; } /* * @notice Creates proposal for voting. * @param _proposalText Text of the proposal. * @param _resultsInBlock Number of block on which results will be counted. */ function createVoting( string calldata _proposalText, uint _resultsInBlock ) onlyShareholder external returns (bool success){ require( _resultsInBlock > block.number, "Block for results should be later than current block" ); votingCounterForContract++; proposalText[votingCounterForContract] = _proposalText; resultsInBlock[votingCounterForContract] = _resultsInBlock; emit Proposal(votingCounterForContract, msg.sender, proposalText[votingCounterForContract], resultsInBlock[votingCounterForContract]); return true; } // Vote 'for' received event VoteFor( uint indexed proposalID, address indexed by ); // Vote 'against' received event VoteAgainst( uint indexed proposalID, address indexed by ); /* * @notice Vote for the proposal * @param _proposalId Id (number) of the proposal */ function voteFor(uint256 _proposalId) onlyShareholder external returns (bool success){ require( resultsInBlock[_proposalId] > block.number, "Voting already finished" ); require( !boolVotedFor[_proposalId][msg.sender] && !boolVotedAgainst[_proposalId][msg.sender], "Already voted" ); numberOfVotersFor[_proposalId] = numberOfVotersFor[_proposalId] + 1; uint voterId = numberOfVotersFor[_proposalId]; votedFor[_proposalId][voterId] = msg.sender; boolVotedFor[_proposalId][msg.sender] = true; emit VoteFor(_proposalId, msg.sender); return true; } /* * @notice Vote against the proposal * @param _proposalId Id (number) of the proposal */ function voteAgainst(uint256 _proposalId) onlyShareholder external returns (bool success){ require( resultsInBlock[_proposalId] > block.number, "Voting finished" ); require( !boolVotedFor[_proposalId][msg.sender] && !boolVotedAgainst[_proposalId][msg.sender], "Already voted" ); numberOfVotersAgainst[_proposalId] = numberOfVotersAgainst[_proposalId] + 1; uint voterId = numberOfVotersAgainst[_proposalId]; votedAgainst[_proposalId][voterId] = msg.sender; boolVotedAgainst[_proposalId][msg.sender] = true; emit VoteAgainst(_proposalId, msg.sender); return true; } /* * This contract can receive Ether from any address. * Received Ether will be distributed as dividends to shareholders. */ function addEtherToContract() external payable { // gas: 21482 } function() external payable { // gas: 21040 } /* ============= Contract initialization * dev: initializes token: set initial values for erc20 variables * assigns all tokens ('totalSupply') to one address ('tokenOwner') * @param _contractNumberInTheLedger Contract Id. * @param _description Description of the project of organization (short text or just a link) * @param _name Name of the token * @param _symbol Symbol of the token * @param _tokenOwner Address that will initially hold all created tokens * @param _dividendsPeriod Period in seconds between finish of the previous dividends round and start of the next. * On test net can be small. * @param _xEurContractAddress Address of contract with xEUR tokens * (can be different for test net, where we use mock up contract) * @param _cryptonomicaVerificationContractAddress Address of the Cryptonomica verification smart contract * (can be different for test net, where we use mock up contract) * @param _disputeResolutionAgreement Text of the arbitration agreement. */ function initToken( uint _contractNumberInTheLedger, string calldata _description, string calldata _name, string calldata _symbol, uint _dividendsPeriod, address _xEurContractAddress, address _cryptonomicaVerificationContractAddress, string calldata _disputeResolutionAgreement ) external returns (bool success) { require( msg.sender == creator, "Only creator can initialize token contract" ); require( totalSupply == 0, "Contract already initialized" ); contractNumberInTheLedger = _contractNumberInTheLedger; description = _description; name = _name; symbol = _symbol; xEuro = XEuro(_xEurContractAddress); cryptonomicaVerification = CryptonomicaVerification(_cryptonomicaVerificationContractAddress); disputeResolutionAgreement = _disputeResolutionAgreement; dividendsPeriod = _dividendsPeriod; return true; } /* * @dev initToken and issueTokens are separate functions because of * 'Stack too deep' exception from compiler * @param _tokenOwner Address that will get all new created tokens. * @param _totalSupply Amount of tokens to create. */ function issueTokens( uint _totalSupply, address _tokenOwner ) external returns (bool success){ require( msg.sender == creator, "Only creator can initialize token contract" ); require( totalSupply == 0, "Contract already initialized" ); require( _totalSupply > 0, "Number of tokens can not be zero" ); totalSupply = _totalSupply; balanceOf[_tokenOwner] = totalSupply; emit Transfer(address(0), _tokenOwner, _totalSupply); return true; } } /* =================== FACTORY */ /* * dev: Universal functions for smart contract management */ contract ManagedContract { /* * dev: smart contract that provides information about person that owns given Ethereum address/key */ CryptonomicaVerification public cryptonomicaVerification; /* * ledger of admins */ mapping(address => bool) isAdmin; modifier onlyAdmin() { require(isAdmin[msg.sender], "Only admin can do that"); _; } /** * @param from Old address * @param to New address * @param by Who made a change */ event CryptonomicaVerificationContractAddressChanged(address from, address to, address indexed by); /** * @param _newAddress address of new contract to be used to verify identity of new admins */ function changeCryptonomicaVerificationContractAddress(address _newAddress) public onlyAdmin returns (bool success) { emit CryptonomicaVerificationContractAddressChanged(address(cryptonomicaVerification), _newAddress, msg.sender); cryptonomicaVerification = CryptonomicaVerification(_newAddress); return true; } /** * @param added New admin address * @param addedBy Who added new admin */ event AdminAdded( address indexed added, address indexed addedBy ); /** * @param _newAdmin Address of new admin */ function addAdmin(address _newAdmin) public onlyAdmin returns (bool success){ require( cryptonomicaVerification.keyCertificateValidUntil(_newAdmin) > now, "New admin has to be verified on Cryptonomica.net" ); // revokedOn returns uint256 (unix time), it's 0 if verification is not revoked require( cryptonomicaVerification.revokedOn(_newAdmin) == 0, "Verification for this address was revoked, can not add" ); isAdmin[_newAdmin] = true; emit AdminAdded(_newAdmin, msg.sender); return true; } /** * @param removed Removed admin address * @param removedBy Who removed admin */ event AdminRemoved( address indexed removed, address indexed removedBy ); /** * @param _oldAdmin Address to remove from admins */ function removeAdmin(address _oldAdmin) external onlyAdmin returns (bool){ require(msg.sender != _oldAdmin, "Admin can not remove himself"); isAdmin[_oldAdmin] = false; emit AdminRemoved(_oldAdmin, msg.sender); return true; } /* --- financial management */ /* * address to send Ether from this contract */ address payable public withdrawalAddress; /* * withdrawal address can be fixed (protected from changes), */ bool public withdrawalAddressFixed = false; /* * @param from Old address * @param to New address * @param changedBy Who made this change */ event WithdrawalAddressChanged( address indexed from, address indexed to, address indexed changedBy ); /* * @param _withdrawalAddress address to which funds from this contract will be sent */ function setWithdrawalAddress(address payable _withdrawalAddress) public onlyAdmin returns (bool success) { require( !withdrawalAddressFixed, "Withdrawal address already fixed" ); require( _withdrawalAddress != address(0), "Wrong address: 0x0" ); require( _withdrawalAddress != address(this), "Wrong address: contract itself" ); emit WithdrawalAddressChanged(withdrawalAddress, _withdrawalAddress, msg.sender); withdrawalAddress = _withdrawalAddress; return true; } /* * @param withdrawalAddressFixedAs Address for withdrawal * @param fixedBy Address who made this change (msg.sender) * * This event can be fired one time only */ event WithdrawalAddressFixed( address indexed withdrawalAddressFixedAs, address indexed fixedBy ); /** * @param _withdrawalAddress Address to which funds from this contract will be sent. * * @dev This function can be called one time only. */ function fixWithdrawalAddress(address _withdrawalAddress) external onlyAdmin returns (bool success) { // prevents event if already fixed require( !withdrawalAddressFixed, "Can't change, address fixed" ); // check, to prevent fixing wrong address require( withdrawalAddress == _withdrawalAddress, "Wrong address in argument" ); withdrawalAddressFixed = true; emit WithdrawalAddressFixed(withdrawalAddress, msg.sender); return true; } /** * @param to Address to which ETH was sent. * @param sumInWei Sum sent (in wei) * @param by Address, that made withdrawal (msg.sender) * @param success Shows f withdrawal was successful. */ event Withdrawal( address indexed to, uint sumInWei, address indexed by, bool indexed success ); /** * @dev This function can be called by any user or contract. * Possible warning: check for reentrancy vulnerability http://solidity.readthedocs.io/en/develop/security-considerations.html#re-entrancy * Since we are making a withdrawal to our own contract/address only there is no possible attack using reentrancy vulnerability */ function withdrawAllToWithdrawalAddress() external returns (bool success) { // http://solidity.readthedocs.io/en/develop/security-considerations.html#sending-and-receiving-ether // about <address>.send(uint256 amount) and <address>.transfer(uint256 amount) // see: http://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=transfer#address-related // https://ethereum.stackexchange.com/questions/19341/address-send-vs-address-transfer-best-practice-usage uint sum = address(this).balance; if (!withdrawalAddress.send(sum)) {// makes withdrawal and returns true (success) or false emit Withdrawal(withdrawalAddress, sum, msg.sender, false); return false; } emit Withdrawal(withdrawalAddress, sum, msg.sender, true); return true; } } /* * This is a model contract where some paid service provided and there is a price * (in main function we can check if msg.value >= price) */ contract ManagedContractWithPaidService is ManagedContract { /* * Price for creating a new smart contract with shares (in wei) */ uint public price; /* * @param from The old price * @param to The new price * @param by Who changed the price */ event PriceChanged( uint from, uint to, address indexed by ); /* * @param _newPrice The new price for the service */ function changePrice(uint _newPrice) public onlyAdmin returns (bool success){ emit PriceChanged(price, _newPrice, msg.sender); price = _newPrice; return true; } } /* * dev: Smart contract to deploy shares smart contracts and maintain a ledger of deployed contracts. */ contract CryptoSharesFactory is ManagedContractWithPaidService { /** * Arbitration clause (dispute resolution agreement) text * see: https://en.wikipedia.org/wiki/Arbitration_clause * https://en.wikipedia.org/wiki/Arbitration#Arbitration_agreement */ string public disputeResolutionAgreement = "Any dispute, controversy or claim arising out of or relating to this smart contract, including transfer of shares/tokens managed by this smart contract or ownership of the shares/tokens, or any voting managed by this smart contract shall be settled by arbitration in accordance with the Cryptonomica Arbitration Rules (https://github.com/Cryptonomica/arbitration-rules) in the version in effect at the time of the filing of the claim. In the case of the Ethereum blockchain fork, the blockchain that has the highest hashrate is considered valid, and all the others are not considered a valid registry, in case of dispute, dispute should be resolved by arbitration court. All Ethereum test networks are not valid registries."; event DisputeResolutionAgreementTextChanged( string newText, address indexed changedBy ); /* * @param _newText New text for arbitration agreement. This will be used for future shares contracts only and * will not change arbitration agreement text in already deployed shares contracts. */ function changeDisputeResolutionAgreement(string calldata _newText) external onlyAdmin returns (bool success){ disputeResolutionAgreement = _newText; emit DisputeResolutionAgreementTextChanged(_newText, msg.sender); return true; } /* Address of the smart contract with xEUR tokens (see: https://xeuro.online) */ address public xEurContractAddress; /** * @param from Old address * @param to New address * @param by Who made a change */ event XEuroContractAddressChanged( address indexed from, address indexed to, address indexed by ); /** * @param _newAddress Address of new contract for xEUR to be used (for the case that this address changes) * This function makes change only for future shares contracts, and does not change shares contract already deployed. */ function changeXEuroContractAddress(address _newAddress) public onlyAdmin returns (bool success) { emit XEuroContractAddressChanged(xEurContractAddress, _newAddress, msg.sender); xEurContractAddress = _newAddress; return true; } /* ---- Constructor ---- */ constructor() public { isAdmin[msg.sender] = true; changePrice(0.2 ether); setWithdrawalAddress(msg.sender); // Ropsten: > mock up contract, verification always valid for any address changeCryptonomicaVerificationContractAddress(0xE48BC3dB5b512d4A3e3Cd388bE541Be7202285B5); // TODO: change in production to https://etherscan.io/address/0x846942953c3b2A898F10DF1e32763A823bf6b27f <<<<<<< // changeCryptonomicaVerificationContractAddress(0x846942953c3b2A898F10DF1e32763A823bf6b27f); // Ropsten: > mock up contract, allows to create tokens for every address changeXEuroContractAddress(0x9a2A6C32352d85c9fcC5ff0f91fCB9CE42c15030); // TODO: change in production to https://etherscan.io/address/0xe577e0B200d00eBdecbFc1cd3F7E8E04C70476BE <<<<<<< // changeXEuroContractAddress(0xe577e0B200d00eBdecbFc1cd3F7E8E04C70476BE) } // end of constructor() /* ---- Creating and managing CryptoShares smart contracts ---- */ // counts deployed contracts uint public cryptoSharesContractsCounter; /* * This struct contains information about deployed contract; */ struct CryptoSharesContract { uint contractId; address contractAddress; uint deployedOnUnixTime; string name; // the same as token name string symbol; // the same as token symbol uint totalSupply; // the same as token totalSupply uint dividendsPeriod; // period between dividends payout rounds, in seconds } event NewCryptoSharesContractCreated( uint indexed contractId, address indexed contractAddress, string name, // the same as token name string symbol, // the same as token symbol uint totalSupply, // the same as token totalSupply uint dividendsPeriod // period between dividends payout rounds, in seconds ); mapping(uint => CryptoSharesContract) public cryptoSharesContractsLedger; /* * @dev This function creates new shares contracts. * @param _description Description of the project or organization (can be short text or link to web page) * @param _name Name of the token, as required by ERC20. * @param _symbol Symbol for the token, as required by ERC20. * @param _totalSupply Total supply, as required by ERC20. * @param _dividendsPeriodInSeconds Period between dividends payout rounds, in seconds. */ function createCryptoSharesContract( string calldata _description, string calldata _name, string calldata _symbol, uint _totalSupply, uint _dividendsPeriodInSeconds ) external payable returns (bool success){ require( msg.value >= price, "msg.value is less than price" ); CryptoShares cryptoSharesContract = new CryptoShares(); cryptoSharesContractsCounter++; cryptoSharesContract.initToken( cryptoSharesContractsCounter, _description, _name, _symbol, _dividendsPeriodInSeconds, xEurContractAddress, address(cryptonomicaVerification), disputeResolutionAgreement ); cryptoSharesContract.issueTokens( _totalSupply, msg.sender ); cryptoSharesContractsCounter; cryptoSharesContractsLedger[cryptoSharesContractsCounter].contractId = cryptoSharesContractsCounter; cryptoSharesContractsLedger[cryptoSharesContractsCounter].contractAddress = address(cryptoSharesContract); cryptoSharesContractsLedger[cryptoSharesContractsCounter].deployedOnUnixTime = now; cryptoSharesContractsLedger[cryptoSharesContractsCounter].name = cryptoSharesContract.name(); cryptoSharesContractsLedger[cryptoSharesContractsCounter].symbol = cryptoSharesContract.symbol(); cryptoSharesContractsLedger[cryptoSharesContractsCounter].totalSupply = cryptoSharesContract.totalSupply(); cryptoSharesContractsLedger[cryptoSharesContractsCounter].dividendsPeriod = cryptoSharesContract.dividendsPeriod(); emit NewCryptoSharesContractCreated( cryptoSharesContractsLedger[cryptoSharesContractsCounter].contractId, cryptoSharesContractsLedger[cryptoSharesContractsCounter].contractAddress, cryptoSharesContractsLedger[cryptoSharesContractsCounter].name, cryptoSharesContractsLedger[cryptoSharesContractsCounter].symbol, cryptoSharesContractsLedger[cryptoSharesContractsCounter].totalSupply, cryptoSharesContractsLedger[cryptoSharesContractsCounter].dividendsPeriod ); return true; } // end of function createCryptoSharesContract }
dev: Universal functions for smart contract management/ dev: smart contract that provides information about person that owns given Ethereum address/key/ ledger of admins/* @param _newAddress address of new contract to be used to verify identity of new admins/* @param _newAdmin Address of new admin/ revokedOn returns uint256 (unix time), it's 0 if verification is not revoked* @param _oldAdmin Address to remove from admins/ @param _withdrawalAddress address to which funds from this contract will be sent/* @param _withdrawalAddress Address to which funds from this contract will be sent. @dev This function can be called one time only./ prevents event if already fixed check, to prevent fixing wrong address* @dev This function can be called by any user or contract. Possible warning: Since we are making a withdrawal to our own contract/address only there is no possible attack using reentrancy vulnerability/ http:solidity.readthedocs.io/en/develop/security-considerations.html#sending-and-receiving-ether about <address>.send(uint256 amount) and <address>.transfer(uint256 amount) see: http:solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=transfer#address-related https:ethereum.stackexchange.com/questions/19341/address-send-vs-address-transfer-best-practice-usage
contract ManagedContract { CryptonomicaVerification public cryptonomicaVerification; mapping(address => bool) isAdmin; modifier onlyAdmin() { require(isAdmin[msg.sender], "Only admin can do that"); _; } function changeCryptonomicaVerificationContractAddress(address _newAddress) public onlyAdmin returns (bool success) { emit CryptonomicaVerificationContractAddressChanged(address(cryptonomicaVerification), _newAddress, msg.sender); cryptonomicaVerification = CryptonomicaVerification(_newAddress); return true; } address indexed added, address indexed addedBy ); function addAdmin(address _newAdmin) public onlyAdmin returns (bool success){ require( cryptonomicaVerification.keyCertificateValidUntil(_newAdmin) > now, "New admin has to be verified on Cryptonomica.net" ); require( cryptonomicaVerification.revokedOn(_newAdmin) == 0, "Verification for this address was revoked, can not add" ); isAdmin[_newAdmin] = true; emit AdminAdded(_newAdmin, msg.sender); return true; } address indexed removed, address indexed removedBy ); function removeAdmin(address _oldAdmin) external onlyAdmin returns (bool){ require(msg.sender != _oldAdmin, "Admin can not remove himself"); isAdmin[_oldAdmin] = false; emit AdminRemoved(_oldAdmin, msg.sender); return true; } address indexed from, address indexed to, address indexed changedBy ); function setWithdrawalAddress(address payable _withdrawalAddress) public onlyAdmin returns (bool success) { require( !withdrawalAddressFixed, "Withdrawal address already fixed" ); require( _withdrawalAddress != address(0), "Wrong address: 0x0" ); require( _withdrawalAddress != address(this), "Wrong address: contract itself" ); emit WithdrawalAddressChanged(withdrawalAddress, _withdrawalAddress, msg.sender); withdrawalAddress = _withdrawalAddress; return true; } address indexed withdrawalAddressFixedAs, address indexed fixedBy ); function fixWithdrawalAddress(address _withdrawalAddress) external onlyAdmin returns (bool success) { require( !withdrawalAddressFixed, "Can't change, address fixed" ); require( withdrawalAddress == _withdrawalAddress, "Wrong address in argument" ); withdrawalAddressFixed = true; emit WithdrawalAddressFixed(withdrawalAddress, msg.sender); return true; } address indexed to, uint sumInWei, address indexed by, bool indexed success ); function withdrawAllToWithdrawalAddress() external returns (bool success) { uint sum = address(this).balance; emit Withdrawal(withdrawalAddress, sum, msg.sender, false); return false; } emit Withdrawal(withdrawalAddress, sum, msg.sender, true); return true; }
5,359,028
[ 1, 5206, 30, 27705, 4186, 364, 13706, 6835, 11803, 19, 4461, 30, 13706, 6835, 716, 8121, 1779, 2973, 6175, 716, 29065, 864, 512, 18664, 379, 1758, 19, 856, 19, 16160, 434, 31116, 19, 225, 389, 2704, 1887, 1758, 434, 394, 6835, 358, 506, 1399, 358, 3929, 4215, 434, 394, 31116, 19, 225, 389, 2704, 4446, 5267, 434, 394, 3981, 19, 22919, 1398, 1135, 2254, 5034, 261, 21136, 813, 3631, 518, 1807, 374, 309, 11805, 353, 486, 22919, 225, 389, 1673, 4446, 5267, 358, 1206, 628, 31116, 19, 225, 389, 1918, 9446, 287, 1887, 1758, 358, 1492, 284, 19156, 628, 333, 6835, 903, 506, 3271, 19, 225, 389, 1918, 9446, 287, 1887, 5267, 358, 1492, 284, 19156, 628, 333, 6835, 903, 506, 3271, 18, 225, 1220, 445, 848, 506, 2566, 1245, 813, 1338, 18, 19, 17793, 871, 309, 1818, 5499, 866, 16, 358, 5309, 28716, 7194, 1758, 225, 1220, 445, 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, 16351, 10024, 8924, 288, 203, 203, 565, 22752, 4708, 26433, 13483, 1071, 13231, 4708, 26433, 13483, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 23467, 31, 203, 203, 565, 9606, 1338, 4446, 1435, 288, 203, 3639, 2583, 12, 291, 4446, 63, 3576, 18, 15330, 6487, 315, 3386, 3981, 848, 741, 716, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 565, 445, 2549, 22815, 4708, 26433, 13483, 8924, 1887, 12, 2867, 389, 2704, 1887, 13, 1071, 1338, 4446, 1135, 261, 6430, 2216, 13, 288, 203, 203, 3639, 3626, 22752, 4708, 26433, 13483, 8924, 1887, 5033, 12, 2867, 12, 22784, 4708, 26433, 13483, 3631, 389, 2704, 1887, 16, 1234, 18, 15330, 1769, 203, 203, 3639, 13231, 4708, 26433, 13483, 273, 22752, 4708, 26433, 13483, 24899, 2704, 1887, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 3639, 1758, 8808, 3096, 16, 203, 3639, 1758, 8808, 3096, 858, 203, 565, 11272, 203, 203, 565, 445, 527, 4446, 12, 2867, 389, 2704, 4446, 13, 1071, 1338, 4446, 1135, 261, 6430, 2216, 15329, 203, 203, 3639, 2583, 12, 203, 5411, 13231, 4708, 26433, 13483, 18, 856, 4719, 1556, 9716, 24899, 2704, 4446, 13, 405, 2037, 16, 203, 5411, 315, 1908, 3981, 711, 358, 506, 13808, 603, 22752, 4708, 26433, 18, 2758, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 13231, 4708, 26433, 13483, 18, 9083, 14276, 1398, 24899, 2704, 4446, 13, 422, 374, 16, 203, 5411, 315, 13483, 364, 333, 1758, 1703, 22919, 16, 848, 486, 527, 6, 2 ]
// Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title 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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, 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; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, 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; } } /** * @title SchedulableToken * @dev The SchedulableToken provide a method to create tokens progressively, in a gradual * and programed way, until a specified date and amount. To effectively create tokens, it * is necessary for someone to periodically run the release() function in the contract. * For example: You want to create a total of 1000 tokens (maxSupply) spread over 2 years (duration). * In this way, when calling the release() function, the number of tokens that are entitled at * that moment will be added to the beneficiary&#39;s wallet. In this scenario, by running the * release() function every day at the same time over 2 years, the beneficiary will receive * 1.37 tokens (1000 / 364.25 * 2) everyday. * @author Anselmo Zago (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8cede2ffe9e0e1e3cce0e9f8ffeaede5fea2e3feeb">[email&#160;protected]</a>), based in TokenVesting by Zeppelin Solidity library. */ contract SchedulableToken is StandardToken, BurnableToken { using SafeMath for uint256; event Released(uint256 amount); address public beneficiary; uint256 public maxSupply; uint256 public start; uint256 public duration; /** * @dev Constructor of the SchedulableToken contract that releases the tokens gradually and * programmatically. The balance will be assigned to _beneficiary in the maximum amount of * _maxSupply, divided proportionally during the _duration period. * @param _beneficiary address of the beneficiary to whom schedulable tokens will be added * @param _maxSupply schedulable token max supply * @param _duration duration in seconds of the period in which the tokens will released */ function SchedulableToken(address _beneficiary, uint256 _maxSupply, uint256 _duration) public { require(_beneficiary != address(0)); require(_maxSupply > 0); require(_duration > 0); beneficiary = _beneficiary; maxSupply = _maxSupply; duration = _duration; start = now; } /** * @notice Transfers schedulable tokens to beneficiary. */ function release() public { uint256 amount = calculateAmountToRelease(); require(amount > 0); balances[beneficiary] = balances[beneficiary].add(amount); totalSupply = totalSupply.add(amount); Released(amount); } /** * @dev Calculates the amount of tokens by right, until that moment. */ function calculateAmountToRelease() public view returns (uint256) { if (now < start.add(duration)) { return maxSupply.mul(now.sub(start)).div(duration).sub(totalSupply); } else { return schedulableAmount(); } } /** * @dev Returns the total amount that still to be released by the end of the duration. */ function schedulableAmount() public view returns (uint256) { return maxSupply.sub(totalSupply); } /** * @dev Overridden the BurnableToken burn() function to also correct maxSupply. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { super.burn(_value); maxSupply = maxSupply.sub(_value); } } /** * @title Letsfair Token (LTF) * @dev LetsfairToken contract implements the ERC20 with the StandardToken functions. * The token&#39;s creation is realize in a gradual and programmatic way, distributed * proportionally over a predefined period, specified by SchedulableToken. * @author Anselmo Zago (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73121d00161f1e1c331f16070015121a015d1c0114">[email&#160;protected]</a>) */ contract LetsfairToken is SchedulableToken { string public constant name = "Letsfair"; string public constant symbol = "LTF"; uint8 public constant decimals = 18; address _beneficiary = 0xe0F158B382F30A1eccecb5B67B1cf7EB92B5f1E4; uint256 _maxSupply = 10 ** 27; // 1 billion with decimals uint256 _duration = 157788000; // ~5 years in seconds function LetsfairToken() SchedulableToken(_beneficiary, _maxSupply, _duration) public {} }
* @dev Returns the total amount that still to be released by the end of the duration./
function schedulableAmount() public view returns (uint256) { return maxSupply.sub(totalSupply); }
10,689,355
[ 1, 1356, 326, 2078, 3844, 716, 4859, 358, 506, 15976, 635, 326, 679, 434, 326, 3734, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 272, 4292, 429, 6275, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 943, 3088, 1283, 18, 1717, 12, 4963, 3088, 1283, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x1C918d87BBD9c270f5Ad943EC98823AE2C66e203/sources/mirin.sol
@notice This low-level function should be called from a contract which performs important safety checks.
function mint(address to) private returns (uint256 liquidity) { uint256 balance0 = bentoBox.balanceOf(token0, address(this)); uint256 balance1 = bentoBox.balanceOf(token1, address(this)); uint256 amount0 = balance0.sub(_reserve0); uint256 amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); if (_totalSupply == 0) { IMigrator _migrator = IMigrator(masterContract.migrator()); if (msg.sender == address(_migrator)) { liquidity = _migrator.desiredLiquidity(); require(liquidity > 0 && liquidity != type(uint256).max, 'Boshi: BAD_DESIRED_LIQUIDITY'); require(address(_migrator) == address(0), 'Boshi: MUST_NOT_HAVE_MIGRATOR'); liquidity = BoshiMath.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); } liquidity = BoshiMath.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'Boshi: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); emit Mint(msg.sender, amount0, amount1); }
9,592,137
[ 1, 2503, 4587, 17, 2815, 445, 1410, 506, 2566, 628, 279, 6835, 1492, 11199, 10802, 24179, 4271, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 358, 13, 3238, 1135, 261, 11890, 5034, 4501, 372, 24237, 13, 288, 203, 3639, 2254, 5034, 11013, 20, 273, 324, 29565, 3514, 18, 12296, 951, 12, 2316, 20, 16, 1758, 12, 2211, 10019, 203, 3639, 2254, 5034, 11013, 21, 273, 324, 29565, 3514, 18, 12296, 951, 12, 2316, 21, 16, 1758, 12, 2211, 10019, 203, 3639, 2254, 5034, 3844, 20, 273, 11013, 20, 18, 1717, 24899, 455, 6527, 20, 1769, 203, 3639, 2254, 5034, 3844, 21, 273, 11013, 21, 18, 1717, 24899, 455, 6527, 21, 1769, 203, 203, 3639, 1426, 14036, 1398, 273, 389, 81, 474, 14667, 24899, 455, 6527, 20, 16, 389, 455, 6527, 21, 1769, 203, 3639, 309, 261, 67, 4963, 3088, 1283, 422, 374, 13, 288, 203, 5411, 6246, 2757, 639, 389, 81, 2757, 639, 273, 6246, 2757, 639, 12, 7525, 8924, 18, 81, 2757, 639, 10663, 203, 5411, 309, 261, 3576, 18, 15330, 422, 1758, 24899, 81, 2757, 639, 3719, 288, 203, 7734, 4501, 372, 24237, 273, 389, 81, 2757, 639, 18, 30458, 48, 18988, 24237, 5621, 203, 7734, 2583, 12, 549, 372, 24237, 405, 374, 597, 4501, 372, 24237, 480, 618, 12, 11890, 5034, 2934, 1896, 16, 296, 38, 538, 12266, 30, 16467, 67, 1639, 2320, 5879, 67, 2053, 53, 3060, 4107, 8284, 203, 7734, 2583, 12, 2867, 24899, 81, 2757, 639, 13, 422, 1758, 12, 20, 3631, 296, 38, 538, 12266, 30, 10685, 67, 4400, 67, 19191, 3412, 67, 49, 3047, 54, 3575, 8284, 203, 7734, 4501, 372, 24237, 273, 605, 538, 2 ]
./full_match/5/0x28fbe43b52544a3947309768e11E4c1AebFDbD92/sources/src/token/ERC1155/extensions/mintable/ERC1155MintableExtension.sol
* @title Extension of {ERC1155} that allows other facets of the diamond to mint based on arbitrary logic./
abstract contract ERC1155MintableExtension is IERC1155MintableExtension, ERC1155BaseInternal { function mintByFacet( address to, uint256 id, uint256 amount, bytes calldata data ) public virtual { if (address(this) != msg.sender) { revert ErrSenderIsNotSelf(); } _mint(to, id, amount, data); } ) public virtual { if (address(this) != msg.sender) { revert ErrSenderIsNotSelf(); } _mint(to, id, amount, data); } function mintByFacet( address[] calldata tos, uint256[] calldata ids, uint256[] calldata amounts, bytes[] calldata datas ) public virtual { if (address(this) != msg.sender) { revert ErrSenderIsNotSelf(); } _mintBatch(tos, ids, amounts, datas); } function mintByFacet( address[] calldata tos, uint256[] calldata ids, uint256[] calldata amounts, bytes[] calldata datas ) public virtual { if (address(this) != msg.sender) { revert ErrSenderIsNotSelf(); } _mintBatch(tos, ids, amounts, datas); } }
1,895,006
[ 1, 3625, 434, 288, 654, 39, 2499, 2539, 97, 716, 5360, 1308, 21681, 434, 326, 4314, 301, 1434, 358, 312, 474, 2511, 603, 11078, 4058, 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, 17801, 6835, 4232, 39, 2499, 2539, 49, 474, 429, 3625, 353, 467, 654, 39, 2499, 2539, 49, 474, 429, 3625, 16, 4232, 39, 2499, 2539, 2171, 3061, 288, 203, 565, 445, 312, 474, 858, 11137, 12, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 745, 892, 501, 203, 203, 565, 262, 1071, 5024, 288, 203, 3639, 309, 261, 2867, 12, 2211, 13, 480, 1234, 18, 15330, 13, 288, 203, 5411, 15226, 1926, 12021, 28041, 10084, 5621, 203, 3639, 289, 203, 203, 3639, 389, 81, 474, 12, 869, 16, 612, 16, 3844, 16, 501, 1769, 203, 565, 289, 203, 203, 565, 262, 1071, 5024, 288, 203, 3639, 309, 261, 2867, 12, 2211, 13, 480, 1234, 18, 15330, 13, 288, 203, 5411, 15226, 1926, 12021, 28041, 10084, 5621, 203, 3639, 289, 203, 203, 3639, 389, 81, 474, 12, 869, 16, 612, 16, 3844, 16, 501, 1769, 203, 565, 289, 203, 203, 565, 445, 312, 474, 858, 11137, 12, 203, 3639, 1758, 8526, 745, 892, 358, 87, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 3258, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 30980, 16, 203, 3639, 1731, 8526, 745, 892, 5386, 203, 565, 262, 1071, 5024, 288, 203, 3639, 309, 261, 2867, 12, 2211, 13, 480, 1234, 18, 15330, 13, 288, 203, 5411, 15226, 1926, 12021, 28041, 10084, 5621, 203, 3639, 289, 203, 203, 3639, 389, 81, 474, 4497, 12, 14627, 16, 3258, 16, 30980, 16, 5386, 1769, 203, 565, 289, 203, 565, 2 ]
pragma solidity ^0.5.10; import "../MerklePatriciaProof.sol"; contract EthashInterface { function verifyPoW(uint blockNumber, bytes32 rlpHeaderHashWithoutNonce, uint nonce, uint difficulty, uint[] calldata dataSetLookup, uint[] calldata witnessForLookup) external view returns (uint, uint); } /// @title TestimoniumCore: A contract enabling cross-blockchain verifications (transactions, receipts, states) /// @author Marten Sigwart, Philipp Frauenthaler /// @notice You can use this contract for submitting new block headers, disputing already submitted block headers, and /// for verifying Merkle Patricia proofs (transactions, receipts, states). contract TestimoniumCore { using RLPReader for *; uint constant ALLOWED_FUTURE_BLOCK_TIME = 15 seconds; uint constant MAX_GAS_LIMIT = 2**63-1; uint constant MIN_GAS_LIMIT = 5000; int64 constant GAS_LIMIT_BOUND_DIVISOR = 1024; bytes32 constant EMPTY_UNCLE_HASH = hex"1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"; EthashInterface ethashContract; struct MetaInfo { bytes32[] successors; // in case of forks a blockchain can have multiple successors uint forkId; uint iterableIndex; // index at which the block header is/was stored in the iterable endpoints array bytes32 latestFork; // contains the hash of the latest node where the current fork branched off address submitter; } struct BlockHeader { bytes32 parent; bytes32 uncleHash; bytes32 stateRoot; bytes32 transactionsRoot; bytes32 receiptsRoot; uint blockNumber; uint gasLimit; uint timestamp; // block timestamp is needed for difficulty calculation uint difficulty; uint totalDifficulty; MetaInfo meta; } mapping (bytes32 => BlockHeader) private headers; // sha3 hash -> Header uint constant lockPeriodInMin = 5 minutes; uint constant requiredSucceedingBlocks = 3; uint maxForkId = 0; bytes32[] iterableEndpoints; bytes32 public longestChainEndpoint; // The contract is initialized with block 8084509 and the total difficulty of that same block. // The contract creator needs to make sure that these values represent a valid block of the tracked blockchain. constructor (bytes memory _rlpHeader, uint totalDifficulty, address _ethashContractAddr) internal { bytes32 newBlockHash; BlockHeader memory newHeader; bytes32 rlpHeaderHashWithoutNonce; uint nonce; (newBlockHash, newHeader, rlpHeaderHashWithoutNonce, nonce) = parseAndValidateBlockHeader(_rlpHeader); // block is also validated by this function newHeader.totalDifficulty = totalDifficulty; newHeader.meta.forkId = maxForkId; maxForkId += 1; newHeader.meta.iterableIndex = iterableEndpoints.push(newBlockHash) - 1; headers[newBlockHash] = newHeader; longestChainEndpoint = newBlockHash; ethashContract = EthashInterface(_ethashContractAddr); } function getHeader(bytes32 blockHash) public view returns ( bytes32 parent, bytes32 uncleHash, bytes32 stateRoot, bytes32 transactionsRoot, bytes32 receiptsRoot, uint blockNumber, uint gasLimit, uint timestamp, uint difficulty, uint totalDifficulty ) { BlockHeader storage header = headers[blockHash]; return ( header.parent, header.uncleHash, header.stateRoot, header.transactionsRoot, header.receiptsRoot, header.blockNumber, header.gasLimit, header.timestamp, header.difficulty, header.totalDifficulty ); } function getHeaderMetaInfo(bytes32 blockHash) public view returns ( bytes32[] memory successors, uint forkId, uint iterableIndex, bytes32 latestFork, address submitter ) { BlockHeader storage header = headers[blockHash]; return ( header.meta.successors, header.meta.forkId, header.meta.iterableIndex, header.meta.latestFork, header.meta.submitter ); } function getNoOfForks() internal view returns (uint) { return iterableEndpoints.length; } // @dev Returns the block hash of the endpoint at the specified index function getBlockHashOfEndpoint(uint index) internal view returns (bytes32) { return iterableEndpoints[index]; } function isBlock(bytes32 hash) public view returns (bool) { return headers[hash].difficulty != 0; } function getTransactionsRoot(bytes32 blockHash) internal view returns (bytes32) { return headers[blockHash].transactionsRoot; } function getReceiptsRoot(bytes32 blockHash) internal view returns (bytes32) { return headers[blockHash].receiptsRoot; } function getStateRoot(bytes32 blockHash) internal view returns (bytes32) { return headers[blockHash].stateRoot; } event PoWValidationResult(uint errorCode, uint errorInfo); /// @dev Accepts an RLP encoded header. The provided header is parsed, validated and some fields are stored. function submitHeader(bytes memory _rlpHeader, uint[] memory dataSetLookup, uint[] memory witnessForLookup, address submitter) internal returns (bytes32) { bytes32 newBlockHash; BlockHeader memory newHeader; bytes32 rlpHeaderHashWithoutNonce; uint nonce; (newBlockHash, newHeader, rlpHeaderHashWithoutNonce, nonce) = parseAndValidateBlockHeader(_rlpHeader); // block is also validated by this function // verify Ethash (uint returnCode, ) = ethashContract.verifyPoW(newHeader.blockNumber, rlpHeaderHashWithoutNonce, nonce, newHeader.difficulty, dataSetLookup, witnessForLookup); emit PoWValidationResult(returnCode, 0); require(returnCode == 0, "Ethash validation failed"); // Get parent header and set next pointer to newHeader BlockHeader storage parentHeader = headers[newHeader.parent]; parentHeader.meta.successors.push(newBlockHash); newHeader.meta.submitter = submitter; // check if parent is an endpoint if (iterableEndpoints.length > parentHeader.meta.iterableIndex && iterableEndpoints[parentHeader.meta.iterableIndex] == newHeader.parent) { // parentHeader is an endpoint (and no fork) -> replace parentHeader in endpoints by new header (since new header becomes new endpoint) newHeader.meta.forkId = parentHeader.meta.forkId; iterableEndpoints[parentHeader.meta.iterableIndex] = newBlockHash; newHeader.meta.iterableIndex = parentHeader.meta.iterableIndex; delete parentHeader.meta.iterableIndex; newHeader.meta.latestFork = parentHeader.meta.latestFork; } else { // parentHeader is forked newHeader.meta.forkId = maxForkId; maxForkId += 1; newHeader.meta.iterableIndex = iterableEndpoints.push(newBlockHash) - 1; newHeader.meta.latestFork = newHeader.parent; if (parentHeader.meta.successors.length == 2) { // a new fork was created, so we set the latest fork of the original branch to the newly created fork // this has to be done only the first time a fork is created setLatestForkAtSuccessors(headers[parentHeader.meta.successors[0]], newHeader.parent); } } if (newHeader.totalDifficulty > headers[longestChainEndpoint].totalDifficulty) { longestChainEndpoint = newBlockHash; } headers[newBlockHash] = newHeader; // make sure to persist the header only AFTER all property changes return newBlockHash; } /// @dev Verifies the existence of a transaction ('txHash') within a certain block ('blockHash'). /// @param blockHash the hash of the block that contains the Merkle root hash /// @param noOfConfirmations the required number of succeeding blocks needed for a block to be considered as confirmed /// @param rlpEncodedValue the value of the Merkle Patricia trie (e.g, transaction, receipt, state) in RLP format /// @param path the path (key) in the trie indicating the way starting at the root node and ending at the value (e.g., transaction) /// @param rlpEncodedNodes an RLP encoded list of nodes of the Merkle branch, first element is the root node, last element the value /// @param merkleRootHash the hash of the root node of the Merkle Patricia trie /// @return 0: verification was successful /// 1: block is confirmed and unlocked, but the Merkle proof was invalid // // The verification follows the following steps: // 1. Verify that the given block is part of the longest Proof of Work chain // 2. Verify that the block is unlcoked and has been confirmed by at least n succeeding unlocked blocks ('noOfConfirmations') // 3. Verify the Merkle Patricia proof of the given block // // In case we have to check whether enough block confirmations occurred // starting from the requested block ('blockHash'), we go to the latest // unlocked block on the longest chain path (could be the requested block itself) // and count the number of confirmations (i.e. the number of unlocked blocks), // starting from the latest unlocked block along the longest chain path. function verifyMerkleProof(bytes32 blockHash, uint8 noOfConfirmations, bytes memory rlpEncodedValue, bytes memory path, bytes memory rlpEncodedNodes, bytes32 merkleRootHash) internal view returns (uint8) { require(isBlock(blockHash), "block does not exist"); bool isPartOfLongestPoWCFork = isBlockPartOfFork(blockHash, longestChainEndpoint); require(isPartOfLongestPoWCFork, "block is not part of the longest PoW chain"); require(headers[longestChainEndpoint].blockNumber >= headers[blockHash].blockNumber + noOfConfirmations); if (MerklePatriciaProof.verify(rlpEncodedValue, path, rlpEncodedNodes, merkleRootHash) > 0) { return 1; } return 0; } function isBlockPartOfFork(bytes32 blockHash, bytes32 forkEndpoint) private view returns (bool) { bytes32 current = forkEndpoint; while (current != 0) { if (current == blockHash) { return true; } current = headers[current].parent; } return false; // while (headers[current].meta.forkId > headers[blockHash].meta.forkId) { // // go to next fork point // current = headers[current].meta.latestFork; // } // // if (headers[current].meta.forkId < headers[blockHash].meta.forkId) { // return false; // the requested block is NOT part of the longest chain // } // // if (headers[current].blockNumber < headers[blockHash].blockNumber) { // // current and the requested block are on a fork with the same fork id // // however, the requested block comes after the fork point (current), so the requested block cannot be part of the longest chain // return false; // } // // return true; } function setLatestForkAtSuccessors(BlockHeader storage header, bytes32 latestFork) private { if (header.meta.latestFork == latestFork) { // latest fork has already been set return; } header.meta.latestFork = latestFork; if (header.meta.successors.length == 1) { setLatestForkAtSuccessors(headers[header.meta.successors[0]], latestFork); } } event SubmitBlockHeader( bytes32 hash, bytes32 hashWithoutNonce, uint nonce, uint difficulty, bytes32 parent, bytes32 transactionsRoot ); function parseAndValidateBlockHeader( bytes memory rlpHeader ) private returns (bytes32, BlockHeader memory, bytes32, uint) { BlockHeader memory header; RLPReader.Iterator memory it = rlpHeader.toRlpItem().iterator(); uint gasUsed; // we do not store gasUsed with the header as we do not need to access it after the header validation has taken place uint idx; uint nonce; while(it.hasNext()) { if( idx == 0 ) header.parent = bytes32(it.next().toUint()); else if ( idx == 1 ) header.uncleHash = bytes32(it.next().toUint()); else if ( idx == 3 ) header.stateRoot = bytes32(it.next().toUint()); else if ( idx == 4 ) header.transactionsRoot = bytes32(it.next().toUint()); else if ( idx == 5 ) header.receiptsRoot = bytes32(it.next().toUint()); else if ( idx == 7 ) header.difficulty = it.next().toUint(); else if ( idx == 8 ) header.blockNumber = it.next().toUint(); else if ( idx == 9 ) header.gasLimit = it.next().toUint(); else if ( idx == 10 ) gasUsed = it.next().toUint(); else if ( idx == 11 ) header.timestamp = it.next().toUint(); else if ( idx == 14 ) nonce = it.next().toUint(); else it.next(); idx++; } // calculate block hash and check that block header does not already exist bytes32 blockHash = keccak256(rlpHeader); require(!isBlock(blockHash), "block already exists"); // duplicate rlp header and truncate nonce and mixDataHash bytes memory rlpWithoutNonce = copy(rlpHeader, rlpHeader.length-42); // 42: length of none+mixHash uint16 rlpHeaderWithoutNonceLength = uint16(rlpHeader.length-3-42); // rlpHeaderLength - 3 prefix bytes (0xf9 + length) - length of nonce and mixHash bytes2 headerLengthBytes = bytes2(rlpHeaderWithoutNonceLength); rlpWithoutNonce[1] = headerLengthBytes[0]; rlpWithoutNonce[2] = headerLengthBytes[1]; bytes32 rlpHeaderHashWithoutNonce = keccak256(rlpWithoutNonce); checkHeaderValidity(header, gasUsed); // Get parent header and set total difficulty header.totalDifficulty = headers[header.parent].totalDifficulty + header.difficulty; emit SubmitBlockHeader(blockHash, rlpHeaderHashWithoutNonce, nonce, header.difficulty, header.parent, header.transactionsRoot); return (blockHash, header, rlpHeaderHashWithoutNonce, nonce); } function copy(bytes memory sourceArray, uint newLength) private pure returns (bytes memory) { uint newArraySize = newLength; if (newArraySize > sourceArray.length) { newArraySize = sourceArray.length; } bytes memory newArray = new bytes(newArraySize); for(uint i = 0; i < newArraySize; i++){ newArray[i] = sourceArray[i]; } return newArray; } // @dev Validates the fields of a block header without validating the PoW // The validation largely follows the header validation of the geth implementation: // https://github.com/ethereum/go-ethereum/blob/aa6005b469fdd1aa7a95f501ce87908011f43159/consensus/ethash/consensus.go#L241 function checkHeaderValidity(BlockHeader memory header, uint gasUsed) private view { if (iterableEndpoints.length == 0) { // we do not check header validity for the genesis block // since the genesis block is submitted at contract creation. return; } // validate parent BlockHeader storage parent = headers[header.parent]; require(parent.difficulty != 0, "non-existent parent"); // validate block number require(parent.blockNumber + 1 == header.blockNumber, "illegal block number"); // validate timestamp require(header.timestamp <= now + ALLOWED_FUTURE_BLOCK_TIME, "illegal timestamp"); require(parent.timestamp < header.timestamp, "illegal timestamp"); // validate difficulty uint expectedDifficulty = calculateDifficulty(parent, header.timestamp); require(expectedDifficulty == header.difficulty, "wrong difficulty"); // validate gas limit require(header.gasLimit <= MAX_GAS_LIMIT, "gas limit too high"); // verify that the gas limit is <= 2^63-1 require(header.gasLimit >= MIN_GAS_LIMIT, "gas limit too small"); // verify that the gas limit is >= 5000 require(gasLimitWithinBounds(int64(header.gasLimit), int64(parent.gasLimit)), "illegal gas limit"); require(gasUsed <= header.gasLimit, "gas used is higher than the gas limit"); // verify that the gasUsed is <= gasLimit } function gasLimitWithinBounds(int64 gasLimit, int64 parentGasLimit) private pure returns (bool) { int64 limit = parentGasLimit / GAS_LIMIT_BOUND_DIVISOR; int64 difference = gasLimit - parentGasLimit; if (difference < 0) { difference *= -1; } return difference <= limit; } // diff = (parent_diff + // (parent_diff / 2048 * max((2 if len(parent.uncles) else 1) - ((timestamp - parent.timestamp) // 9), -99)) // ) + 2^(periodCount - 2) // https://github.com/ethereum/go-ethereum/blob/aa6005b469fdd1aa7a95f501ce87908011f43159/consensus/ethash/consensus.go#L335 function calculateDifficulty(BlockHeader memory parent, uint timestamp) private pure returns (uint) { int x = int((timestamp - parent.timestamp) / 9); // take into consideration uncles of parent if (parent.uncleHash == EMPTY_UNCLE_HASH) { x = 1 - x; } else { x = 2 - x; } if (x < -99) { x = -99; } x = int(parent.difficulty) + int(parent.difficulty) / 2048 * x; // minimum difficulty = 131072 if (x < 131072) { x = 131072; } uint bombDelayFromParent = 5000000 - 1; if (parent.blockNumber + 1 >= 9200000) { // https://eips.ethereum.org/EIPS/eip-2384 bombDelayFromParent = 9000000 - 1; } // calculate a fake block number for the ice-age delay // Specification: https://eips.ethereum.org/EIPS/eip-1234 uint fakeBlockNumber = 0; if (parent.blockNumber >= bombDelayFromParent) { fakeBlockNumber = parent.blockNumber - bombDelayFromParent; } // for the exponential factor uint periodCount = fakeBlockNumber / 100000; // the exponential factor, commonly referred to as "the bomb" // diff = diff + 2^(periodCount - 2) if (periodCount > 1) { return uint(x) + 2**(periodCount - 2); } return uint(x); } }
verify that the gas limit is >= 5000
require(header.gasLimit >= MIN_GAS_LIMIT, "gas limit too small");
6,443,747
[ 1, 8705, 716, 326, 16189, 1800, 353, 1545, 20190, 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, 3639, 2583, 12, 3374, 18, 31604, 3039, 1545, 6989, 67, 43, 3033, 67, 8283, 16, 315, 31604, 1800, 4885, 5264, 8863, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "./ownable.sol"; import "./managable.sol"; /// Burn attestor lets managers attest vendor burns /// @title BurnAttestor /// @dev this contract acts as both a trusted oracle which managers can attest cross chain burns of MRXb/MRXe and also as a ledger for vendor withdraws from unwraps. /// @author SeqSEE contract BurnAttestor is Ownable, Managable { uint256 public attestationsRequired; mapping(uint256 => uint256) public bscAttestations; //burn txid => attested mapping(uint256 => uint256) public ethAttestations; //burn txid => attested mapping(uint256 => mapping(address => bool)) public bscAttested; //burn txid => mapping (address => attested) mapping(uint256 => mapping(address => bool)) public ethAttested; //burn txid => mapping (address => attested) mapping(address => uint256) public pendingWithdraws; /// Emitted whenever a burn attestation has reached attestationsRequired /// @param chain The chain which the burn occurred, this can only be "bsc" or "eth" /// @param burn The transaction hash of the burn /// @param burner The hexified vendor address /// @param value The amount of the burn event BurnAttested( string indexed chain, bytes32 burn, address indexed burner, uint256 value ); /// Deploy a BurnAttestor contract constructor(uint256 _attestationsRequired) { require(_attestationsRequired > 0, "At least 1 attestation required"); attestationsRequired = _attestationsRequired; } /// A management only method to attest cross chain burns and once sufficently attested to increase the vendor allowance /// @param chain The chain which the burn occurred, this can only be "bsc" or "eth" /// @param burn The transaction hash of the burn /// @param burner The hexified MRX address which is tied to the vendor function attestBurn( string memory chain, uint256 burn, address payable burner ) public payable isManager { if ( keccak256(abi.encodePacked(chain)) == keccak256(abi.encodePacked("bsc")) ) { require(bscAttested[burn][msg.sender] == false, "Already attested"); bscAttested[burn][msg.sender] = true; bscAttestations[burn] = bscAttestations[burn] + 1; if (bscAttestations[burn] >= attestationsRequired) { pendingWithdraws[payable(burner)] += msg.value; emit BurnAttested(chain, bytes32(burn), burner, msg.value); } } else if ( keccak256(abi.encodePacked(chain)) == keccak256(abi.encodePacked("eth")) ) { require(ethAttested[burn][msg.sender] == false, "Already attested"); ethAttested[burn][msg.sender] = true; ethAttestations[burn] = ethAttestations[burn] + 1; if (ethAttestations[burn] >= attestationsRequired) { pendingWithdraws[payable(burner)] + msg.value; emit BurnAttested(chain, bytes32(burn), burner, msg.value); } } else { revert("Unknown chain"); } } /// An owner only method to change the amount of attestations required /// @param _attestationsRequired The amount of attestations required before a vendor allowance can be increased function setAttestationRequired(uint256 _attestationsRequired) public isOwner { require(_attestationsRequired > 0, "At least 1 attestation required"); attestationsRequired = _attestationsRequired; } /// A method to retrieve the caller's available balance in satoshi function vendorBalance() public view returns (uint256) { return pendingWithdraws[msg.sender]; } /// A method to withdraw any available unwrapped vendor funds function withdraw() public virtual returns (uint256) { uint256 amount = pendingWithdraws[msg.sender]; require(amount > 0, "Insufficient funds"); // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdraws[msg.sender] = 0; payable(msg.sender).transfer(amount); return amount; } }
burn txid => attested
mapping(uint256 => uint256) public bscAttestations;
926,107
[ 1, 70, 321, 18372, 516, 2403, 3149, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 324, 1017, 3075, 395, 1012, 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 ]
/** * @title TraderOperatorable * @author Team 3301 <[email protected]> * @dev TraderOperatorable contract stores TraderOperators contract address, and modifiers for * contracts. */ pragma solidity 0.5.12; import "../interface/ITraderOperators.sol"; import "../base/Operatorable.sol"; import "../../helpers/Initializable.sol"; contract TraderOperatorable is Operatorable { ITraderOperators internal traderOperatorsInst; address private traderOperatorsPending; event TraderOperatorsContractChanged(address indexed caller, address indexed traderOperatorsAddress); event TraderOperatorsContractPending(address indexed caller, address indexed traderOperatorsAddress); /** * @dev Reverts if sender does not have the trader role associated. */ modifier onlyTrader() { require(isTrader(msg.sender), "TraderOperatorable: caller is not trader"); _; } /** * @dev Reverts if sender does not have the operator or trader role associated. */ modifier onlyOperatorOrTraderOrSystem() { require( isOperator(msg.sender) || isTrader(msg.sender) || isSystem(msg.sender), "TraderOperatorable: caller is not trader or operator or system" ); _; } /** * @dev Initialization instead of constructor, called once. The setTradersOperatorsContract function can be called only by Admin role with * confirmation through the operators contract. * @param _baseOperators BaseOperators contract address. * @param _traderOperators TraderOperators contract address. */ function initialize(address _baseOperators, address _traderOperators) public initializer { super.initialize(_baseOperators); _setTraderOperatorsContract(_traderOperators); } /** * @dev Set the new the address of Operators contract, should be confirmed from operators contract by calling confirmFor(addr) * where addr is the address of current contract instance. This is done to prevent the case when the new contract address is * broken and control of the contract can be lost in such case * @param _traderOperators TradeOperators contract address. */ function setTraderOperatorsContract(address _traderOperators) public onlyAdmin { require( _traderOperators != address(0), "TraderOperatorable: address of new traderOperators contract can not be zero" ); traderOperatorsPending = _traderOperators; emit TraderOperatorsContractPending(msg.sender, _traderOperators); } /** * @dev The function should be called from new operators contract by admin to insure that traderOperatorsPending address * is the real contract address. */ function confirmTraderOperatorsContract() public { require( traderOperatorsPending != address(0), "TraderOperatorable: address of pending traderOperators contract can not be zero" ); require( msg.sender == traderOperatorsPending, "TraderOperatorable: should be called from new traderOperators contract" ); _setTraderOperatorsContract(traderOperatorsPending); } /** * @return The address of the TraderOperators contract. */ function getTraderOperatorsContract() public view returns (address) { return address(traderOperatorsInst); } /** * @return The pending TraderOperators contract address */ function getTraderOperatorsPending() public view returns (address) { return traderOperatorsPending; } /** * @return If '_account' has trader privileges. */ function isTrader(address _account) public view returns (bool) { return traderOperatorsInst.isTrader(_account); } /** INTERNAL FUNCTIONS */ function _setTraderOperatorsContract(address _traderOperators) internal { require( _traderOperators != address(0), "TraderOperatorable: address of new traderOperators contract can not be zero" ); traderOperatorsInst = ITraderOperators(_traderOperators); emit TraderOperatorsContractChanged(msg.sender, _traderOperators); } }
* @return The address of the TraderOperators contract./
function getTraderOperatorsContract() public view returns (address) { return address(traderOperatorsInst); }
955,699
[ 1, 2463, 1021, 1758, 434, 326, 2197, 765, 24473, 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, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 1609, 765, 24473, 8924, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1758, 12, 313, 1143, 24473, 10773, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../interfaces/IFantomMintBalanceGuard.sol"; import "../interfaces/IFantomDeFiTokenStorage.sol"; import "./FantomMintErrorCodes.sol"; // FantomMintCore implements a calculation of different rate steps // between collateral and debt pools to ensure healthy accounts. contract FantomMintCollateral is Initializable, ReentrancyGuard, FantomMintErrorCodes { // define used libs using SafeMath for uint256; using Address for address; using SafeERC20 for ERC20; // initialize initializes the contract properly before the first use. function initialize() public initializer { ReentrancyGuard.initialize(); } // ------------------------------------------------------------- // Emitted events definition // ------------------------------------------------------------- // Deposited is emitted on token received to deposit // increasing user's collateral value. event Deposited(address indexed token, address indexed user, uint256 amount); // Withdrawn is emitted on confirmed token withdraw // from the deposit decreasing user's collateral value. event Withdrawn(address indexed token, address indexed user, uint256 amount); // ------------------------------------------------------------- // Abstract function required for the collateral manager // ------------------------------------------------------------- // getCollateralPool (abstract) returns the address of collateral pool. function getCollateralPool() public view returns (IFantomDeFiTokenStorage); // checkCollateralCanDecrease (abstract) checks if the specified // amount of collateral can be removed from account // without breaking collateral to debt ratio rule. function checkCollateralCanDecrease(address _account, address _token, uint256 _amount) public view returns (bool); // getMaxToWithdraw (abstract) calculates the maximal amount of given token collateral // which can be withdrawn and still be withing the given collateral to debt rate. function getMaxToWithdraw(address _account, address _token, uint256 _ratio) public view returns (uint256); // getPrice (abstract) returns the price of given ERC20 token using on-chain oracle // expression of an exchange rate between the token and base denomination. function getPrice(address _token) public view returns (uint256); // canDeposit (abstract) checks if the given token can be deposited to the collateral pool. function canDeposit(address _token) public view returns (bool); // rewardUpdate (abstract) notifies the reward distribution to update state // of the given account. function rewardUpdate(address _account) public; // ------------------------------------------------------------- // Collateral management functions below // ------------------------------------------------------------- // mustDeposit (wrapper) tries to deposit given amount of tokens // and reverts on failure. function mustDeposit(address _token, uint256 _amount) public nonReentrant { // make the attempt uint256 result = _deposit(_token, _amount); // check zero amount condition require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); // check deposit prohibited condition require(result != ERR_DEPOSIT_PROHIBITED, "deposit of the token prohibited"); // check low balance condition require(result != ERR_LOW_BALANCE, "insufficient token balance"); // check missing allowance condition require(result != ERR_LOW_ALLOWANCE, "insufficient allowance"); // check no value condition require(result != ERR_NO_VALUE, "token has no value"); // sanity check for any non-covered condition require(result == ERR_NO_ERROR, "unexpected failure"); } // deposit receives assets to build up the collateral value. // The collateral can be used later to mint tokens inside fMint module. // The call does not subtract any fee. No interest is granted on deposit. function deposit(address _token, uint256 _amount) public nonReentrant returns (uint256) { return _deposit(_token, _amount); } // _deposit (internal) does the collateral increase job. function _deposit(address _token, uint256 _amount) internal returns (uint256) { // make sure a non-zero value is being deposited if (_amount == 0) { return ERR_ZERO_AMOUNT; } // make sure the requested token can be deposited if (!canDeposit(_token)) { return ERR_DEPOSIT_PROHIBITED; } // make sure caller has enough balance to cover the deposit if (_amount > ERC20(_token).balanceOf(msg.sender)) { return ERR_LOW_BALANCE; } // make sure we are allowed to transfer funds from the caller // to the fMint collateral pool if (_amount > ERC20(_token).allowance(msg.sender, address(this))) { return ERR_LOW_ALLOWANCE; } // make sure the token has a value before we accept it as a collateral if (getPrice(_token) == 0) { return ERR_NO_VALUE; } // update the reward distribution for the account before the state changes rewardUpdate(msg.sender); // transfer ERC20 tokens from account to the collateral ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); // add the collateral to the account getCollateralPool().add(msg.sender, _token, _amount); // emit the event signaling a successful deposit emit Deposited(_token, msg.sender, _amount); // deposit successful return ERR_NO_ERROR; } // mustWithdraw (wrapper) tries to subtracts any deposited collateral token from the contract // and reverts on failure. function mustWithdraw(address _token, uint256 _amount) public nonReentrant { // make the attempt uint256 result = _withdraw(_token, _amount); // check zero amount condition require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); // check low balance condition require(result != ERR_LOW_BALANCE, "insufficient collateral balance"); // check no value condition require(result != ERR_NO_VALUE, "token has no value"); // check low balance condition require(result != ERR_LOW_COLLATERAL_RATIO, "insufficient collateral value remains"); // sanity check for any non-covered condition require(result == ERR_NO_ERROR, "unexpected failure"); } // withdraw subtracts any deposited collateral token from the contract. // The remaining collateral value is compared to the minimal required // collateral to debt ratio and the transfer is rejected // if the ratio is lower than the enforced one. function withdraw(address _token, uint256 _amount) public nonReentrant returns (uint256) { return _withdraw(_token, _amount); } // _withdraw (internal) does the collateral decrease job. function _withdraw(address _token, uint256 _amount) internal returns (uint256) { // make sure a non-zero value is being withdrawn if (_amount == 0) { return ERR_ZERO_AMOUNT; } // get the collateral pool IFantomDeFiTokenStorage pool = IFantomDeFiTokenStorage(getCollateralPool()); // make sure the withdraw does not exceed collateral balance if (_amount > pool.balanceOf(msg.sender, _token)) { return ERR_LOW_BALANCE; } // does the new state obey the enforced minimal collateral to debt ratio? // if the check fails, the collateral withdraw is rejected if (!checkCollateralCanDecrease(msg.sender, _token, _amount)) { return ERR_LOW_COLLATERAL_RATIO; } // update the reward distribution for the account before state changes rewardUpdate(msg.sender); // remove the collateral from account pool.sub(msg.sender, _token, _amount); // transfer withdrawn ERC20 tokens to the caller ERC20(_token).safeTransfer(msg.sender, _amount); // signal the successful asset withdrawal emit Withdrawn(_token, msg.sender, _amount); // withdraw successful return ERR_NO_ERROR; } // mustWithdrawMax tries to subtracts maximum of deposited collateral token from the contract // it can to still satisfy the required collateral ratio. It reverts the transaction // if it fails. function mustWithdrawMax(address _token, uint256 _ratio) public nonReentrant { // try to withdraw max amount of tokens allowed uint256 result = _withdrawMax(_token, _ratio); // check zero amount condition require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); // check low balance condition require(result != ERR_LOW_BALANCE, "insufficient collateral balance"); // check no value condition require(result != ERR_NO_VALUE, "token has no value"); // check low balance condition require(result != ERR_LOW_COLLATERAL_RATIO, "insufficient collateral value remains"); // sanity check for any non-covered condition require(result == ERR_NO_ERROR, "unexpected failure"); } // withdrawMax tries to subtracts maximum of deposited collateral token from the contract // it can to still satisfy the required collateral ratio. function withdrawMax(address _token, uint256 _ratio) public nonReentrant returns (uint256) { return _withdrawMax(_token, _ratio); } // _withdrawMax (internal) does the collateral decrease job to the lowest possible // collateral value calculated for the current price conditions and debt to collateral // ratio situation of the account. function _withdrawMax(address _token, uint256 _ratio) internal returns (uint256) { return _withdraw(_token, getMaxToWithdraw(msg.sender, _token, _ratio)); } }
mustWithdraw (wrapper) tries to subtracts any deposited collateral token from the contract and reverts on failure. make the attempt check zero amount condition check low balance condition check no value condition check low balance condition sanity check for any non-covered condition
function mustWithdraw(address _token, uint256 _amount) public nonReentrant { uint256 result = _withdraw(_token, _amount); require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); require(result != ERR_LOW_BALANCE, "insufficient collateral balance"); require(result != ERR_NO_VALUE, "token has no value"); require(result != ERR_LOW_COLLATERAL_RATIO, "insufficient collateral value remains"); require(result == ERR_NO_ERROR, "unexpected failure"); }
12,589,114
[ 1, 11926, 1190, 9446, 261, 8376, 13, 9327, 358, 10418, 87, 1281, 443, 1724, 329, 4508, 2045, 287, 1147, 628, 326, 6835, 471, 15226, 87, 603, 5166, 18, 1221, 326, 4395, 866, 3634, 3844, 2269, 866, 4587, 11013, 2269, 866, 1158, 460, 2269, 866, 4587, 11013, 2269, 16267, 866, 364, 1281, 1661, 17, 16810, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1297, 1190, 9446, 12, 2867, 389, 2316, 16, 2254, 5034, 389, 8949, 13, 1071, 1661, 426, 8230, 970, 288, 203, 3639, 2254, 5034, 563, 273, 389, 1918, 9446, 24899, 2316, 16, 389, 8949, 1769, 203, 203, 3639, 2583, 12, 2088, 480, 10359, 67, 24968, 67, 2192, 51, 5321, 16, 315, 5836, 17, 7124, 3844, 2665, 8863, 203, 203, 3639, 2583, 12, 2088, 480, 10359, 67, 4130, 67, 38, 1013, 4722, 16, 315, 2679, 11339, 4508, 2045, 287, 11013, 8863, 203, 203, 3639, 2583, 12, 2088, 480, 10359, 67, 3417, 67, 4051, 16, 315, 2316, 711, 1158, 460, 8863, 203, 203, 3639, 2583, 12, 2088, 480, 10359, 67, 4130, 67, 4935, 12190, 654, 1013, 67, 54, 789, 4294, 16, 315, 2679, 11339, 4508, 2045, 287, 460, 22632, 8863, 203, 203, 3639, 2583, 12, 2088, 422, 10359, 67, 3417, 67, 3589, 16, 315, 21248, 5166, 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 ]
./partial_match/1/0x788f6cc1FaFa6161a03B914D68a83a37EaFD47DC/sources/src/HODLStaking.sol
Address where fees are sent
address public feeWallet;
15,553,892
[ 1, 1887, 1625, 1656, 281, 854, 3271, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 1071, 14036, 16936, 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 ]
./full_match/3/0xA67395Af3f042A574E412Ab6ef20C3d5aC935F35/sources/Dynamo_Transaction.sol
receive moneyrequired confition: paymeny amount >= sales priceget addresss of current ownertransfer from current owner to the msg sender, and mark item as sold
function buyNft(uint256 nftId, address myaddress, uint256 amountPaid) public payable { uint salePrice = DynamoNft.getSalePrice(nftId); uint amountPaid = msg.value; address myaddress = msg.sender; require(amountPaid >= salePrice); address payable currentOwner = payable(DynamoNft.ownerOf(nftId)); currentOwner.transfer(amountPaid); DynamoNft.transferNft(currentOwner, msg.sender, nftId); DynamoNft.markAsSold(nftId); }
14,217,297
[ 1, 18149, 15601, 4718, 2195, 608, 30, 8843, 27617, 93, 3844, 1545, 272, 5408, 6205, 588, 1758, 87, 434, 783, 3410, 13866, 628, 783, 3410, 358, 326, 1234, 5793, 16, 471, 2267, 761, 487, 272, 1673, 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, 225, 445, 30143, 50, 1222, 12, 11890, 5034, 290, 1222, 548, 16, 1758, 3399, 2867, 16, 2254, 5034, 3844, 16507, 350, 13, 1071, 8843, 429, 288, 203, 565, 2254, 272, 5349, 5147, 273, 463, 12076, 50, 1222, 18, 588, 30746, 5147, 12, 82, 1222, 548, 1769, 203, 565, 2254, 3844, 16507, 350, 273, 1234, 18, 1132, 31, 203, 565, 1758, 3399, 2867, 273, 1234, 18, 15330, 31, 203, 377, 203, 565, 2583, 12, 8949, 16507, 350, 1545, 272, 5349, 5147, 1769, 203, 203, 565, 1758, 8843, 429, 783, 5541, 273, 8843, 429, 12, 40, 12076, 50, 1222, 18, 8443, 951, 12, 82, 1222, 548, 10019, 203, 203, 565, 783, 5541, 18, 13866, 12, 8949, 16507, 350, 1769, 203, 565, 463, 12076, 50, 1222, 18, 13866, 50, 1222, 12, 2972, 5541, 16, 1234, 18, 15330, 16, 290, 1222, 548, 1769, 7010, 565, 463, 12076, 50, 1222, 18, 3355, 1463, 55, 1673, 12, 82, 1222, 548, 1769, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; interface IUTUToken { function mint(address to, uint256 amount) external; function burn(uint256 amount) external; } contract Distributor is Ownable { using SafeMath for uint256; // Use a global counter so batches when distributing cannot overlap. uint256 private idx; address public utuToken; uint256 public toMint; uint256 public distributeAfter; bool public assigned; struct Contributor { address addr; uint256 amount; } Contributor[] public contribs; constructor( address _utuToken, uint256 _toMint, uint256 _distributeAfter ) public { utuToken = _utuToken; toMint = _toMint; distributeAfter = _distributeAfter; } function assign( address[] memory _contributors, uint256[] memory _balances ) onlyOwner public { require(!assigned, "UTU: assigned"); require(_contributors.length == _balances.length, "UTU: mismatching array lengths"); for (uint32 i = 0 ; i < _contributors.length; i++) { Contributor memory c = Contributor(_contributors[i], _balances[i]); toMint = toMint.sub(c.amount); // Will throw on underflow contribs.push(c); } } function assignDone() onlyOwner public { assigned = true; } function distribute(uint256 _to) public { require(assigned, "UTU: !assigned"); require(block.timestamp > distributeAfter, "UTU: still locked"); require(_to < contribs.length, "UTU: out of range"); for (; idx <= _to; idx++) { IUTUToken(utuToken).mint(contribs[idx].addr, contribs[idx].amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @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; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@nomiclabs/buidler/console.sol"; /** * @title The Sale contract. * * For the UTU crowdsale, participants first need to go through KYC after which * they are allowed to exchange USDT for UTU tokens at a fixed price. Each * participant is only allowed to exchange <= 500 USDT. * * A Successful KYC check will grant the user a signature which the contract * uses for authorization. We impose a limit of only one purchase per address. * */ interface IUTUToken { function mint(address to, uint256 amount) external; function burn(uint256 amount) external; } contract Sale is Ownable { using SafeERC20 for ERC20; using SafeMath for uint256; using ECDSA for bytes32; struct Cart { uint256 amount; bool checkedOut; } address public utuToken; ERC20 public usdt; address public kycAuthority; address public treasury; uint256 public startTime; uint256 public endTime; // The following constants are all for the public sale. uint256 public maxContribution = 1242 * 10**6; // USDT uses 6 decimals. uint256 public minContribution = 200 * 10**6; uint256 public maxUSDT = 250000 * 10**6; // The sale is capped at 250000 USDT uint256 public maxUTU = 6250000 * 10**18; uint256 public utuPerUSDT = (6250000 / 250000) * 10**12; uint256 public usdtAvailable = maxUSDT; // Mapping from KYC address to withdrawal address. mapping(address => Cart) public publicContributors; // Private sale participants can claim their allocation after the public sale // finishes. bool public assigned; mapping(address => Cart) public privateContributors; event Contributed(address indexed kycAddress, address indexed sender, uint256 amount); event CheckOut(address indexed target, uint256 amount, bool indexed isPublic); /** * @param _utuToken address Token for sale * @param _usdt address USDT token used to contribute to sale * @param _kycAuthority address Address of the KYC signer * @param _treasury address Address of treasury receiving USDT * @param _startTime uint256 specifying the the starting time of the sale */ constructor( address _utuToken, ERC20 _usdt, address _kycAuthority, address _treasury, uint256 _startTime ) public { utuToken = _utuToken; usdt = _usdt; kycAuthority = _kycAuthority; treasury = _treasury; startTime = _startTime; endTime = startTime + 2 days; } /* * The KYC authority does sign(signHash(hash(kycAddr))) to authorize the * given address. Someone could front-run us here and use the signature * to buy. This is not a problem because the tokens will be minted to the * kycAddr and thus the front-runner would just give us free tokens. * * @param _kycAddr address provided during kyc and receiver of tokens * @param amount uint256 USDT to be exchanged for UTU * @param signature bytes signature provided by the KYC authority * */ function buy(address _kycAddr, uint256 amount, bytes memory signature) public { require(usdtAvailable > 0, 'UTU: no more UTU token available'); require(isActive(), 'UTU: sale is not active'); if (!isUncapped()) { require(amount <= maxContribution, 'UTU: above individual cap'); require(publicContributors[_kycAddr].amount == 0, 'UTU: already bought'); } require(amount >= minContribution, 'UTU: below individual floor'); uint256 _usdtActual = amount > usdtAvailable ? usdtAvailable : amount; uint256 out = usdtToUTU(_usdtActual); usdtAvailable = usdtAvailable.sub(_usdtActual); bytes32 eh = keccak256(abi.encodePacked(_kycAddr)).toEthSignedMessageHash(); require(ECDSA.recover(eh, signature) == kycAuthority, 'UTU: invalid signature'); publicContributors[_kycAddr].amount = publicContributors[_kycAddr].amount.add(out); usdt.safeTransferFrom(msg.sender, treasury, _usdtActual); emit Contributed(_kycAddr, msg.sender, out); } /* * After the public sale finishes anyone can mint for a given kycAddr, since * funds are sent to that address and not the caller of the function. * * @param kycAddr address to mint tokens to. */ function checkoutPublic(address _kycAddr) public { require(block.timestamp > endTime, 'UTU: can only check out after sale'); require(publicContributors[_kycAddr].amount > 0, 'UTU: no public allocation'); require(!publicContributors[_kycAddr].checkedOut, 'UTU: already checked out'); publicContributors[_kycAddr].checkedOut = true; IUTUToken(utuToken).mint(_kycAddr, publicContributors[_kycAddr].amount); emit CheckOut(_kycAddr, publicContributors[_kycAddr].amount, true); } /** * Assign the amounts for the private sale participants. * * @param _contributors Address[] All the private contributor addresses * @param _balances uint256[] All the private contributor balances */ function assignPrivate( address[] memory _contributors, uint256[] memory _balances ) onlyOwner public { require(!assigned, "UTU: already assigned private sale"); require(_contributors.length == _balances.length, "UTU: mismatching array lengths"); for (uint32 i = 0 ; i < _contributors.length; i++) { require(privateContributors[_contributors[i]].amount == 0, 'UTU: already assigned'); privateContributors[_contributors[i]] = Cart(_balances[i], false); } assigned = true; } /* * After the public sale finishes the private sale participants get their tokens * unlocked and can mint them. * */ function checkoutPrivate(address _target) public { require(block.timestamp > endTime, 'UTU: can only check out after sale'); require(privateContributors[_target].amount > 0, 'UTU: no private allocation'); require(!privateContributors[_target].checkedOut, 'UTU: already checked out'); privateContributors[_target].checkedOut = true; IUTUToken(utuToken).mint(_target, privateContributors[_target].amount); emit CheckOut(_target, privateContributors[_target].amount, false); } /* * Calculate UTU allocation given USDT input. * * @param _usdtIn uint256 USDT to be converted to UTU. */ function usdtToUTU(uint256 _usdtIn) public view returns (uint256) { return _usdtIn.mul(utuPerUSDT); } /* * Calculate amount of UTU coins left for purchase. */ function utuAvailable() public view returns (uint256) { return usdtAvailable.mul(utuPerUSDT); } /* * Check whether the sale is active or not */ function isActive() public view returns (bool) { return block.timestamp >= startTime && block.timestamp < endTime; } /* * Check whether the cap on individual contributions is active. */ function isUncapped() public view returns (bool) { return block.timestamp > startTime + 1 hours; } /** * Recover tokens accidentally sent to the token contract. * @param _token address of the token to be recovered. 0x0 address will * recover ETH. * @param _to address Recipient of the recovered tokens * @param _balance uint256 Amount of tokens to be recovered */ function recoverTokens(address _token, address payable _to, uint256 _balance) onlyOwner external { require(_to != address(0), "cannot recover to zero address"); if (_token == address(0)) { // Recover Eth uint256 total = address(this).balance; uint256 balance = _balance == 0 ? total : Math.min(total, _balance); _to.transfer(balance); } else { uint256 total = ERC20(_token).balanceOf(address(this)); uint256 balance = _balance == 0 ? total : Math.min(total, _balance); ERC20(_token).safeTransfer(_to, balance); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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))) } // 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. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("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; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.8.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; contract TetherMock { using SafeMath for uint; string public name; string public symbol; uint public decimals; uint public _totalSupply; uint constant MAX_UINT = 2**256 - 1; mapping (address => mapping (address => uint)) allowed; mapping(address => uint) balances; // additional variables for use if transaction fees ever became necessary uint public basisPointsRate = 0; uint public maximumFee = 0; event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); // Called when new token are issued event Issue(uint amount); // Called when tokens are redeemed event Redeem(uint amount); // Called when contract is deprecated event Deprecate(address newAddress); // Called if contract ever adds fees event Params(uint feeBasisPoints, uint maxFee); // The contract can be initialized with a number of tokens // All the tokens are deposited to the owner address // // @param _balance Initial supply of the contract // @param _name Token Name // @param _symbol Token symbol // @param _decimals Token decimals constructor(uint _initialSupply) public { _totalSupply = _initialSupply; balances[msg.sender] = balances[msg.sender].add(_initialSupply); name = 'USDT'; symbol = 'USDT'; decimals = 6; } function transferFrom(address _from, address _to, uint _value) public { uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[_to] = balances[_to].add(sendAmount); balances[_from] = balances[_from].sub(_value); if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } Transfer(_from, _to, sendAmount); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return balance An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) view public returns (uint balance) { return balances[_owner]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than 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 remaining A uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) view public returns (uint remaining) { return allowed[_owner][_spender]; } // deprecate current contract if favour of a new one function totalSupply() view public returns (uint){ return _totalSupply; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public { uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); Transfer(msg.sender, _to, sendAmount); } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issued function issue(address _to, uint amount) public { balances[_to] += amount; _totalSupply += amount; Issue(amount); } // Redeem tokens. // These tokens are withdrawn from the owner address // if the balance must be enough to cover the redeem // or the call will fail. // @param _amount Number of tokens to be issued function redeem(address _from, uint amount) public { require(_totalSupply >= amount); _totalSupply -= amount; balances[_from] -= amount; Redeem(amount); } }
Mapping from KYC address to withdrawal address.
mapping(address => Cart) public publicContributors;
169,488
[ 1, 3233, 628, 1475, 61, 39, 1758, 358, 598, 9446, 287, 1758, 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, 202, 6770, 12, 2867, 516, 17695, 13, 1071, 1071, 442, 665, 13595, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../interfaces/INiftyswapExchange20.sol"; import "../utils/ReentrancyGuard.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC20.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC165.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155TokenReceiver.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC1155/ERC1155MintBurn.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; /** * This Uniswap-like implementation supports ERC-1155 standard tokens * with an ERC-20 based token used as a currency instead of Ether. * * Liquidity tokens are also ERC-1155 tokens you can find the ERC-1155 * implementation used here: * https://github.com/horizon-games/multi-token-standard/tree/master/contracts/tokens/ERC1155 * * @dev Like Uniswap, tokens with 0 decimals and low supply are susceptible to significant rounding * errors when it comes to removing liquidity, possibly preventing them to be withdrawn without * some collaboration between liquidity providers. */ contract NiftyswapExchange20 is ReentrancyGuard, ERC1155MintBurn, INiftyswapExchange20 { using SafeMath for uint256; /***********************************| | Variables & Constants | |__________________________________*/ // Variables IERC1155 internal immutable token; // address of the ERC-1155 token contract address internal immutable currency; // address of the ERC-20 currency used for exchange address internal immutable factory; // address for the factory that created this contract uint256 internal constant FEE_MULTIPLIER = 995; // Multiplier that calculates the fee (0.5%) // Mapping variables mapping(uint256 => uint256) internal totalSupplies; // Liquidity pool token supply per Token id mapping(uint256 => uint256) internal currencyReserves; // currency Token reserve per Token id /***********************************| | Constructor | |__________________________________*/ /** * @notice Create instance of exchange contract with respective token and currency token * @param _tokenAddr The address of the ERC-1155 Token * @param _currencyAddr The address of the ERC-20 currency Token */ constructor(address _tokenAddr, address _currencyAddr) public { require( _tokenAddr != address(0) && _currencyAddr != address(0), "NiftyswapExchange20#constructor:INVALID_INPUT" ); factory = msg.sender; token = IERC1155(_tokenAddr); currency = _currencyAddr; } /***********************************| | Exchange Functions | |__________________________________*/ /** * @notice Convert currency tokens to Tokens _id and transfers Tokens to recipient. * @dev User specifies MAXIMUM inputs (_maxCurrency) and EXACT outputs. * @dev Assumes that all trades will be successful, or revert the whole tx * @dev Exceeding currency tokens sent will be refunded to recipient * @dev Sorting IDs is mandatory for efficient way of preventing duplicated IDs (which would lead to exploit) * @param _tokenIds Array of Tokens ID that are bought * @param _tokensBoughtAmounts Amount of Tokens id bought for each corresponding Token id in _tokenIds * @param _maxCurrency Total maximum amount of currency tokens to spend for all Token ids * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output Tokens and refund * @return currencySold How much currency was actually sold. */ function _currencyToToken( uint256[] memory _tokenIds, uint256[] memory _tokensBoughtAmounts, uint256 _maxCurrency, uint256 _deadline, address _recipient) internal nonReentrant() returns (uint256[] memory currencySold) { // Input validation require(_deadline >= block.timestamp, "NiftyswapExchange20#_currencyToToken: DEADLINE_EXCEEDED"); // Number of Token IDs to deposit uint256 nTokens = _tokenIds.length; uint256 totalRefundCurrency = _maxCurrency; // Initialize variables currencySold = new uint256[](nTokens); // Amount of currency tokens sold per ID // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes the currency Tokens are already received by contract, but not // the Tokens Ids // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 idBought = _tokenIds[i]; uint256 amountBought = _tokensBoughtAmounts[i]; uint256 tokenReserve = tokenReserves[i]; require(amountBought > 0, "NiftyswapExchange20#_currencyToToken: NULL_TOKENS_BOUGHT"); // Load currency token and Token _id reserves uint256 currencyReserve = currencyReserves[idBought]; // Get amount of currency tokens to send for purchase // Neither reserves amount have been changed so far in this transaction, so // no adjustment to the inputs is needed uint256 currencyAmount = getBuyPrice(amountBought, currencyReserve, tokenReserve); // Calculate currency token amount to refund (if any) where whatever is not used will be returned // Will throw if total cost exceeds _maxCurrency totalRefundCurrency = totalRefundCurrency.sub(currencyAmount); // Append Token id, Token id amount and currency token amount to tracking arrays currencySold[i] = currencyAmount; // Update individual currency reseve amount currencyReserves[idBought] = currencyReserve.add(currencyAmount); } // Refund currency token if any if (totalRefundCurrency > 0) { TransferHelper.safeTransfer(currency, _recipient, totalRefundCurrency); } // Send Tokens all tokens purchased token.safeBatchTransferFrom(address(this), _recipient, _tokenIds, _tokensBoughtAmounts, ""); return currencySold; } /** * @dev Pricing function used for converting between currency token to Tokens. * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return price Amount of currency tokens to send to Niftyswap. */ function getBuyPrice( uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public pure returns (uint256 price) { // Reserves must not be empty require(_assetSoldReserve > 0 && _assetBoughtReserve > 0, "NiftyswapExchange20#getBuyPrice: EMPTY_RESERVE"); // Calculate price with fee uint256 numerator = _assetSoldReserve.mul(_assetBoughtAmount).mul(1000); uint256 denominator = (_assetBoughtReserve.sub(_assetBoughtAmount)).mul(FEE_MULTIPLIER); (price, ) = divRound(numerator, denominator); return price; // Will add 1 if rounding error } /** * @notice Convert Tokens _id to currency tokens and transfers Tokens to recipient. * @dev User specifies EXACT Tokens _id sold and MINIMUM currency tokens received. * @dev Assumes that all trades will be valid, or the whole tx will fail * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _tokenIds Array of Token IDs that are sold * @param _tokensSoldAmounts Array of Amount of Tokens sold for each id in _tokenIds. * @param _minCurrency Minimum amount of currency tokens to receive * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output currency tokens. * @return currencyBought How much currency was actually purchased. */ function _tokenToCurrency( uint256[] memory _tokenIds, uint256[] memory _tokensSoldAmounts, uint256 _minCurrency, uint256 _deadline, address _recipient) internal nonReentrant() returns (uint256[] memory currencyBought) { // Number of Token IDs to deposit uint256 nTokens = _tokenIds.length; // Input validation require(_deadline >= block.timestamp, "NiftyswapExchange20#_tokenToCurrency: DEADLINE_EXCEEDED"); // Initialize variables uint256 totalCurrency = 0; // Total amount of currency tokens to transfer currencyBought = new uint256[](nTokens); // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes the Tokens ids are already received by contract, but not // the Tokens Ids. Will return cards not sold if invalid price. // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 idSold = _tokenIds[i]; uint256 amountSold = _tokensSoldAmounts[i]; uint256 tokenReserve = tokenReserves[i]; // If 0 tokens send for this ID, revert require(amountSold > 0, "NiftyswapExchange20#_tokenToCurrency: NULL_TOKENS_SOLD"); // Load currency token and Token _id reserves uint256 currencyReserve = currencyReserves[idSold]; // Get amount of currency that will be received // Need to sub amountSold because tokens already added in reserve, which would bias the calculation // Don't need to add it for currencyReserve because the amount is added after this calculation uint256 currencyAmount = getSellPrice(amountSold, tokenReserve.sub(amountSold), currencyReserve); // Increase cost of transaction totalCurrency = totalCurrency.add(currencyAmount); // Update individual currency reseve amount currencyReserves[idSold] = currencyReserve.sub(currencyAmount); // Append Token id, Token id amount and currency token amount to tracking arrays currencyBought[i] = currencyAmount; } // If minCurrency is not met require(totalCurrency >= _minCurrency, "NiftyswapExchange20#_tokenToCurrency: INSUFFICIENT_CURRENCY_AMOUNT"); // Transfer currency here TransferHelper.safeTransfer(currency, _recipient, totalCurrency); return currencyBought; } /** * @dev Pricing function used for converting Tokens to currency token. * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return price Amount of currency tokens to receive from Niftyswap. */ function getSellPrice( uint256 _assetSoldAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public pure returns (uint256 price) { //Reserves must not be empty require(_assetSoldReserve > 0 && _assetBoughtReserve > 0, "NiftyswapExchange20#getSellPrice: EMPTY_RESERVE"); // Calculate amount to receive (with fee) uint256 _assetSoldAmount_withFee = _assetSoldAmount.mul(FEE_MULTIPLIER); uint256 numerator = _assetSoldAmount_withFee.mul(_assetBoughtReserve); uint256 denominator = _assetSoldReserve.mul(1000).add(_assetSoldAmount_withFee); return numerator / denominator; //Rounding errors will favor Niftyswap, so nothing to do } /***********************************| | Liquidity Functions | |__________________________________*/ /** * @notice Deposit less than max currency tokens && exact Tokens (token ID) at current ratio to mint liquidity pool tokens. * @dev min_liquidity does nothing when total liquidity pool token supply is 0. * @dev Assumes that sender approved this contract on the currency * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _provider Address that provides liquidity to the reserve * @param _tokenIds Array of Token IDs where liquidity is added * @param _tokenAmounts Array of amount of Tokens deposited corresponding to each ID provided in _tokenIds * @param _maxCurrency Array of maximum number of tokens deposited for each ID provided in _tokenIds. * Deposits max amount if total liquidity pool token supply is 0. * @param _deadline Timestamp after which this transaction will be reverted */ function _addLiquidity( address _provider, uint256[] memory _tokenIds, uint256[] memory _tokenAmounts, uint256[] memory _maxCurrency, uint256 _deadline) internal nonReentrant() { // Requirements require(_deadline >= block.timestamp, "NiftyswapExchange20#_addLiquidity: DEADLINE_EXCEEDED"); // Initialize variables uint256 nTokens = _tokenIds.length; // Number of Token IDs to deposit uint256 totalCurrency = 0; // Total amount of currency tokens to transfer // Initialize arrays uint256[] memory liquiditiesToMint = new uint256[](nTokens); uint256[] memory currencyAmounts = new uint256[](nTokens); // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes tokens _ids are deposited already, but not currency tokens // as this is calculated and executed below. // Loop over all Token IDs to deposit for (uint256 i = 0; i < nTokens; i ++) { // Store current id and amount from argument arrays uint256 tokenId = _tokenIds[i]; uint256 amount = _tokenAmounts[i]; // Check if input values are acceptable require(_maxCurrency[i] > 0, "NiftyswapExchange20#_addLiquidity: NULL_MAX_CURRENCY"); require(amount > 0, "NiftyswapExchange20#_addLiquidity: NULL_TOKENS_AMOUNT"); // Current total liquidity calculated in currency token uint256 totalLiquidity = totalSupplies[tokenId]; // When reserve for this token already exists if (totalLiquidity > 0) { // Load currency token and Token reserve's supply of Token id uint256 currencyReserve = currencyReserves[tokenId]; // Amount not yet in reserve uint256 tokenReserve = tokenReserves[i]; /** * Amount of currency tokens to send to token id reserve: * X/Y = dx/dy * dx = X*dy/Y * where * X: currency total liquidity * Y: Token _id total liquidity (before tokens were received) * dy: Amount of token _id deposited * dx: Amount of currency to deposit * * Adding .add(1) if rounding errors so to not favor users incorrectly */ (uint256 currencyAmount, bool rounded) = divRound(amount.mul(currencyReserve), tokenReserve.sub(amount)); require(_maxCurrency[i] >= currencyAmount, "NiftyswapExchange20#_addLiquidity: MAX_CURRENCY_AMOUNT_EXCEEDED"); // Update currency reserve size for Token id before transfer currencyReserves[tokenId] = currencyReserve.add(currencyAmount); // Update totalCurrency totalCurrency = totalCurrency.add(currencyAmount); // Proportion of the liquidity pool to give to current liquidity provider // If rounding error occured, round down to favor previous liquidity providers // See https://github.com/0xsequence/niftyswap/issues/19 liquiditiesToMint[i] = (currencyAmount.sub(rounded ? 1 : 0)).mul(totalLiquidity) / currencyReserve; currencyAmounts[i] = currencyAmount; // Mint liquidity ownership tokens and increase liquidity supply accordingly totalSupplies[tokenId] = totalLiquidity.add(liquiditiesToMint[i]); } else { uint256 maxCurrency = _maxCurrency[i]; // Otherwise rounding error could end up being significant on second deposit require(maxCurrency >= 1000000000, "NiftyswapExchange20#_addLiquidity: INVALID_CURRENCY_AMOUNT"); // Update currency reserve size for Token id before transfer currencyReserves[tokenId] = maxCurrency; // Update totalCurrency totalCurrency = totalCurrency.add(maxCurrency); // Initial liquidity is amount deposited (Incorrect pricing will be arbitraged) // uint256 initialLiquidity = _maxCurrency; totalSupplies[tokenId] = maxCurrency; // Liquidity to mints liquiditiesToMint[i] = maxCurrency; currencyAmounts[i] = maxCurrency; } } // Mint liquidity pool tokens _batchMint(_provider, _tokenIds, liquiditiesToMint, ""); // Transfer all currency to this contract TransferHelper.safeTransferFrom(currency, _provider, address(this), totalCurrency); // Emit event emit LiquidityAdded(_provider, _tokenIds, _tokenAmounts, currencyAmounts); } /** * @dev Burn liquidity pool tokens to withdraw currency && Tokens at current ratio. * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _provider Address that removes liquidity to the reserve * @param _tokenIds Array of Token IDs where liquidity is removed * @param _poolTokenAmounts Array of Amount of liquidity pool tokens burned for each Token id in _tokenIds. * @param _minCurrency Minimum currency withdrawn for each Token id in _tokenIds. * @param _minTokens Minimum Tokens id withdrawn for each Token id in _tokenIds. * @param _deadline Timestamp after which this transaction will be reverted */ function _removeLiquidity( address _provider, uint256[] memory _tokenIds, uint256[] memory _poolTokenAmounts, uint256[] memory _minCurrency, uint256[] memory _minTokens, uint256 _deadline) internal nonReentrant() { // Input validation require(_deadline > block.timestamp, "NiftyswapExchange20#_removeLiquidity: DEADLINE_EXCEEDED"); // Initialize variables uint256 nTokens = _tokenIds.length; // Number of Token IDs to deposit uint256 totalCurrency = 0; // Total amount of currency to transfer uint256[] memory tokenAmounts = new uint256[](nTokens); // Amount of Tokens to transfer for each id uint256[] memory currencyAmounts = new uint256[](nTokens); // Amount of currency to transfer for each id // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes NIFTY liquidity tokens are already received by contract, but not // the currency nor the Tokens Ids // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 id = _tokenIds[i]; uint256 amountPool = _poolTokenAmounts[i]; uint256 tokenReserve = tokenReserves[i]; // Load total liquidity pool token supply for Token _id uint256 totalLiquidity = totalSupplies[id]; require(totalLiquidity > 0, "NiftyswapExchange20#_removeLiquidity: NULL_TOTAL_LIQUIDITY"); // Load currency and Token reserve's supply of Token id uint256 currencyReserve = currencyReserves[id]; // Calculate amount to withdraw for currency and Token _id uint256 currencyAmount = amountPool.mul(currencyReserve) / totalLiquidity; uint256 tokenAmount = amountPool.mul(tokenReserve) / totalLiquidity; // Verify if amounts to withdraw respect minimums specified require(currencyAmount >= _minCurrency[i], "NiftyswapExchange20#_removeLiquidity: INSUFFICIENT_CURRENCY_AMOUNT"); require(tokenAmount >= _minTokens[i], "NiftyswapExchange20#_removeLiquidity: INSUFFICIENT_TOKENS"); // Update total liquidity pool token supply of Token _id totalSupplies[id] = totalLiquidity.sub(amountPool); // Update currency reserve size for Token id currencyReserves[id] = currencyReserve.sub(currencyAmount); // Update totalCurrency and tokenAmounts totalCurrency = totalCurrency.add(currencyAmount); tokenAmounts[i] = tokenAmount; currencyAmounts[i] = currencyAmount; } // Burn liquidity pool tokens for offchain supplies _batchBurn(address(this), _tokenIds, _poolTokenAmounts); // Transfer total currency and all Tokens ids TransferHelper.safeTransfer(currency, _provider, totalCurrency); token.safeBatchTransferFrom(address(this), _provider, _tokenIds, tokenAmounts, ""); // Emit event emit LiquidityRemoved(_provider, _tokenIds, tokenAmounts, currencyAmounts); } /***********************************| | Receiver Methods Handler | |__________________________________*/ // Method signatures for onReceive control logic // bytes4(keccak256( // "_tokenToCurrency(uint256[],uint256[],uint256,uint256,address)" // )); bytes4 internal constant SELLTOKENS_SIG = 0xdb08ec97; // bytes4(keccak256( // "_addLiquidity(address,uint256[],uint256[],uint256[],uint256)" // )); bytes4 internal constant ADDLIQUIDITY_SIG = 0x82da2b73; // bytes4(keccak256( // "_removeLiquidity(address,uint256[],uint256[],uint256[],uint256[],uint256)" // )); bytes4 internal constant REMOVELIQUIDITY_SIG = 0x5c0bf259; // bytes4(keccak256( // "DepositTokens()" // )); bytes4 internal constant DEPOSIT_SIG = 0xc8c323f9; /***********************************| | Buying Tokens | |__________________________________*/ /** * @dev Purchase tokens with currency. */ function buyTokens( uint256[] memory _tokenIds, uint256[] memory _tokensBoughtAmounts, uint256 _maxCurrency, uint256 _deadline, address _recipient ) override external returns (uint256[] memory) { require(_deadline >= block.timestamp, "NiftyswapExchange20#buyTokens: DEADLINE_EXCEEDED"); require(_tokenIds.length > 0, "NiftyswapExchange20#buyTokens: INVALID_CURRENCY_IDS_AMOUNT"); // Transfer the tokens for purchase TransferHelper.safeTransferFrom(currency, msg.sender, address(this), _maxCurrency); address recipient = _recipient == address(0x0) ? msg.sender : _recipient; // Execute trade and retrieve amount of currency spent uint256[] memory currencySold = _currencyToToken(_tokenIds, _tokensBoughtAmounts, _maxCurrency, _deadline, recipient); emit TokensPurchase(msg.sender, recipient, _tokenIds, _tokensBoughtAmounts, currencySold); return currencySold; } /** * @notice Handle which method is being called on transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _from The address which previously owned the Token * @param _ids An array containing ids of each Token being transferred * @param _amounts An array containing amounts of each Token being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)") */ function onERC1155BatchReceived( address, // _operator, address _from, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) override public returns(bytes4) { // This function assumes that the ERC-1155 token contract can // only call `onERC1155BatchReceived()` via a valid token transfer. // Users must be responsible and only use this Niftyswap exchange // contract with ERC-1155 compliant token contracts. // Obtain method to call via object signature bytes4 functionSignature = abi.decode(_data, (bytes4)); /***********************************| | Selling Tokens | |__________________________________*/ if (functionSignature == SELLTOKENS_SIG) { // Tokens received need to be Token contract require(msg.sender == address(token), "NiftyswapExchange20#onERC1155BatchReceived: INVALID_TOKENS_TRANSFERRED"); // Decode SellTokensObj from _data to call _tokenToCurrency() SellTokensObj memory obj; (, obj) = abi.decode(_data, (bytes4, SellTokensObj)); address recipient = obj.recipient == address(0x0) ? _from : obj.recipient; // Execute trade and retrieve amount of currency received uint256[] memory currencyBought = _tokenToCurrency(_ids, _amounts, obj.minCurrency, obj.deadline, recipient); emit CurrencyPurchase(_from, recipient, _ids, _amounts, currencyBought); /***********************************| | Adding Liquidity Tokens | |__________________________________*/ } else if (functionSignature == ADDLIQUIDITY_SIG) { // Only allow to receive ERC-1155 tokens from `token` contract require(msg.sender == address(token), "NiftyswapExchange20#onERC1155BatchReceived: INVALID_TOKEN_TRANSFERRED"); // Decode AddLiquidityObj from _data to call _addLiquidity() AddLiquidityObj memory obj; (, obj) = abi.decode(_data, (bytes4, AddLiquidityObj)); _addLiquidity(_from, _ids, _amounts, obj.maxCurrency, obj.deadline); /***********************************| | Removing iquidity Tokens | |__________________________________*/ } else if (functionSignature == REMOVELIQUIDITY_SIG) { // Tokens received need to be NIFTY-1155 tokens require(msg.sender == address(this), "NiftyswapExchange20#onERC1155BatchReceived: INVALID_NIFTY_TOKENS_TRANSFERRED"); // Decode RemoveLiquidityObj from _data to call _removeLiquidity() RemoveLiquidityObj memory obj; (, obj) = abi.decode(_data, (bytes4, RemoveLiquidityObj)); _removeLiquidity(_from, _ids, _amounts, obj.minCurrency, obj.minTokens, obj.deadline); /***********************************| | Deposits & Invalid Calls | |__________________________________*/ } else if (functionSignature == DEPOSIT_SIG) { // Do nothing for when contract is self depositing // This could be use to deposit currency "by accident", which would be locked require(msg.sender == address(currency), "NiftyswapExchange20#onERC1155BatchReceived: INVALID_TOKENS_DEPOSITED"); } else { revert("NiftyswapExchange20#onERC1155BatchReceived: INVALID_METHOD"); } return ERC1155_BATCH_RECEIVED_VALUE; } /** * @dev Will pass to onERC115Batch5Received */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes memory _data) override public returns(bytes4) { uint256[] memory ids = new uint256[](1); uint256[] memory amounts = new uint256[](1); ids[0] = _id; amounts[0] = _amount; require( ERC1155_BATCH_RECEIVED_VALUE == onERC1155BatchReceived(_operator, _from, ids, amounts, _data), "NiftyswapExchange20#onERC1155Received: INVALID_ONRECEIVED_MESSAGE" ); return ERC1155_RECEIVED_VALUE; } /** * @notice Prevents receiving Ether or calls to unsuported methods */ fallback () external { revert("NiftyswapExchange:UNSUPPORTED_METHOD"); } /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Get amount of currency in reserve for each Token _id in _ids * @param _ids Array of ID sto query currency reserve of * @return amount of currency in reserve for each Token _id */ function getCurrencyReserves( uint256[] calldata _ids) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory currencyReservesReturn = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { currencyReservesReturn[i] = currencyReserves[_ids[i]]; } return currencyReservesReturn; } /** * @notice Return price for `currency => Token _id` trades with an exact token amount. * @param _ids Array of ID of tokens bought. * @param _tokensBought Amount of Tokens bought. * @return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought */ function getPrice_currencyToToken( uint256[] calldata _ids, uint256[] calldata _tokensBought) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory prices = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { // Load Token id reserve uint256 tokenReserve = token.balanceOf(address(this), _ids[i]); prices[i] = getBuyPrice(_tokensBought[i], currencyReserves[_ids[i]], tokenReserve); } // Return prices return prices; } /** * @notice Return price for `Token _id => currency` trades with an exact token amount. * @param _ids Array of IDs token sold. * @param _tokensSold Array of amount of each Token sold. * @return Amount of currency that can be bought for Tokens in _ids for amounts in _tokensSold */ function getPrice_tokenToCurrency( uint256[] calldata _ids, uint256[] calldata _tokensSold) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory prices = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { // Load Token id reserve uint256 tokenReserve = token.balanceOf(address(this), _ids[i]); prices[i] = getSellPrice(_tokensSold[i], tokenReserve, currencyReserves[_ids[i]]); } // Return price return prices; } /** * @return Address of Token that is sold on this exchange. */ function getTokenAddress() override external view returns (address) { return address(token); } /** * @return Address of the currency contract that is used as currency */ function getCurrencyInfo() override external view returns (address) { return (address(currency)); } /** * @notice Get total supply of liquidity tokens * @param _ids ID of the Tokens * @return The total supply of each liquidity token id provided in _ids */ function getTotalSupply(uint256[] calldata _ids) override external view returns (uint256[] memory) { // Number of ids uint256 nIds = _ids.length; // Variables uint256[] memory batchTotalSupplies = new uint256[](nIds); // Iterate over each owner and token ID for (uint256 i = 0; i < nIds; i++) { batchTotalSupplies[i] = totalSupplies[_ids[i]]; } return batchTotalSupplies; } /** * @return Address of factory that created this exchange. */ function getFactoryAddress() override external view returns (address) { return factory; } /***********************************| | Utility Functions | |__________________________________*/ /** * @notice Divides two numbers and add 1 if there is a rounding error * @param a Numerator * @param b Denominator */ function divRound(uint256 a, uint256 b) internal pure returns (uint256, bool) { return a % b == 0 ? (a/b, false) : ((a/b).add(1), true); } /** * @notice Return Token reserves for given Token ids * @dev Assumes that ids are sorted from lowest to highest with no duplicates. * This assumption allows for checking the token reserves only once, otherwise * token reserves need to be re-checked individually or would have to do more expensive * duplication checks. * @param _tokenIds Array of IDs to query their Reserve balance. * @return Array of Token ids' reserves */ function _getTokenReserves( uint256[] memory _tokenIds) internal view returns (uint256[] memory) { uint256 nTokens = _tokenIds.length; // Regular balance query if only 1 token, otherwise batch query if (nTokens == 1) { uint256[] memory tokenReserves = new uint256[](1); tokenReserves[0] = token.balanceOf(address(this), _tokenIds[0]); return tokenReserves; } else { // Lazy check preventing duplicates & build address array for query address[] memory thisAddressArray = new address[](nTokens); thisAddressArray[0] = address(this); for (uint256 i = 1; i < nTokens; i++) { require(_tokenIds[i-1] < _tokenIds[i], "NiftyswapExchange20#_getTokenReserves: UNSORTED_OR_DUPLICATE_TOKEN_IDS"); thisAddressArray[i] = address(this); } return token.balanceOfBatch(thisAddressArray, _tokenIds); } } /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more thsan 5,000 gas. * @return Whether a given interface is supported */ function supportsInterface(bytes4 interfaceID) public override pure returns (bool) { return interfaceID == type(IERC20).interfaceId || interfaceID == type(IERC165).interfaceId || interfaceID == type(IERC1155).interfaceId || interfaceID == type(IERC1155TokenReceiver).interfaceId; } }
currency Token reserve per Token id
mapping(uint256 => uint256) internal currencyReserves;
1,793,669
[ 1, 7095, 3155, 20501, 1534, 3155, 612, 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, 225, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 2713, 5462, 607, 264, 3324, 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 ]
// SPDX-Licene-Identifier: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "./libraries/DecimalsConverter.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/IShieldMining.sol"; import "./interfaces/ILiquidityRegistry.sol"; import "./interfaces/IPolicyBookAdmin.sol"; import "./interfaces/IPolicyBookFacade.sol"; import "./interfaces/helpers/IPriceFeed.sol"; import "./interfaces/IPolicyBookFabric.sol"; import "./interfaces/IPolicyBookRegistry.sol"; import "./abstract/AbstractDependant.sol"; import "./Globals.sol"; contract PolicyBookFacade is IPolicyBookFacade, AbstractDependant, Initializable { using EnumerableSet for EnumerableSet.AddressSet; using Math for uint256; IPolicyBookAdmin public policyBookAdmin; ILeveragePortfolio public reinsurancePool; IPolicyBook public override policyBook; IShieldMining public shieldMining; IPolicyBookRegistry public policyBookRegistry; using SafeMath for uint256; ILiquidityRegistry public liquidityRegistry; address public capitalPoolAddress; address public priceFeed; // virtual funds deployed by reinsurance pool uint256 public override VUreinsurnacePool; // leverage funds deployed by reinsurance pool uint256 public override LUreinsurnacePool; // leverage funds deployed by user leverage pool mapping(address => uint256) public override LUuserLeveragePool; // total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool) uint256 public override totalLeveragedLiquidity; uint256 public override userleveragedMPL; uint256 public override reinsurancePoolMPL; uint256 public override rebalancingThreshold; bool public override safePricingModel; mapping(address => uint256) public override userLiquidity; EnumerableSet.AddressSet internal userLeveragePools; event DeployLeverageFunds(uint256 _deployedAmount); modifier onlyCapitalPool() { require(msg.sender == capitalPoolAddress, "PBFC: only CapitalPool"); _; } modifier onlyPolicyBookAdmin() { require(msg.sender == address(policyBookAdmin), "PBFC: Not a PBA"); _; } modifier onlyLeveragePortfolio() { require( msg.sender == address(reinsurancePool) || policyBookRegistry.isUserLeveragePool(msg.sender), "PBFC: only LeveragePortfolio" ); _; } modifier onlyPolicyBookRegistry() { require(msg.sender == address(policyBookRegistry), "PBFC: Not a policy book registry"); _; } function __PolicyBookFacade_init( address pbProxy, address liquidityProvider, uint256 _initialDeposit ) external override initializer { policyBook = IPolicyBook(pbProxy); rebalancingThreshold = DEFAULT_REBALANCING_THRESHOLD; userLiquidity[liquidityProvider] = _initialDeposit; } function setDependencies(IContractsRegistry contractsRegistry) external override onlyInjectorOrZero { IContractsRegistry _contractsRegistry = IContractsRegistry(contractsRegistry); capitalPoolAddress = _contractsRegistry.getCapitalPoolContract(); policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract()); policyBookAdmin = IPolicyBookAdmin(_contractsRegistry.getPolicyBookAdminContract()); priceFeed = _contractsRegistry.getPriceFeedContract(); reinsurancePool = ILeveragePortfolio(_contractsRegistry.getReinsurancePoolContract()); shieldMining = IShieldMining(_contractsRegistry.getShieldMiningContract()); } /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _epochsNumber is number of seconds to cover /// @param _coverTokens is number of tokens to cover function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external override { _buyPolicy(msg.sender, msg.sender, _epochsNumber, _coverTokens, 0, address(0)); } function buyPolicyFor( address _holder, uint256 _epochsNumber, uint256 _coverTokens ) external override { _buyPolicy(msg.sender, _holder, _epochsNumber, _coverTokens, 0, address(0)); } function buyPolicyFromDistributor( uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external override { uint256 _distributorFee = policyBookAdmin.distributorFees(_distributor); _buyPolicy( msg.sender, msg.sender, _epochsNumber, _coverTokens, _distributorFee, _distributor ); } /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _holder address user the policy is being "bought for" /// @param _epochsNumber is number of seconds to cover /// @param _coverTokens is number of tokens to cover function buyPolicyFromDistributorFor( address _holder, uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external override { uint256 _distributorFee = policyBookAdmin.distributorFees(_distributor); _buyPolicy( msg.sender, _holder, _epochsNumber, _coverTokens, _distributorFee, _distributor ); } /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidity(uint256 _liquidityAmount) external override { _addLiquidity(msg.sender, msg.sender, _liquidityAmount, 0); } function addLiquidityFromDistributorFor(address _liquidityHolderAddr, uint256 _liquidityAmount) external override { _addLiquidity(msg.sender, _liquidityHolderAddr, _liquidityAmount, 0); } /// @notice Let user to add liquidity by supplying stable coin and stake it, /// @dev access: ANY function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external override { _addLiquidity(msg.sender, msg.sender, _liquidityAmount, _stakeSTBLAmount); } function _addLiquidity( address _liquidityBuyerAddr, address _liquidityHolderAddr, uint256 _liquidityAmount, uint256 _stakeSTBLAmount ) internal { uint256 _tokensToAdd = policyBook.addLiquidity( _liquidityBuyerAddr, _liquidityHolderAddr, _liquidityAmount, _stakeSTBLAmount ); _reevaluateProvidedLeverageStable(_liquidityAmount); _updateShieldMining(_liquidityHolderAddr, _tokensToAdd, false); } function _buyPolicy( address _policyBuyerAddr, address _policyHolderAddr, uint256 _epochsNumber, uint256 _coverTokens, uint256 _distributorFee, address _distributor ) internal { (uint256 _premium, ) = policyBook.buyPolicy( _policyBuyerAddr, _policyHolderAddr, _epochsNumber, _coverTokens, _distributorFee, _distributor ); _reevaluateProvidedLeverageStable(_premium); } function _reevaluateProvidedLeverageStable(uint256 newAmount) internal { uint256 _newAmountPercentage; uint256 _totalLiq = policyBook.totalLiquidity(); if (_totalLiq > 0) { _newAmountPercentage = newAmount.mul(PERCENTAGE_100).div(_totalLiq); } if ((_totalLiq > 0 && _newAmountPercentage > rebalancingThreshold) || _totalLiq == 0) { _deployLeveragedFunds(); } } /// @notice deploy leverage funds (RP lStable, ULP lStable) /// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity /// @param leveragePool whether user leverage or reinsurance leverage function deployLeverageFundsAfterRebalance( uint256 deployedAmount, ILeveragePortfolio.LeveragePortfolio leveragePool ) external override onlyLeveragePortfolio { if (leveragePool == ILeveragePortfolio.LeveragePortfolio.USERLEVERAGEPOOL) { LUuserLeveragePool[msg.sender] = deployedAmount; LUuserLeveragePool[msg.sender] > 0 ? userLeveragePools.add(msg.sender) : userLeveragePools.remove(msg.sender); } else { LUreinsurnacePool = deployedAmount; } uint256 _LUuserLeveragePool; for (uint256 i = 0; i < userLeveragePools.length(); i++) { _LUuserLeveragePool += LUuserLeveragePool[userLeveragePools.at(i)]; } totalLeveragedLiquidity = VUreinsurnacePool.add(LUreinsurnacePool).add( _LUuserLeveragePool ); emit DeployLeverageFunds(deployedAmount); } /// @notice deploy virtual funds (RP vStable) /// @param deployedAmount uint256 the deployed amount to be added to the liquidity function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external override onlyLeveragePortfolio { VUreinsurnacePool = deployedAmount; uint256 _LUuserLeveragePool; if (userLeveragePools.length() > 0) { _LUuserLeveragePool = LUuserLeveragePool[userLeveragePools.at(0)]; } totalLeveragedLiquidity = VUreinsurnacePool.add(LUreinsurnacePool).add( _LUuserLeveragePool ); emit DeployLeverageFunds(deployedAmount); } function _deployLeveragedFunds() internal { uint256 _deployedAmount; uint256 _LUuserLeveragePool; _deployedAmount = reinsurancePool.deployVirtualStableToCoveragePools(); VUreinsurnacePool = _deployedAmount; _deployedAmount = reinsurancePool.deployLeverageStableToCoveragePools( ILeveragePortfolio.LeveragePortfolio.REINSURANCEPOOL ); LUreinsurnacePool = _deployedAmount; address[] memory _userLeverageArr = policyBookRegistry.listByType( IPolicyBookFabric.ContractType.VARIOUS, 0, policyBookRegistry.countByType(IPolicyBookFabric.ContractType.VARIOUS) ); for (uint256 i = 0; i < _userLeverageArr.length; i++) { _deployedAmount = ILeveragePortfolio(_userLeverageArr[i]) .deployLeverageStableToCoveragePools( ILeveragePortfolio.LeveragePortfolio.USERLEVERAGEPOOL ); LUuserLeveragePool[_userLeverageArr[i]] = _deployedAmount; _deployedAmount > 0 ? userLeveragePools.add(_userLeverageArr[i]) : userLeveragePools.remove(_userLeverageArr[i]); _LUuserLeveragePool += _deployedAmount; } totalLeveragedLiquidity = VUreinsurnacePool.add(LUreinsurnacePool).add( _LUuserLeveragePool ); } function _updateShieldMining( address liquidityProvider, uint256 liquidityAmount, bool isWithdraw ) internal { // check if SM active if (shieldMining.getShieldTokenAddress(address(policyBook)) != address(0)) { shieldMining.updateTotalSupply(address(policyBook), address(0), liquidityProvider); } if (isWithdraw) { userLiquidity[liquidityProvider] -= liquidityAmount; } else { userLiquidity[liquidityProvider] += liquidityAmount; } } /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external override { uint256 _withdrawAmount = policyBook.withdrawLiquidity(msg.sender); _reevaluateProvidedLeverageStable(_withdrawAmount); _updateShieldMining(msg.sender, _withdrawAmount, true); } /// @notice set the MPL for the user leverage and the reinsurance leverage /// @param _userLeverageMPL uint256 value of the user leverage MPL /// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external override onlyPolicyBookAdmin { userleveragedMPL = _userLeverageMPL; reinsurancePoolMPL = _reinsuranceLeverageMPL; } /// @notice sets the rebalancing threshold value /// @param _newRebalancingThreshold uint256 rebalancing threshhold value function setRebalancingThreshold(uint256 _newRebalancingThreshold) external override onlyPolicyBookAdmin { require(_newRebalancingThreshold > 0, "PBF: threshold can not be 0"); rebalancingThreshold = _newRebalancingThreshold; } /// @notice sets the rebalancing threshold value /// @param _safePricingModel bool is pricing model safe (true) or not (false) function setSafePricingModel(bool _safePricingModel) external override onlyPolicyBookAdmin { safePricingModel = _safePricingModel; } /// @notice fetches all the pools data /// @return uint256 VUreinsurnacePool /// @return uint256 LUreinsurnacePool /// @return uint256 LUleveragePool /// @return uint256 user leverage pool address function getPoolsData() external view override returns ( uint256, uint256, uint256, address ) { uint256 _LUuserLeveragePool; address _userLeverageAddress; if (userLeveragePools.length() > 0) { _LUuserLeveragePool = DecimalsConverter.convertFrom18( LUuserLeveragePool[userLeveragePools.at(0)], policyBook.stblDecimals() ); _userLeverageAddress = userLeveragePools.at(0); } return ( DecimalsConverter.convertFrom18(VUreinsurnacePool, policyBook.stblDecimals()), DecimalsConverter.convertFrom18(LUreinsurnacePool, policyBook.stblDecimals()), _LUuserLeveragePool, _userLeverageAddress ); } // TODO possible sandwich attack or allowance fluctuation function getClaimApprovalAmount(address user) external view override returns (uint256) { (uint256 _coverTokens, , , , ) = policyBook.policyHolders(user); _coverTokens = DecimalsConverter.convertFrom18( _coverTokens.div(100), policyBook.stblDecimals() ); return IPriceFeed(priceFeed).howManyBMIsInUSDT(_coverTokens); } /// @notice upserts a withdraw request /// @dev prevents adding a request if an already pending or ready request is open. /// @param _tokensToWithdraw uint256 amount of tokens to withdraw function requestWithdrawal(uint256 _tokensToWithdraw) external override { IPolicyBook.WithdrawalStatus _withdrawlStatus = policyBook.getWithdrawalStatus(msg.sender); require( _withdrawlStatus == IPolicyBook.WithdrawalStatus.NONE || _withdrawlStatus == IPolicyBook.WithdrawalStatus.EXPIRED, "PBf: ongoing withdrawl request" ); policyBook.requestWithdrawal(_tokensToWithdraw, msg.sender); liquidityRegistry.registerWithdrawl(address(policyBook), msg.sender); } /// @notice Used to get a list of user leverage pools which provide leverage to this pool , use with count() /// @return _userLeveragePools a list containing policybook addresses function listUserLeveragePools(uint256 offset, uint256 limit) external view override returns (address[] memory _userLeveragePools) { uint256 to = (offset.add(limit)).min(userLeveragePools.length()).max(offset); _userLeveragePools = new address[](to - offset); for (uint256 i = offset; i < to; i++) { _userLeveragePools[i - offset] = userLeveragePools.at(i); } } /// @notice get count of user leverage pools which provide leverage to this pool function countUserLeveragePools() external view override returns (uint256) { return userLeveragePools.length(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @notice the intention of this library is to be able to easily convert /// one amount of tokens with N decimal places /// to another amount with M decimal places library DecimalsConverter { using SafeMath for uint256; function convert( uint256 amount, uint256 baseDecimals, uint256 destinationDecimals ) internal pure returns (uint256) { if (baseDecimals > destinationDecimals) { amount = amount.div(10**(baseDecimals - destinationDecimals)); } else if (baseDecimals < destinationDecimals) { amount = amount.mul(10**(destinationDecimals - baseDecimals)); } return amount; } function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) { return convert(amount, baseDecimals, 18); } function convertFrom18(uint256 amount, uint256 destinationDecimals) internal pure returns (uint256) { return convert(amount, 18, destinationDecimals); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IPriceFeed { function howManyBMIsInUSDT(uint256 usdtAmount) external view returns (uint256); function howManyUSDTsInBMI(uint256 bmiAmount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IShieldMining { struct ShieldMiningInfo { IERC20 rewardsToken; uint8 decimals; uint256 firstBlockWithReward; uint256 lastBlockWithReward; uint256 lastUpdateBlock; uint256 rewardTokensLocked; uint256 rewardPerTokenStored; uint256 totalSupply; uint256[] endsOfDistribution; // new state post v2 uint256 nearestLastBlocksWithReward; // lastBlockWithReward => rewardPerBlock mapping(uint256 => uint256) rewardPerBlock; } struct ShieldMiningDeposit { address policyBook; uint256 amount; uint256 duration; uint256 depositRewardPerBlock; uint256 startBlock; uint256 endBlock; } /// TODO document SM functions function blocksWithRewardsPassed(address _policyBook) external view returns (uint256); function rewardPerToken(address _policyBook) external view returns (uint256); function earned( address _policyBook, address _userLeveragePool, address _account ) external view returns (uint256); function updateTotalSupply( address _policyBook, address _userLeveragePool, address liquidityProvider ) external; function associateShieldMining(address _policyBook, address _shieldMiningToken) external; function fillShieldMining( address _policyBook, uint256 _amount, uint256 _duration ) external; function getRewardFor( address _userAddress, address _policyBook, address _userLeveragePool ) external; function getRewardFor(address _userAddress, address _userLeveragePoolAddress) external; function getReward(address _policyBook, address _userLeveragePool) external; function getReward(address _userLeveragePoolAddress) external; function getShieldTokenAddress(address _policyBook) external view returns (address); function getShieldMiningInfo(address _policyBook) external view returns ( address _rewardsToken, uint256 _decimals, uint256 _firstBlockWithReward, uint256 _lastBlockWithReward, uint256 _lastUpdateBlock, uint256 _nearestLastBlocksWithReward, uint256 _rewardTokensLocked, uint256 _rewardPerTokenStored, uint256 _rewardPerBlock, uint256 _tokenPerDay, uint256 _totalSupply ); function getDepositList( address _account, uint256 _offset, uint256 _limit ) external view returns (ShieldMiningDeposit[] memory _depositsList); function countUsersDeposits(address _account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IPolicyBookRegistry { struct PolicyBookStats { string symbol; address insuredContract; IPolicyBookFabric.ContractType contractType; uint256 maxCapacity; uint256 totalSTBLLiquidity; uint256 totalLeveragedLiquidity; uint256 stakedSTBL; uint256 APY; uint256 annualInsuranceCost; uint256 bmiXRatio; bool whitelisted; } function policyBooksByInsuredAddress(address insuredContract) external view returns (address); function policyBookFacades(address facadeAddress) external view returns (address); /// @notice Adds PolicyBook to registry, access: PolicyFabric function add( address insuredContract, IPolicyBookFabric.ContractType contractType, address policyBook, address facadeAddress ) external; function whitelist(address policyBookAddress, bool whitelisted) external; /// @notice returns required allowances for the policybooks function getPoliciesPrices( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external view returns (uint256[] memory _durations, uint256[] memory _allowances); /// @notice Buys a batch of policies function buyPolicyBatch( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external; /// @notice Checks if provided address is a PolicyBook function isPolicyBook(address policyBook) external view returns (bool); /// @notice Checks if provided address is a policyBookFacade function isPolicyBookFacade(address _facadeAddress) external view returns (bool); /// @notice Checks if provided address is a user leverage pool function isUserLeveragePool(address policyBookAddress) external view returns (bool); /// @notice Returns number of registered PolicyBooks with certain contract type function countByType(IPolicyBookFabric.ContractType contractType) external view returns (uint256); /// @notice Returns number of registered PolicyBooks, access: ANY function count() external view returns (uint256); function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType) external view returns (uint256); function countWhitelisted() external view returns (uint256); /// @notice Listing registered PolicyBooks with certain contract type, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type function listByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses function list(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); function listByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); function listWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY function listWithStatsByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Listing registered PolicyBooks with stats, access: ANY function listWithStats(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Getting stats from policy books, access: ANY /// @param policyBooks is list of PolicyBooks addresses function stats(address[] calldata policyBooks) external view returns (PolicyBookStats[] memory _stats); /// @notice Return existing Policy Book contract, access: ANY /// @param insuredContract is contract address to lookup for created IPolicyBook function policyBookFor(address insuredContract) external view returns (address); /// @notice Getting stats from policy books, access: ANY /// @param insuredContracts is list of insuredContracts in registry function statsByInsuredContracts(address[] calldata insuredContracts) external view returns (PolicyBookStats[] memory _stats); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./IPolicyBook.sol"; import "./ILeveragePortfolio.sol"; interface IPolicyBookFacade { /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external; /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicyFor( address _holder, uint256 _epochsNumber, uint256 _coverTokens ) external; function policyBook() external view returns (IPolicyBook); function userLiquidity(address account) external view returns (uint256); /// @notice virtual funds deployed by reinsurance pool function VUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by reinsurance pool function LUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by user leverage pool function LUuserLeveragePool(address userLeveragePool) external view returns (uint256); /// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool) function totalLeveragedLiquidity() external view returns (uint256); function userleveragedMPL() external view returns (uint256); function reinsurancePoolMPL() external view returns (uint256); function rebalancingThreshold() external view returns (uint256); function safePricingModel() external view returns (bool); /// @notice policyBookFacade initializer /// @param pbProxy polciybook address upgreadable cotnract. function __PolicyBookFacade_init( address pbProxy, address liquidityProvider, uint256 initialDeposit ) external; /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributor( uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @param _buyer who is buying the coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributorFor( address _buyer, uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidity(uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _user the one taht add liquidity /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin and stake it, /// @dev access: ANY function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external; /// @notice fetches all the pools data /// @return uint256 VUreinsurnacePool /// @return uint256 LUreinsurnacePool /// @return uint256 LUleveragePool /// @return uint256 user leverage pool address function getPoolsData() external view returns ( uint256, uint256, uint256, address ); /// @notice deploy leverage funds (RP lStable, ULP lStable) /// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity /// @param leveragePool whether user leverage or reinsurance leverage function deployLeverageFundsAfterRebalance( uint256 deployedAmount, ILeveragePortfolio.LeveragePortfolio leveragePool ) external; /// @notice deploy virtual funds (RP vStable) /// @param deployedAmount uint256 the deployed amount to be added to the liquidity function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external; /// @notice set the MPL for the user leverage and the reinsurance leverage /// @param _userLeverageMPL uint256 value of the user leverage MPL /// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external; /// @notice sets the rebalancing threshold value /// @param _newRebalancingThreshold uint256 rebalancing threshhold value function setRebalancingThreshold(uint256 _newRebalancingThreshold) external; /// @notice sets the rebalancing threshold value /// @param _safePricingModel bool is pricing model safe (true) or not (false) function setSafePricingModel(bool _safePricingModel) external; /// @notice returns how many BMI tokens needs to approve in order to submit a claim function getClaimApprovalAmount(address user) external view returns (uint256); /// @notice upserts a withdraw request /// @dev prevents adding a request if an already pending or ready request is open. /// @param _tokensToWithdraw uint256 amount of tokens to withdraw function requestWithdrawal(uint256 _tokensToWithdraw) external; function listUserLeveragePools(uint256 offset, uint256 limit) external view returns (address[] memory _userLeveragePools); function countUserLeveragePools() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IPolicyBookFabric { enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS} /// @notice Create new Policy Book contract, access: ANY /// @param _contract is Contract to create policy book for /// @param _contractType is Contract to create policy book for /// @param _description is bmiXCover token desription for this policy book /// @param _projectSymbol replaces x in bmiXCover token symbol /// @param _initialDeposit is an amount user deposits on creation (addLiquidity()) /// @return _policyBook is address of created contract function create( address _contract, ContractType _contractType, string calldata _description, string calldata _projectSymbol, uint256 _initialDeposit, address _shieldMiningToken ) external returns (address); function createLeveragePools( ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IPolicyBookAdmin { function getUpgrader() external view returns (address); function getImplementationOfPolicyBook(address policyBookAddress) external returns (address); function getImplementationOfPolicyBookFacade(address policyBookFacadeAddress) external returns (address); function getCurrentPolicyBooksImplementation() external view returns (address); function getCurrentPolicyBooksFacadeImplementation() external view returns (address); function getCurrentUserLeverageImplementation() external view returns (address); /// @notice It blacklists or whitelists a PolicyBook. Only whitelisted PolicyBooks can /// receive stakes and funds /// @param policyBookAddress PolicyBook address that will be whitelisted or blacklisted /// @param whitelisted true to whitelist or false to blacklist a PolicyBook function whitelist(address policyBookAddress, bool whitelisted) external; /// @notice Whitelist distributor address. Commission fee is 2-5% of the Premium /// It comes from the Protocol’s fee part /// @dev If commission fee is 5%, so _distributorFee = 5 /// @param _distributor distributor address that will receive funds /// @param _distributorFee distributor fee amount function whitelistDistributor(address _distributor, uint256 _distributorFee) external; /// @notice Removes a distributor address from the distributor whitelist /// @param _distributor distributor address that will be blacklist function blacklistDistributor(address _distributor) external; /// @notice Distributor commission fee is 2-5% of the Premium /// It comes from the Protocol’s fee part /// @dev If max commission fee is 5%, so _distributorFeeCap = 5. Default value is 5 /// @param _distributor address of the distributor /// @return true if address is a whitelisted distributor function isWhitelistedDistributor(address _distributor) external view returns (bool); /// @notice Distributor commission fee is 2-5% of the Premium /// It comes from the Protocol’s fee part /// @dev If max commission fee is 5%, so _distributorFeeCap = 5. Default value is 5 /// @param _distributor address of the distributor /// @return distributor fee value. It is distributor commission function distributorFees(address _distributor) external view returns (uint256); /// @notice Used to get a list of whitelisted distributors /// @dev If max commission fee is 5%, so _distributorFeeCap = 5. Default value is 5 /// @return _distributors a list containing distritubors addresses /// @return _distributorsFees a list containing distritubors fees function listDistributors(uint256 offset, uint256 limit) external view returns (address[] memory _distributors, uint256[] memory _distributorsFees); /// @notice Returns number of whitelisted distributors, access: ANY function countDistributors() external view returns (uint256); /// @notice sets the policybookFacade mpls values /// @param _facadeAddress address of the policybook facade /// @param _userLeverageMPL uint256 value of the user leverage mpl; /// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage mpl function setPolicyBookFacadeMPLs( address _facadeAddress, uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL ) external; /// @notice sets the policybookFacade mpls values /// @param _facadeAddress address of the policybook facade /// @param _newRebalancingThreshold uint256 value of the reinsurance leverage mpl function setPolicyBookFacadeRebalancingThreshold( address _facadeAddress, uint256 _newRebalancingThreshold ) external; /// @notice sets the policybookFacade mpls values /// @param _facadeAddress address of the policybook facade /// @param _safePricingModel bool is pricing model safe (true) or not (false) function setPolicyBookFacadeSafePricingModel(address _facadeAddress, bool _safePricingModel) external; function setLeveragePortfolioRebalancingThreshold( address _LeveragePoolAddress, uint256 _newRebalancingThreshold ) external; function setLeveragePortfolioProtocolConstant( address _LeveragePoolAddress, uint256 _targetUR, uint256 _d_ProtocolConstant, uint256 _a_ProtocolConstant, uint256 _max_ProtocolConstant ) external; function setUserLeverageMaxCapacities(address _userLeverageAddress, uint256 _maxCapacities) external; /// @notice setup all pricing model varlues ///@param _riskyAssetThresholdPercentage URRp Utilization ration for pricing model when the assets is considered risky, % ///@param _minimumCostPercentage MC minimum cost of cover (Premium), %; ///@param _minimumInsuranceCost minimum cost of insurance (Premium) , (10**18) ///@param _lowRiskMaxPercentPremiumCost TMCI target maximum cost of cover when the asset is not considered risky (Premium) ///@param _lowRiskMaxPercentPremiumCost100Utilization MCI not risky ///@param _highRiskMaxPercentPremiumCost TMCI target maximum cost of cover when the asset is considered risky (Premium) ///@param _highRiskMaxPercentPremiumCost100Utilization MCI risky function setupPricingModel( uint256 _riskyAssetThresholdPercentage, uint256 _minimumCostPercentage, uint256 _minimumInsuranceCost, uint256 _lowRiskMaxPercentPremiumCost, uint256 _lowRiskMaxPercentPremiumCost100Utilization, uint256 _highRiskMaxPercentPremiumCost, uint256 _highRiskMaxPercentPremiumCost100Utilization ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; import "./IClaimingRegistry.sol"; import "./IPolicyBookFacade.sol"; interface IPolicyBook { enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED} struct PolicyHolder { uint256 coverTokens; uint256 startEpochNumber; uint256 endEpochNumber; uint256 paid; uint256 reinsurancePrice; } struct WithdrawalInfo { uint256 withdrawalAmount; uint256 readyToWithdrawDate; bool withdrawalAllowed; } struct BuyPolicyParameters { address buyer; address holder; uint256 epochsNumber; uint256 coverTokens; uint256 distributorFee; address distributor; } function policyHolders(address _holder) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function policyBookFacade() external view returns (IPolicyBookFacade); function setPolicyBookFacade(address _policyBookFacade) external; function EPOCH_DURATION() external view returns (uint256); function stblDecimals() external view returns (uint256); function READY_TO_WITHDRAW_PERIOD() external view returns (uint256); function whitelisted() external view returns (bool); function epochStartTime() external view returns (uint256); // @TODO: should we let DAO to change contract address? /// @notice Returns address of contract this PolicyBook covers, access: ANY /// @return _contract is address of covered contract function insuranceContractAddress() external view returns (address _contract); /// @notice Returns type of contract this PolicyBook covers, access: ANY /// @return _type is type of contract function contractType() external view returns (IPolicyBookFabric.ContractType _type); function totalLiquidity() external view returns (uint256); function totalCoverTokens() external view returns (uint256); // /// @notice return MPL for user leverage pool // function userleveragedMPL() external view returns (uint256); // /// @notice return MPL for reinsurance pool // function reinsurancePoolMPL() external view returns (uint256); // function bmiRewardMultiplier() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns ( uint256 _withdrawalAmount, uint256 _readyToWithdrawDate, bool _withdrawalAllowed ); function __PolicyBook_init( address _insuranceContract, IPolicyBookFabric.ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external; function whitelist(bool _whitelisted) external; function getEpoch(uint256 time) external view returns (uint256); /// @notice get STBL equivalent function convertBMIXToSTBL(uint256 _amount) external view returns (uint256); /// @notice get BMIX equivalent function convertSTBLToBMIX(uint256 _amount) external view returns (uint256); /// @notice submits new claim of the policy book function submitClaimAndInitializeVoting(string calldata evidenceURI) external; /// @notice submits new appeal claim of the policy book function submitAppealAndInitializeVoting(string calldata evidenceURI) external; /// @notice updates info on claim acceptance function commitClaim( address claimer, uint256 claimAmount, uint256 claimEndTime, IClaimingRegistry.ClaimStatus status ) external; /// @notice forces an update of RewardsGenerator multiplier function forceUpdateBMICoverStakingRewardMultiplier() external; /// @notice function to get precise current cover and liquidity function getNewCoverAndLiquidity() external view returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity); /// @notice view function to get precise policy price /// @param _epochsNumber is number of epochs to cover /// @param _coverTokens is number of tokens to cover /// @param _buyer address of the user who buy the policy /// @return totalSeconds is number of seconds to cover /// @return totalPrice is the policy price which will pay by the buyer function getPolicyPrice( uint256 _epochsNumber, uint256 _coverTokens, address _buyer ) external view returns ( uint256 totalSeconds, uint256 totalPrice, uint256 pricePercentage ); /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _buyer who is transferring funds /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicy( address _buyer, address _holder, uint256 _epochsNumber, uint256 _coverTokens, uint256 _distributorFee, address _distributor ) external returns (uint256, uint256); function updateEpochsInfo() external; function secondsToEndCurrentEpoch() external view returns (uint256); /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin /// @param _liquidityHolderAddr is address of address to assign cover /// @param _liqudityAmount is amount of stable coin tokens to secure function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityBuyerAddr address the one that transfer funds /// @param _liquidityHolderAddr address the one that owns liquidity /// @param _liquidityAmount uint256 amount to be added on behalf the sender /// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake function addLiquidity( address _liquidityBuyerAddr, address _liquidityHolderAddr, uint256 _liquidityAmount, uint256 _stakeSTBLAmount ) external returns (uint256); function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256); function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus); function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external; // function requestWithdrawalWithPermit( // uint256 _tokensToWithdraw, // uint8 _v, // bytes32 _r, // bytes32 _s // ) external; function unlockTokens() external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity(address sender) external returns (uint256); ///@notice for doing defi hard rebalancing, access: policyBookFacade function updateLiquidity(uint256 _newLiquidity) external; function getAPY() external view returns (uint256); /// @notice Getting user stats, access: ANY function userStats(address _user) external view returns (PolicyHolder memory); /// @notice Getting number stats, access: ANY /// @return _maxCapacities is a max token amount that a user can buy /// @return _totalSTBLLiquidity is PolicyBook's liquidity /// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity /// @return _stakedSTBL is how much stable coin are staked on this PolicyBook /// @return _annualProfitYields is its APY /// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance function numberStats() external view returns ( uint256 _maxCapacities, uint256 _totalSTBLLiquidity, uint256 _totalLeveragedLiquidity, uint256 _stakedSTBL, uint256 _annualProfitYields, uint256 _annualInsuranceCost, uint256 _bmiXRatio ); /// @notice Getting info, access: ANY /// @return _symbol is the symbol of PolicyBook (bmiXCover) /// @return _insuredContract is an addres of insured contract /// @return _contractType is a type of insured contract /// @return _whitelisted is a state of whitelisting function info() external view returns ( string memory _symbol, address _insuredContract, IPolicyBookFabric.ContractType _contractType, bool _whitelisted ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface ILiquidityRegistry { struct LiquidityInfo { address policyBookAddr; uint256 lockedAmount; uint256 availableAmount; uint256 bmiXRatio; // multiply availableAmount by this num to get stable coin } struct WithdrawalRequestInfo { address policyBookAddr; uint256 requestAmount; uint256 requestSTBLAmount; uint256 availableLiquidity; uint256 readyToWithdrawDate; uint256 endWithdrawDate; } struct WithdrawalSetInfo { address policyBookAddr; uint256 requestAmount; uint256 requestSTBLAmount; uint256 availableSTBLAmount; } function tryToAddPolicyBook(address _userAddr, address _policyBookAddr) external; function tryToRemovePolicyBook(address _userAddr, address _policyBookAddr) external; function getPolicyBooksArrLength(address _userAddr) external view returns (uint256); function getPolicyBooksArr(address _userAddr) external view returns (address[] memory _resultArr); function getLiquidityInfos( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (LiquidityInfo[] memory _resultArr); function getWithdrawalRequests( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (uint256 _arrLength, WithdrawalRequestInfo[] memory _resultArr); function getWithdrawalSet( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (uint256 _arrLength, WithdrawalSetInfo[] memory _resultArr); function registerWithdrawl(address _policyBook, address _users) external; function getAllPendingWithdrawalRequestsAmount() external returns (uint256 _totalWithdrawlAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface ILeveragePortfolio { enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL} struct LevFundsFactors { uint256 netMPL; uint256 netMPLn; address policyBookAddr; // uint256 poolTotalLiquidity; // uint256 poolUR; // uint256 minUR; } function targetUR() external view returns (uint256); function d_ProtocolConstant() external view returns (uint256); function a_ProtocolConstant() external view returns (uint256); function max_ProtocolConstant() external view returns (uint256); /// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook. /// @param leveragePoolType LeveragePortfolio is determine the pool which call the function function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType) external returns (uint256); /// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook. function deployVirtualStableToCoveragePools() external returns (uint256); /// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner /// @param threshold uint256 is the reevaluatation threshold function setRebalancingThreshold(uint256 threshold) external; /// @notice set the protocol constant : access by owner /// @param _targetUR uint256 target utitlization ration /// @param _d_ProtocolConstant uint256 D protocol constant /// @param _a_ProtocolConstant uint256 A protocol constant /// @param _max_ProtocolConstant uint256 the max % included function setProtocolConstant( uint256 _targetUR, uint256 _d_ProtocolConstant, uint256 _a_ProtocolConstant, uint256 _max_ProtocolConstant ) external; /// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max) /// @param poolUR uint256 utitilization ratio for a coverage pool /// @return uint256 M facotr //function calcM(uint256 poolUR) external returns (uint256); /// @return uint256 the amount of vStable stored in the pool function totalLiquidity() external view returns (uint256); /// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook /// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook /// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for /// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external; /// @notice Used to get a list of coverage pools which get leveraged , use with count() /// @return _coveragePools a list containing policybook addresses function listleveragedCoveragePools(uint256 offset, uint256 limit) external view returns (address[] memory _coveragePools); /// @notice get count of coverage pools which get leveraged function countleveragedCoveragePools() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IContractsRegistry { function getUniswapRouterContract() external view returns (address); function getUniswapBMIToETHPairContract() external view returns (address); function getUniswapBMIToUSDTPairContract() external view returns (address); function getSushiswapRouterContract() external view returns (address); function getSushiswapBMIToETHPairContract() external view returns (address); function getSushiswapBMIToUSDTPairContract() external view returns (address); function getSushiSwapMasterChefV2Contract() external view returns (address); function getWETHContract() external view returns (address); function getUSDTContract() external view returns (address); function getBMIContract() external view returns (address); function getPriceFeedContract() external view returns (address); function getPolicyBookRegistryContract() external view returns (address); function getPolicyBookFabricContract() external view returns (address); function getBMICoverStakingContract() external view returns (address); function getBMICoverStakingViewContract() external view returns (address); function getLegacyRewardsGeneratorContract() external view returns (address); function getRewardsGeneratorContract() external view returns (address); function getBMIUtilityNFTContract() external view returns (address); function getNFTStakingContract() external view returns (address); function getLiquidityMiningContract() external view returns (address); function getClaimingRegistryContract() external view returns (address); function getPolicyRegistryContract() external view returns (address); function getLiquidityRegistryContract() external view returns (address); function getClaimVotingContract() external view returns (address); function getReinsurancePoolContract() external view returns (address); function getLeveragePortfolioViewContract() external view returns (address); function getCapitalPoolContract() external view returns (address); function getPolicyBookAdminContract() external view returns (address); function getPolicyQuoteContract() external view returns (address); function getLegacyBMIStakingContract() external view returns (address); function getBMIStakingContract() external view returns (address); function getSTKBMIContract() external view returns (address); function getVBMIContract() external view returns (address); function getLegacyLiquidityMiningStakingContract() external view returns (address); function getLiquidityMiningStakingETHContract() external view returns (address); function getLiquidityMiningStakingUSDTContract() external view returns (address); function getReputationSystemContract() external view returns (address); function getAaveProtocolContract() external view returns (address); function getAaveLendPoolAddressProvdierContract() external view returns (address); function getAaveATokenContract() external view returns (address); function getCompoundProtocolContract() external view returns (address); function getCompoundCTokenContract() external view returns (address); function getCompoundComptrollerContract() external view returns (address); function getYearnProtocolContract() external view returns (address); function getYearnVaultContract() external view returns (address); function getYieldGeneratorContract() external view returns (address); function getShieldMiningContract() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IClaimingRegistry { enum ClaimStatus { CAN_CLAIM, UNCLAIMABLE, PENDING, AWAITING_CALCULATION, REJECTED_CAN_APPEAL, REJECTED, ACCEPTED } struct ClaimInfo { address claimer; address policyBookAddress; string evidenceURI; uint256 dateSubmitted; uint256 dateEnded; bool appeal; ClaimStatus status; uint256 claimAmount; } /// @notice returns anonymous voting duration function anonymousVotingDuration(uint256 index) external view returns (uint256); /// @notice returns the whole voting duration function votingDuration(uint256 index) external view returns (uint256); /// @notice returns how many time should pass before anyone could calculate a claim result function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256); /// @notice returns true if a user can buy new policy of specified PolicyBook function canBuyNewPolicy(address buyer, address policyBookAddress) external view returns (bool); /// @notice submits new PolicyBook claim for the user function submitClaim( address user, address policyBookAddress, string calldata evidenceURI, uint256 cover, bool appeal ) external returns (uint256); /// @notice returns true if the claim with this index exists function claimExists(uint256 index) external view returns (bool); /// @notice returns claim submition time function claimSubmittedTime(uint256 index) external view returns (uint256); /// @notice returns claim end time or zero in case it is pending function claimEndTime(uint256 index) external view returns (uint256); /// @notice returns true if the claim is anonymously votable function isClaimAnonymouslyVotable(uint256 index) external view returns (bool); /// @notice returns true if the claim is exposably votable function isClaimExposablyVotable(uint256 index) external view returns (bool); /// @notice returns true if claim is anonymously votable or exposably votable function isClaimVotable(uint256 index) external view returns (bool); /// @notice returns true if a claim can be calculated by anyone function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool); /// @notice returns true if this claim is pending or awaiting function isClaimPending(uint256 index) external view returns (bool); /// @notice returns how many claims the holder has function countPolicyClaimerClaims(address user) external view returns (uint256); /// @notice returns how many pending claims are there function countPendingClaims() external view returns (uint256); /// @notice returns how many claims are there function countClaims() external view returns (uint256); /// @notice returns a claim index of it's claimer and an ordinal number function claimOfOwnerIndexAt(address claimer, uint256 orderIndex) external view returns (uint256); /// @notice returns pending claim index by its ordinal index function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns claim index by its ordinal index function claimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns current active claim index by policybook and claimer function claimIndex(address claimer, address policyBookAddress) external view returns (uint256); /// @notice returns true if the claim is appealed function isClaimAppeal(uint256 index) external view returns (bool); /// @notice returns current status of a claim function policyStatus(address claimer, address policyBookAddress) external view returns (ClaimStatus); /// @notice returns current status of a claim function claimStatus(uint256 index) external view returns (ClaimStatus); /// @notice returns the claim owner (claimer) function claimOwner(uint256 index) external view returns (address); /// @notice returns the claim PolicyBook function claimPolicyBook(uint256 index) external view returns (address); /// @notice returns claim info by its index function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo); function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount); function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256); /// @notice marks the user's claim as Accepted function acceptClaim(uint256 index) external; /// @notice marks the user's claim as Rejected function rejectClaim(uint256 index) external; /// @notice Update Image Uri in case it contains material that is ilegal /// or offensive. /// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri. /// @param _claimIndex Claim Index that is going to be updated /// @param _newEvidenceURI New evidence uri. It can be blank. function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "../interfaces/IContractsRegistry.sol"; abstract contract AbstractDependant { /// @dev keccak256(AbstractDependant.setInjector(address)) - 1 bytes32 private constant _INJECTOR_SLOT = 0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76; modifier onlyInjectorOrZero() { address _injector = injector(); require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector"); _; } function setInjector(address _injector) external onlyInjectorOrZero { bytes32 slot = _INJECTOR_SLOT; assembly { sstore(slot, _injector) } } /// @dev has to apply onlyInjectorOrZero() modifier function setDependencies(IContractsRegistry) external virtual; function injector() public view returns (address _injector) { bytes32 slot = _INJECTOR_SLOT; assembly { _injector := sload(slot) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds uint256 constant DAYS_IN_THE_YEAR = 365; uint256 constant MAX_INT = type(uint256).max; uint256 constant DECIMALS18 = 10**18; uint256 constant PRECISION = 10**25; uint256 constant PERCENTAGE_100 = 100 * PRECISION; uint256 constant BLOCKS_PER_DAY = 6450; uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365; uint256 constant APY_TOKENS = DECIMALS18; uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION; uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23; uint256 constant REBALANCE_DURATION = 1 days; uint256 constant EPOCH_DAYS_AMOUNT = 7;
365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60;
234,928
[ 1, 5718, 25, 4681, 225, 4248, 7507, 225, 4752, 6824, 225, 4752, 3974, 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, 11890, 5034, 5381, 17209, 67, 706, 67, 24644, 67, 15137, 273, 21382, 380, 4248, 380, 4752, 380, 4752, 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 ]
// SPDX-License-Identifier: APACHE 2.0 pragma solidity >=0.8.0 <0.9.0; /** * @dev IOpenSearch is about searching fields to identify addresses of interest. */ interface IOpenSearch { function searchField(string memory _term, string memory _field, uint256 _resultLimit) view external returns(address[] memory _results); function searchField(uint256 _value, string memory _comparator, string memory _field, uint256 _resultLimit) view external returns (address[] memory _results); function generalSearch(string memory _term) view external returns (address [] memory _results); function addSearchableAddress(address _address, string memory _field, string[] memory _values) external returns (bool _added); function addSearchableAddress(address _address, string memory _field, uint256 [] memory _values) external returns (bool _added); function addGeneralSearchTermsForAddress(address _address, string [] memory _terms) external returns (uint256 _termsAddedCount); function removeSearchableAddress(address _address) external returns (bool _removed); }
* @dev IOpenSearch is about searching fields to identify addresses of interest./
interface IOpenSearch { function searchField(string memory _term, string memory _field, uint256 _resultLimit) view external returns(address[] memory _results); function searchField(uint256 _value, string memory _comparator, string memory _field, uint256 _resultLimit) view external returns (address[] memory _results); function generalSearch(string memory _term) view external returns (address [] memory _results); function addSearchableAddress(address _address, string memory _field, string[] memory _values) external returns (bool _added); function addSearchableAddress(address _address, string memory _field, uint256 [] memory _values) external returns (bool _added); function addGeneralSearchTermsForAddress(address _address, string [] memory _terms) external returns (uint256 _termsAddedCount); function removeSearchableAddress(address _address) external returns (bool _removed); }
2,482,541
[ 1, 45, 3678, 2979, 353, 2973, 15300, 1466, 358, 9786, 6138, 434, 16513, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 1665, 1907, 2979, 288, 203, 203, 565, 445, 1623, 974, 12, 1080, 3778, 389, 6408, 16, 533, 3778, 389, 1518, 16, 2254, 5034, 389, 2088, 3039, 13, 1476, 3903, 1135, 12, 2867, 8526, 3778, 389, 4717, 1769, 203, 203, 565, 445, 1623, 974, 12, 11890, 5034, 389, 1132, 16, 533, 3778, 389, 832, 2528, 16, 533, 3778, 389, 1518, 16, 2254, 5034, 389, 2088, 3039, 13, 1476, 3903, 1135, 261, 2867, 8526, 3778, 389, 4717, 1769, 203, 203, 565, 445, 7470, 2979, 12, 1080, 3778, 389, 6408, 13, 1476, 3903, 1135, 261, 2867, 5378, 3778, 389, 4717, 1769, 203, 203, 565, 445, 527, 2979, 429, 1887, 12, 2867, 389, 2867, 16, 533, 3778, 389, 1518, 16, 533, 8526, 3778, 389, 2372, 13, 3903, 1135, 261, 6430, 389, 9665, 1769, 203, 203, 565, 445, 527, 2979, 429, 1887, 12, 2867, 389, 2867, 16, 533, 3778, 389, 1518, 16, 2254, 5034, 5378, 3778, 389, 2372, 13, 3903, 1135, 261, 6430, 389, 9665, 1769, 203, 377, 203, 565, 445, 527, 12580, 2979, 11673, 1290, 1887, 12, 2867, 389, 2867, 16, 533, 5378, 3778, 389, 10112, 13, 3903, 1135, 261, 11890, 5034, 389, 10112, 8602, 1380, 1769, 203, 203, 565, 445, 1206, 2979, 429, 1887, 12, 2867, 389, 2867, 13, 3903, 1135, 261, 6430, 389, 14923, 1769, 203, 203, 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 ]
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 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; } } /** * @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() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "Invalid owner"); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract EyeToken is ERC20, Ownable { using SafeMath for uint256; struct Frozen { bool frozen; uint until; } string public name = "EyeCoin"; string public symbol = "EYE"; uint8 public decimals = 18; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; mapping(address => Frozen) public frozenAccounts; uint256 internal totalSupplyTokens; bool internal isICO; address public wallet; function EyeToken() public Ownable() { wallet = msg.sender; isICO = true; totalSupplyTokens = 10000000000 * 10 ** uint256(decimals); balances[wallet] = totalSupplyTokens; } /** * @dev Finalize ICO */ function finalizeICO() public onlyOwner { isICO = false; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupplyTokens; } /** * @dev Freeze account, make transfers from this account unavailable * @param _account Given account */ function freeze(address _account) public onlyOwner { freeze(_account, 0); } /** * @dev Temporary freeze account, make transfers from this account unavailable for a time * @param _account Given account * @param _until Time until */ function freeze(address _account, uint _until) public onlyOwner { if (_until == 0 || (_until != 0 && _until > now)) { frozenAccounts[_account] = Frozen(true, _until); } } /** * @dev Unfreeze account, make transfers from this account available * @param _account Given account */ function unfreeze(address _account) public onlyOwner { if (frozenAccounts[_account].frozen) { delete frozenAccounts[_account]; } } /** * @dev allow transfer tokens or not * @param _from The address to transfer from. */ modifier allowTransfer(address _from) { assert(!isICO); if (frozenAccounts[_from].frozen) { require(frozenAccounts[_from].until != 0 && frozenAccounts[_from].until < now, "Frozen account"); delete frozenAccounts[_from]; } _; } /** * @dev transfer tokens 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) { bool result = _transfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return result; } /** * @dev transfer tokens for a specified address in ICO mode * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferICO(address _to, uint256 _value) public onlyOwner returns (bool) { assert(isICO); require(_to != address(0), "Zero address 'To'"); require(_value <= balances[wallet], "Not enought balance"); balances[wallet] = balances[wallet].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(wallet, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @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 allowTransfer(_from) returns (bool) { require(_value <= allowed[_from][msg.sender], "Not enought allowance"); bool result = _transfer(_from, _to, _value); if (result) { allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); } return result; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev transfer token for a specified address * @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 allowTransfer(_from) returns (bool) { require(_to != address(0), "Zero address 'To'"); require(_from != address(0), "Zero address 'From'"); require(_value <= balances[_from], "Not enought balance"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); return true; } } /** * @title Crowd-sale * * @dev Crowd-sale contract for tokens */ contract CrowdSale is Ownable { using SafeMath for uint256; event Payment( address wallet, uint date, uint256 amountEth, uint256 amountCoin, uint8 bonusPercent ); uint constant internal MIN_TOKEN_AMOUNT = 5000; uint constant internal SECONDS_IN_DAY = 86400; // 24 * 60 * 60 uint constant internal SECONDS_IN_YEAR = 31557600; // ( 365 * 24 + 6 ) * 60 * 60 int8 constant internal PHASE_NOT_STARTED = -5; int8 constant internal PHASE_BEFORE_PRESALE = -4; int8 constant internal PHASE_BETWEEN_PRESALE_ICO = -3; int8 constant internal PHASE_ICO_FINISHED = -2; int8 constant internal PHASE_FINISHED = -1; int8 constant internal PHASE_PRESALE = 0; int8 constant internal PHASE_ICO_1 = 1; int8 constant internal PHASE_ICO_2 = 2; int8 constant internal PHASE_ICO_3 = 3; int8 constant internal PHASE_ICO_4 = 4; int8 constant internal PHASE_ICO_5 = 5; address internal manager; EyeToken internal token; address internal base_wallet; uint256 internal dec_mul; address internal vest_1; address internal vest_2; address internal vest_3; address internal vest_4; int8 internal phase_i; // see PHASE_XXX uint internal presale_start = 1533020400; // 2018-07-31 07:00 UTC uint internal presale_end = 1534316400; // 2018-08-15 07:00 UTC uint internal ico_start = 1537254000; // 2018-09-18 07:00 UTC uint internal ico_phase_1_days = 7; uint internal ico_phase_2_days = 7; uint internal ico_phase_3_days = 7; uint internal ico_phase_4_days = 7; uint internal ico_phase_5_days = 7; uint internal ico_phase_1_end; uint internal ico_phase_2_end; uint internal ico_phase_3_end; uint internal ico_phase_4_end; uint internal ico_phase_5_end; uint8[6] public bonus_percents = [50, 40, 30, 20, 10, 0]; uint internal finish_date; uint public exchange_rate; // tokens in one ethereum * 1000 uint256 public lastPayerOverflow = 0; /** * @dev Crowd-sale constructor */ function CrowdSale() Ownable() public { phase_i = PHASE_NOT_STARTED; manager = address(0); } /** * @dev Allow only for owner or manager */ modifier onlyOwnerOrManager(){ require(msg.sender == owner || (msg.sender == manager && manager != address(0)), "Invalid owner or manager"); _; } /** * @dev Returns current manager */ function getManager() public view onlyOwnerOrManager returns (address) { return manager; } /** * @dev Sets new manager * @param _manager New manager */ function setManager(address _manager) public onlyOwner { manager = _manager; } /** * @dev Set exchange rate * @param _rate New exchange rate * * executed by CRM */ function setRate(uint _rate) public onlyOwnerOrManager { require(_rate > 0, "Invalid exchange rate"); exchange_rate = _rate; } function _addPayment(address wallet, uint256 amountEth, uint256 amountCoin, uint8 bonusPercent) internal { emit Payment(wallet, now, amountEth, amountCoin, bonusPercent); } /** * @dev Start crowd-sale * @param _token Coin's contract * @param _rate current exchange rate */ function start(address _token, uint256 _rate) public onlyOwnerOrManager { require(_rate > 0, "Invalid exchange rate"); assert(phase_i == PHASE_NOT_STARTED); token = EyeToken(_token); base_wallet = token.wallet(); dec_mul = 10 ** uint256(token.decimals()); // Organizasional expenses address org_exp = 0x45709fcBeb5D133bFA336d8c70FFFF98eE815359; // Early birds address ear_brd = 0xE640b346E1d9A1eb3F809608a8a92f041D02F3BE; // Community development address com_dev = 0xdC2c6398F7a9cF2CbdCfEcB37CF732f486642316; // Special coins address special = 0x1dBcDb11c6C05a4EA541227fBdEeB02d6492BD07; // Team lock vest_1 = 0xC49d11a05aF6D5BDeBfd18E0010516D9840f3610; vest_2 = 0x7Fd486029C8D81f4894e4ef0D460c2bD97187aeF; vest_3 = 0xcCcC86e1086015AEE865165f6f93a82dE591Cb3C; vest_4 = 0xd7569317e6af13D4d3832613F930cc5b7cecaE6e; token.transferICO(org_exp, 600000000 * dec_mul); token.transferICO(ear_brd, 1000000000 * dec_mul); token.transferICO(com_dev, 1000000000 * dec_mul); token.transferICO(special, 800000000 * dec_mul); token.transferICO(vest_1, 500000000 * dec_mul); token.transferICO(vest_2, 500000000 * dec_mul); token.transferICO(vest_3, 500000000 * dec_mul); token.transferICO(vest_4, 500000000 * dec_mul); exchange_rate = _rate; phase_i = PHASE_BEFORE_PRESALE; _updatePhaseTimes(); } /** * @dev Finalize ICO */ function _finalizeICO() internal { assert(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED); phase_i = PHASE_ICO_FINISHED; uint curr_date = now; finish_date = (curr_date < ico_phase_5_end ? ico_phase_5_end : curr_date).add(SECONDS_IN_DAY * 10); } /** * @dev Finalize crowd-sale */ function _finalize() internal { assert(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED); uint date = now.add(SECONDS_IN_YEAR); token.freeze(vest_1, date); date = date.add(SECONDS_IN_YEAR); token.freeze(vest_2, date); date = date.add(SECONDS_IN_YEAR); token.freeze(vest_3, date); date = date.add(SECONDS_IN_YEAR); token.freeze(vest_4, date); token.finalizeICO(); token.transferOwnership(base_wallet); phase_i = PHASE_FINISHED; } /** * @dev Finalize crowd-sale */ function finalize() public onlyOwner { _finalize(); } function _calcPhase() internal view returns (int8) { if (phase_i == PHASE_FINISHED || phase_i == PHASE_NOT_STARTED) return phase_i; uint curr_date = now; if (curr_date >= ico_phase_5_end || token.balanceOf(base_wallet) == 0) return PHASE_ICO_FINISHED; if (curr_date < presale_start) return PHASE_BEFORE_PRESALE; if (curr_date <= presale_end) return PHASE_PRESALE; if (curr_date < ico_start) return PHASE_BETWEEN_PRESALE_ICO; if (curr_date < ico_phase_1_end) return PHASE_ICO_1; if (curr_date < ico_phase_2_end) return PHASE_ICO_2; if (curr_date < ico_phase_3_end) return PHASE_ICO_3; if (curr_date < ico_phase_4_end) return PHASE_ICO_4; return PHASE_ICO_5; } function phase() public view returns (int8) { return _calcPhase(); } /** * @dev Recalculate phase */ function _updatePhase(bool check_can_sale) internal { uint curr_date = now; if (phase_i == PHASE_ICO_FINISHED) { if (curr_date >= finish_date) _finalize(); } else if (phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED) { int8 new_phase = _calcPhase(); if (new_phase == PHASE_ICO_FINISHED && phase_i != PHASE_ICO_FINISHED) _finalizeICO(); else phase_i = new_phase; } if (check_can_sale) assert(phase_i >= 0); } /** * @dev Update phase end times */ function _updatePhaseTimes() internal { assert(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED); if (phase_i < PHASE_ICO_1) ico_phase_1_end = ico_start.add(SECONDS_IN_DAY.mul(ico_phase_1_days)); if (phase_i < PHASE_ICO_2) ico_phase_2_end = ico_phase_1_end.add(SECONDS_IN_DAY.mul(ico_phase_2_days)); if (phase_i < PHASE_ICO_3) ico_phase_3_end = ico_phase_2_end.add(SECONDS_IN_DAY.mul(ico_phase_3_days)); if (phase_i < PHASE_ICO_4) ico_phase_4_end = ico_phase_3_end.add(SECONDS_IN_DAY.mul(ico_phase_4_days)); if (phase_i < PHASE_ICO_5) ico_phase_5_end = ico_phase_4_end.add(SECONDS_IN_DAY.mul(ico_phase_5_days)); if (phase_i != PHASE_ICO_FINISHED) finish_date = ico_phase_5_end.add(SECONDS_IN_DAY.mul(10)); _updatePhase(false); } /** * @dev Send tokens to the specified address * * @param _to Address sent to * @param _amount_coin Amount of tockens * @return excess coins * * executed by CRM */ function transferICO(address _to, uint256 _amount_coin) public onlyOwnerOrManager { _updatePhase(true); uint256 remainedCoin = token.balanceOf(base_wallet); require(remainedCoin >= _amount_coin, "Not enough coins"); token.transferICO(_to, _amount_coin); if (remainedCoin == _amount_coin) _finalizeICO(); } /** * @dev Default contract function. Buy tokens by sending ethereums */ function() public payable { _updatePhase(true); address sender = msg.sender; uint256 amountEth = msg.value; uint256 remainedCoin = token.balanceOf(base_wallet); if (remainedCoin == 0) { sender.transfer(amountEth); _finalizeICO(); } else { uint8 percent = bonus_percents[uint256(phase_i)]; uint256 amountCoin = calcTokensFromEth(amountEth); assert(amountCoin >= MIN_TOKEN_AMOUNT); if (amountCoin > remainedCoin) { lastPayerOverflow = amountCoin.sub(remainedCoin); amountCoin = remainedCoin; } base_wallet.transfer(amountEth); token.transferICO(sender, amountCoin); _addPayment(sender, amountEth, amountCoin, percent); if (amountCoin == remainedCoin) _finalizeICO(); } } function calcTokensFromEth(uint256 ethAmount) internal view returns (uint256) { uint8 percent = bonus_percents[uint256(phase_i)]; uint256 bonusRate = uint256(percent).add(100); uint256 totalCoins = ethAmount.mul(exchange_rate).div(1000); uint256 totalFullCoins = (totalCoins.add(dec_mul.div(2))).div(dec_mul); uint256 tokensWithBonusX100 = bonusRate.mul(totalFullCoins); uint256 fullCoins = (tokensWithBonusX100.add(50)).div(100); return fullCoins.mul(dec_mul); } /** * @dev Freeze the account * @param _accounts Given accounts * * executed by CRM */ function freeze(address[] _accounts) public onlyOwnerOrManager { assert(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED); uint i; for (i = 0; i < _accounts.length; i++) { require(_accounts[i] != address(0), "Zero address"); require(_accounts[i] != base_wallet, "Freeze self"); } for (i = 0; i < _accounts.length; i++) { token.freeze(_accounts[i]); } } /** * @dev Unfreeze the account * @param _accounts Given accounts */ function unfreeze(address[] _accounts) public onlyOwnerOrManager { assert(phase_i != PHASE_NOT_STARTED && phase_i != PHASE_FINISHED); uint i; for (i = 0; i < _accounts.length; i++) { require(_accounts[i] != address(0), "Zero address"); require(_accounts[i] != base_wallet, "Freeze self"); } for (i = 0; i < _accounts.length; i++) { token.unfreeze(_accounts[i]); } } /** * @dev get ICO times * @return presale_start, presale_end, ico_start, ico_phase_1_end, ico_phase_2_end, ico_phase_3_end, ico_phase_4_end, ico_phase_5_end */ function getTimes() public view returns (uint, uint, uint, uint, uint, uint, uint, uint) { return (presale_start, presale_end, ico_start, ico_phase_1_end, ico_phase_2_end, ico_phase_3_end, ico_phase_4_end, ico_phase_5_end); } /** * @dev Sets start and end dates for pre-sale phase_i * @param _presale_start Pre-sale sart date * @param _presale_end Pre-sale end date */ function setPresaleDates(uint _presale_start, uint _presale_end) public onlyOwnerOrManager { _updatePhase(false); assert(phase_i == PHASE_BEFORE_PRESALE); // require(_presale_start >= now); require(_presale_start < _presale_end); require(_presale_end < ico_start); presale_start = _presale_start; presale_end = _presale_end; } /** * @dev Sets start date for ICO phases * @param _ico_start ICO start date * @param _ico_1_days Days of ICO phase 1 * @param _ico_2_days Days of ICO phase 2 * @param _ico_3_days Days of ICO phase 3 * @param _ico_4_days Days of ICO phase 4 * @param _ico_5_days Days of ICO phase 5 */ function setICODates(uint _ico_start, uint _ico_1_days, uint _ico_2_days, uint _ico_3_days, uint _ico_4_days, uint _ico_5_days) public onlyOwnerOrManager { _updatePhase(false); assert(phase_i != PHASE_FINISHED && phase_i != PHASE_ICO_FINISHED && phase_i < PHASE_ICO_1); require(presale_end < _ico_start); ico_start = _ico_start; ico_phase_1_days = _ico_1_days; ico_phase_2_days = _ico_2_days; ico_phase_3_days = _ico_3_days; ico_phase_4_days = _ico_4_days; ico_phase_5_days = _ico_5_days; _updatePhaseTimes(); } }
* @dev Sets start date for ICO phases @param _ico_start ICO start date @param _ico_1_days Days of ICO phase 1 @param _ico_2_days Days of ICO phase 2 @param _ico_3_days Days of ICO phase 3 @param _ico_4_days Days of ICO phase 4 @param _ico_5_days Days of ICO phase 5/
function setICODates(uint _ico_start, uint _ico_1_days, uint _ico_2_days, uint _ico_3_days, uint _ico_4_days, uint _ico_5_days) public onlyOwnerOrManager { _updatePhase(false); assert(phase_i != PHASE_FINISHED && phase_i != PHASE_ICO_FINISHED && phase_i < PHASE_ICO_1); require(presale_end < _ico_start); ico_start = _ico_start; ico_phase_1_days = _ico_1_days; ico_phase_2_days = _ico_2_days; ico_phase_3_days = _ico_3_days; ico_phase_4_days = _ico_4_days; ico_phase_5_days = _ico_5_days; _updatePhaseTimes(); }
10,117,375
[ 1, 2785, 787, 1509, 364, 467, 3865, 24642, 225, 389, 10764, 67, 1937, 467, 3865, 787, 1509, 225, 389, 10764, 67, 21, 67, 9810, 463, 8271, 434, 467, 3865, 6855, 404, 225, 389, 10764, 67, 22, 67, 9810, 463, 8271, 434, 467, 3865, 6855, 576, 225, 389, 10764, 67, 23, 67, 9810, 463, 8271, 434, 467, 3865, 6855, 890, 225, 389, 10764, 67, 24, 67, 9810, 463, 8271, 434, 467, 3865, 6855, 1059, 225, 389, 10764, 67, 25, 67, 9810, 463, 8271, 434, 467, 3865, 6855, 1381, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 444, 2871, 1212, 815, 12, 11890, 389, 10764, 67, 1937, 16, 2254, 389, 10764, 67, 21, 67, 9810, 16, 2254, 389, 10764, 67, 22, 67, 9810, 16, 2254, 389, 10764, 67, 23, 67, 9810, 16, 2254, 389, 10764, 67, 24, 67, 9810, 16, 2254, 389, 10764, 67, 25, 67, 9810, 13, 1071, 1338, 5541, 1162, 1318, 288, 203, 3639, 389, 2725, 11406, 12, 5743, 1769, 203, 3639, 1815, 12, 13961, 67, 77, 480, 15490, 4429, 67, 23259, 2056, 597, 6855, 67, 77, 480, 15490, 4429, 67, 2871, 51, 67, 23259, 2056, 597, 6855, 67, 77, 411, 15490, 4429, 67, 2871, 51, 67, 21, 1769, 203, 3639, 2583, 12, 12202, 5349, 67, 409, 411, 389, 10764, 67, 1937, 1769, 203, 3639, 277, 2894, 67, 1937, 273, 389, 10764, 67, 1937, 31, 203, 3639, 277, 2894, 67, 13961, 67, 21, 67, 9810, 273, 389, 10764, 67, 21, 67, 9810, 31, 203, 3639, 277, 2894, 67, 13961, 67, 22, 67, 9810, 273, 389, 10764, 67, 22, 67, 9810, 31, 203, 3639, 277, 2894, 67, 13961, 67, 23, 67, 9810, 273, 389, 10764, 67, 23, 67, 9810, 31, 203, 3639, 277, 2894, 67, 13961, 67, 24, 67, 9810, 273, 389, 10764, 67, 24, 67, 9810, 31, 203, 3639, 277, 2894, 67, 13961, 67, 25, 67, 9810, 273, 389, 10764, 67, 25, 67, 9810, 31, 203, 3639, 389, 2725, 11406, 10694, 5621, 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 ]
./partial_match/1/0x15e72822d258D98a82E10f666E0b54796E5195A1/sources/SAFEMARS.sol
* @dev Initializes the contract setting the deployer as the initial owner./
constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); }
3,539,440
[ 1, 9685, 326, 6835, 3637, 326, 7286, 264, 487, 326, 2172, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 288, 203, 3639, 1758, 1234, 12021, 273, 389, 3576, 12021, 5621, 203, 3639, 389, 8443, 273, 1234, 12021, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 1234, 12021, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x3231Cb76718CDeF2155FC47b5286d82e6eDA273f/sources/EUR.sol
* @dev Transfers tokens and subsequently calls a method on the recipient [ERC677]. If the recipient is a non-contract address this method behaves just like transfer. @param caller Address of the caller passed through the frontend. @param to Recipient address. @param amount Number of tokens to transfer. @param data Additional data passed to the recipient's tokenFallback method./
function transferAndCall_withCaller( address caller, address to, uint256 amount, bytes data ) public guarded(caller) whenNotPaused returns (bool ok) { avoidBlackholes(to); return token.transferAndCall(caller, to, amount, data); }
3,732,594
[ 1, 1429, 18881, 2430, 471, 10815, 715, 4097, 279, 707, 603, 326, 8027, 306, 654, 39, 26, 4700, 8009, 971, 326, 8027, 353, 279, 1661, 17, 16351, 1758, 333, 707, 12433, 6606, 2537, 3007, 7412, 18, 225, 4894, 5267, 434, 326, 4894, 2275, 3059, 326, 15442, 18, 225, 358, 23550, 1758, 18, 225, 3844, 3588, 434, 2430, 358, 7412, 18, 225, 501, 15119, 501, 2275, 358, 326, 8027, 1807, 1147, 12355, 707, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7412, 1876, 1477, 67, 1918, 11095, 12, 203, 3639, 1758, 4894, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 501, 203, 565, 262, 203, 3639, 1071, 203, 3639, 3058, 17212, 12, 16140, 13, 203, 3639, 1347, 1248, 28590, 203, 3639, 1135, 261, 6430, 1529, 13, 203, 565, 288, 203, 3639, 4543, 13155, 76, 9112, 12, 869, 1769, 203, 3639, 327, 1147, 18, 13866, 1876, 1477, 12, 16140, 16, 358, 16, 3844, 16, 501, 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 ]
// SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../lib/ABDKMath64x64.sol"; import "../interfaces/IAssimilator.sol"; import "../interfaces/IOracle.sol"; contract XsgdToUsdAssimilator is IAssimilator { using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; using SafeMath for uint256; IOracle private constant oracle = IOracle(0xe25277fF4bbF9081C75Ab0EB13B4A13a721f3E13); IERC20 private constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 private constant xsgd = IERC20(0x70e8dE73cE538DA2bEEd35d14187F6959a8ecA96); uint256 private constant DECIMALS = 1e6; function getRate() public view override returns (uint256) { (, int256 price, , , ) = oracle.latestRoundData(); return uint256(price); } // takes raw xsgd amount, transfers it in, calculates corresponding numeraire amount and returns it function intakeRawAndGetBalance(uint256 _amount) external override returns (int128 amount_, int128 balance_) { bool _transferSuccess = xsgd.transferFrom(msg.sender, address(this), _amount); require(_transferSuccess, "Curve/XSGD-transfer-from-failed"); uint256 _balance = xsgd.balanceOf(address(this)); uint256 _rate = getRate(); balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS); amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS); } // takes raw xsgd amount, transfers it in, calculates corresponding numeraire amount and returns it function intakeRaw(uint256 _amount) external override returns (int128 amount_) { bool _transferSuccess = xsgd.transferFrom(msg.sender, address(this), _amount); require(_transferSuccess, "Curve/XSGD-transfer-from-failed"); uint256 _rate = getRate(); amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS); } // takes a numeraire amount, calculates the raw amount of xsgd, transfers it in and returns the corresponding raw amount function intakeNumeraire(int128 _amount) external override returns (uint256 amount_) { uint256 _rate = getRate(); amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate; bool _transferSuccess = xsgd.transferFrom(msg.sender, address(this), amount_); require(_transferSuccess, "Curve/XSGD-transfer-from-failed"); } // takes a numeraire amount, calculates the raw amount of xsgd, transfers it in and returns the corresponding raw amount function intakeNumeraireLPRatio( uint256 _baseWeight, uint256 _quoteWeight, address _addr, int128 _amount ) external override returns (uint256 amount_) { uint256 _xsgdBal = xsgd.balanceOf(_addr); if (_xsgdBal <= 0) return 0; // DECIMALS _xsgdBal = _xsgdBal.mul(1e18).div(_baseWeight); // DECIMALS uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight); // Rate is in DECIMALS uint256 _rate = _usdcBal.mul(DECIMALS).div(_xsgdBal); amount_ = (_amount.mulu(DECIMALS) * DECIMALS) / _rate; bool _transferSuccess = xsgd.transferFrom(msg.sender, address(this), amount_); require(_transferSuccess, "Curve/XSGD-transfer-failed"); } // takes a raw amount of xsgd and transfers it out, returns numeraire value of the raw amount function outputRawAndGetBalance(address _dst, uint256 _amount) external override returns (int128 amount_, int128 balance_) { uint256 _rate = getRate(); uint256 _xsgdAmount = ((_amount) * _rate) / 1e8; bool _transferSuccess = xsgd.transfer(_dst, _xsgdAmount); require(_transferSuccess, "Curve/XSGD-transfer-failed"); uint256 _balance = xsgd.balanceOf(address(this)); amount_ = _xsgdAmount.divu(DECIMALS); balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS); } // takes a raw amount of xsgd and transfers it out, returns numeraire value of the raw amount function outputRaw(address _dst, uint256 _amount) external override returns (int128 amount_) { uint256 _rate = getRate(); uint256 _xsgdAmount = (_amount * _rate) / 1e8; bool _transferSuccess = xsgd.transfer(_dst, _xsgdAmount); require(_transferSuccess, "Curve/XSGD-transfer-failed"); amount_ = _xsgdAmount.divu(DECIMALS); } // takes a numeraire value of xsgd, figures out the raw amount, transfers raw amount out, and returns raw amount function outputNumeraire(address _dst, int128 _amount) external override returns (uint256 amount_) { uint256 _rate = getRate(); amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate; bool _transferSuccess = xsgd.transfer(_dst, amount_); require(_transferSuccess, "Curve/XSGD-transfer-failed"); } // takes a numeraire amount and returns the raw amount function viewRawAmount(int128 _amount) external view override returns (uint256 amount_) { uint256 _rate = getRate(); amount_ = (_amount.mulu(DECIMALS) * 1e8) / _rate; } function viewRawAmountLPRatio( uint256 _baseWeight, uint256 _quoteWeight, address _addr, int128 _amount ) external view override returns (uint256 amount_) { uint256 _xsgdBal = xsgd.balanceOf(_addr); if (_xsgdBal <= 0) return 0; // DECIMALS _xsgdBal = _xsgdBal.mul(1e18).div(_baseWeight); // DECIMALS uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight); // Rate is in DECIMALS uint256 _rate = _usdcBal.mul(DECIMALS).div(_xsgdBal); amount_ = (_amount.mulu(DECIMALS) * DECIMALS) / _rate; } // takes a raw amount and returns the numeraire amount function viewNumeraireAmount(uint256 _amount) external view override returns (int128 amount_) { uint256 _rate = getRate(); amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS); } // views the numeraire value of the current balance of the reserve, in this case xsgd function viewNumeraireBalance(address _addr) external view override returns (int128 balance_) { uint256 _rate = getRate(); uint256 _balance = xsgd.balanceOf(_addr); if (_balance <= 0) return ABDKMath64x64.fromUInt(0); balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS); } // views the numeraire value of the current balance of the reserve, in this case xsgd function viewNumeraireAmountAndBalance(address _addr, uint256 _amount) external view override returns (int128 amount_, int128 balance_) { uint256 _rate = getRate(); amount_ = ((_amount * _rate) / 1e8).divu(DECIMALS); uint256 _balance = xsgd.balanceOf(_addr); balance_ = ((_balance * _rate) / 1e8).divu(DECIMALS); } // views the numeraire value of the current balance of the reserve, in this case xsgd // instead of calculating with chainlink's "rate" it'll be determined by the existing // token ratio // Mainly to protect LP from losing function viewNumeraireBalanceLPRatio( uint256 _baseWeight, uint256 _quoteWeight, address _addr ) external view override returns (int128 balance_) { uint256 _xsgdBal = xsgd.balanceOf(_addr); if (_xsgdBal <= 0) return ABDKMath64x64.fromUInt(0); uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight); // Rate is in DECIMALS uint256 _rate = _usdcBal.mul(1e18).div(_xsgdBal.mul(1e18).div(_baseWeight)); balance_ = ((_xsgdBal * _rate) / DECIMALS).divu(1e18); } } // 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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.7.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (63 - (x >> 64)); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256 (xe); else x <<= uint256 (-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= uint256 (re); else if (re < 0) result >>= uint256 (-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; interface IAssimilator { function getRate() external view returns (uint256); function intakeRaw(uint256 amount) external returns (int128); function intakeRawAndGetBalance(uint256 amount) external returns (int128, int128); function intakeNumeraire(int128 amount) external returns (uint256); function intakeNumeraireLPRatio( uint256, uint256, address, int128 ) external returns (uint256); function outputRaw(address dst, uint256 amount) external returns (int128); function outputRawAndGetBalance(address dst, uint256 amount) external returns (int128, int128); function outputNumeraire(address dst, int128 amount) external returns (uint256); function viewRawAmount(int128) external view returns (uint256); function viewRawAmountLPRatio( uint256, uint256, address, int128 ) external view returns (uint256); function viewNumeraireAmount(uint256) external view returns (int128); function viewNumeraireBalanceLPRatio( uint256, uint256, address ) external view returns (int128); function viewNumeraireBalance(address) external view returns (int128); function viewNumeraireAmountAndBalance(address, uint256) external view returns (int128, int128); } // SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.3; interface IOracle { function acceptOwnership() external; function accessController() external view returns (address); function aggregator() external view returns (address); function confirmAggregator(address _aggregator) external; function decimals() external view returns (uint8); function description() external view returns (string memory); function getAnswer(uint256 _roundId) external view returns (int256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getTimestamp(uint256 _roundId) external view returns (uint256); function latestAnswer() external view returns (int256); function latestRound() external view returns (uint256); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestTimestamp() external view returns (uint256); function owner() external view returns (address); function phaseAggregators(uint16) external view returns (address); function phaseId() external view returns (uint16); function proposeAggregator(address _aggregator) external; function proposedAggregator() external view returns (address); function proposedGetRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function proposedLatestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function setController(address _accessController) external; function transferOwnership(address _to) external; function version() external view returns (uint256); }
views the numeraire value of the current balance of the reserve, in this case xsgd instead of calculating with chainlink's "rate" it'll be determined by the existing token ratio Mainly to protect LP from losing Rate is in DECIMALS
function viewNumeraireBalanceLPRatio( uint256 _baseWeight, uint256 _quoteWeight, address _addr ) external view override returns (int128 balance_) { uint256 _xsgdBal = xsgd.balanceOf(_addr); if (_xsgdBal <= 0) return ABDKMath64x64.fromUInt(0); uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight); uint256 _rate = _usdcBal.mul(1e18).div(_xsgdBal.mul(1e18).div(_baseWeight)); balance_ = ((_xsgdBal * _rate) / DECIMALS).divu(1e18); }
6,322,768
[ 1, 7061, 326, 818, 6070, 577, 460, 434, 326, 783, 11013, 434, 326, 20501, 16, 316, 333, 648, 619, 1055, 72, 3560, 434, 21046, 598, 2687, 1232, 1807, 315, 5141, 6, 518, 5614, 506, 11383, 635, 326, 2062, 1147, 7169, 12740, 715, 358, 17151, 511, 52, 628, 437, 2470, 13025, 353, 316, 25429, 55, 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, 1476, 2578, 6070, 577, 13937, 48, 8025, 4197, 12, 203, 3639, 2254, 5034, 389, 1969, 6544, 16, 203, 3639, 2254, 5034, 389, 6889, 6544, 16, 203, 3639, 1758, 389, 4793, 203, 565, 262, 3903, 1476, 3849, 1135, 261, 474, 10392, 11013, 67, 13, 288, 203, 3639, 2254, 5034, 389, 92, 1055, 72, 38, 287, 273, 619, 1055, 72, 18, 12296, 951, 24899, 4793, 1769, 203, 203, 3639, 309, 261, 67, 92, 1055, 72, 38, 287, 1648, 374, 13, 327, 10336, 3398, 10477, 1105, 92, 1105, 18, 2080, 14342, 12, 20, 1769, 203, 203, 3639, 2254, 5034, 389, 407, 7201, 38, 287, 273, 584, 7201, 18, 12296, 951, 24899, 4793, 2934, 16411, 12, 21, 73, 2643, 2934, 2892, 24899, 6889, 6544, 1769, 203, 203, 3639, 2254, 5034, 389, 5141, 273, 389, 407, 7201, 38, 287, 18, 16411, 12, 21, 73, 2643, 2934, 2892, 24899, 92, 1055, 72, 38, 287, 18, 16411, 12, 21, 73, 2643, 2934, 2892, 24899, 1969, 6544, 10019, 203, 203, 3639, 11013, 67, 273, 14015, 67, 92, 1055, 72, 38, 287, 380, 389, 5141, 13, 342, 25429, 55, 2934, 2892, 89, 12, 21, 73, 2643, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; contract Etherwow{ function userRollDice(uint, address) payable {uint;address;} } /** * @title FixBet16 * @dev fix bet num = 16, bet size = 0.5 eth. */ contract FixBet16{ modifier onlyOwner{ require(msg.sender == owner); _; } address public owner; Etherwow public etherwow; bool public bet; /* * @dev contract initialize * @param new etherwow address */ function FixBet16(){ owner = msg.sender; } /* * @dev owner set etherwow contract address * @param new etherwow address */ function ownerSetEtherwowAddress(address newEtherwowAddress) public onlyOwner { etherwow = Etherwow(newEtherwowAddress); } /* * @dev owner set fallback function mode * @param new fallback function mode. true - bet, false - add funds to contract */ function ownerSetMod(bool newMod) public onlyOwner { bet = newMod; } /* * @dev add funds or bet. if bet == false, add funds to this contract for cover the txn gas fee */ function () payable{ if (bet == true){ require(msg.value == 500000000000000000); etherwow.userRollDice.value(msg.value)(16, msg.sender); } else return; } }
@dev add funds or bet. if bet == false, add funds to this contract for cover the txn gas fee/
function () payable{ if (bet == true){ require(msg.value == 500000000000000000); etherwow.userRollDice.value(msg.value)(16, msg.sender); } else return; }
12,187,505
[ 1, 1289, 284, 19156, 578, 2701, 18, 309, 2701, 422, 629, 16, 527, 284, 19156, 358, 333, 6835, 364, 5590, 326, 7827, 16189, 14036, 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, 1832, 8843, 429, 95, 203, 3639, 309, 261, 70, 278, 422, 638, 15329, 203, 5411, 2583, 12, 3576, 18, 1132, 422, 1381, 12648, 2787, 11706, 1769, 203, 5411, 225, 2437, 91, 543, 18, 1355, 24194, 40, 1812, 18, 1132, 12, 3576, 18, 1132, 21433, 2313, 16, 1234, 18, 15330, 1769, 21281, 3639, 289, 203, 3639, 469, 327, 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 ]
./full_match/1/0xcAa9c61CC9F8F1774a01543FACeB9c3c263489c0/sources/contracts/vaults/Vault.sol
@notice Set total assets Emits a {TotalAssets} event. @param totalAssets_ New total assets value
function setTotalAssets(uint256 totalAssets_) external onlyRole(KEEPER_ROLE) { _totalAssets = totalAssets_; emit TotalAssets(totalAssets_); }
16,513,012
[ 1, 694, 2078, 7176, 7377, 1282, 279, 288, 5269, 10726, 97, 871, 18, 225, 2078, 10726, 67, 1166, 2078, 7176, 460, 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, 25015, 10726, 12, 11890, 5034, 2078, 10726, 67, 13, 203, 3639, 3903, 203, 3639, 1338, 2996, 12, 6859, 41, 3194, 67, 16256, 13, 203, 565, 288, 203, 3639, 389, 4963, 10726, 273, 2078, 10726, 67, 31, 203, 203, 3639, 3626, 10710, 10726, 12, 4963, 10726, 67, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @dev AMM that is designed for assets with stable price to each other e.g. USDC and USDT. * It utilizes constant sum price curve x + y = const but fee is variable depending on the token balances. * In most cases fee is equal to 1 bip. But when balances are at extreme ends it either lowers to 0 * or increases to 20 bip. * Fee calculations are explained in more details in `getReturn` method. * Note that AMM does not support token with fees. * Note that tokens decimals are required to be the same. */ contract FixedRateSwap is ERC20 { using SafeERC20 for IERC20; using SafeCast for uint256; event Swap( address indexed trader, int256 token0Amount, int256 token1Amount ); event Deposit( address indexed user, uint256 token0Amount, uint256 token1Amount, uint256 share ); event Withdrawal( address indexed user, uint256 token0Amount, uint256 token1Amount, uint256 share ); IERC20 immutable public token0; IERC20 immutable public token1; uint8 immutable private _decimals; uint256 constant private _ONE = 1e18; uint256 constant private _C1 = 0.9999e18; uint256 constant private _C2 = 3.382712334998325432e18; uint256 constant private _C3 = 0.456807350974663119e18; uint256 constant private _THRESHOLD = 1; uint256 constant private _LOWER_BOUND_NUMERATOR = 998; uint256 constant private _UPPER_BOUND_NUMERATOR = 1002; uint256 constant private _DENOMINATOR = 1000; constructor( IERC20 _token0, IERC20 _token1, string memory name, string memory symbol, uint8 decimals_ ) ERC20(name, symbol) { token0 = _token0; token1 = _token1; _decimals = decimals_; require(IERC20Metadata(address(_token0)).decimals() == decimals_, "token0 decimals mismatch"); require(IERC20Metadata(address(_token1)).decimals() == decimals_, "token1 decimals mismatch"); } function decimals() public view override returns(uint8) { return _decimals; } /** * @notice estimates return value of the swap * @param tokenFrom token that user wants to sell * @param tokenTo token that user wants to buy * @param inputAmount amount of `tokenFrom` that user wants to sell * @return outputAmount amount of `tokenTo` that user will receive after the trade * * @dev * `getReturn` at point `x = inputBalance / (inputBalance + outputBalance)`: * `getReturn(x) = 0.9999 + (0.5817091329374359 - x * 1.2734233188154198)^17` * When balance is changed from `inputBalance` to `inputBalance + amount` we should take * integral of getReturn to calculate proper amount: * `getReturn(x0, x1) = (integral (0.9999 + (0.5817091329374359 - x * 1.2734233188154198)^17) dx from x=x0 to x=x1) / (x1 - x0)` * `getReturn(x0, x1) = (0.9999 * x - 3.3827123349983306 * (x - 0.4568073509746632) ** 18 from x=x0 to x=x1) / (x1 - x0)` * `getReturn(x0, x1) = (0.9999 * (x1 - x0) + 3.3827123349983306 * ((x0 - 0.4568073509746632) ** 18 - (x1 - 0.4568073509746632) ** 18)) / (x1 - x0)` * C0 = 0.9999 * C2 = 3.3827123349983306 * C3 = 0.4568073509746632 * `getReturn(x0, x1) = (C0 * (x1 - x0) + C2 * ((x0 - C3) ** 18 - (x1 - C3) ** 18)) / (x1 - x0)` */ function getReturn(IERC20 tokenFrom, IERC20 tokenTo, uint256 inputAmount) public view returns(uint256 outputAmount) { require(inputAmount > 0, "Input amount should be > 0"); uint256 fromBalance = tokenFrom.balanceOf(address(this)); uint256 toBalance = tokenTo.balanceOf(address(this)); // require is needed to be sure that _getReturn math won't overflow require(inputAmount <= toBalance, "Input amount is too big"); outputAmount = _getReturn(fromBalance, toBalance, inputAmount); } /** * @notice makes a deposit of both tokens to the AMM * @param token0Amount amount of token0 to deposit * @param token1Amount amount of token1 to deposit * @param minShare minimal required amount of LP tokens received * @return share amount of LP tokens received */ function deposit(uint256 token0Amount, uint256 token1Amount, uint256 minShare) external returns(uint256 share) { share = depositFor(token0Amount, token1Amount, msg.sender, minShare); } /** * @notice makes a deposit of both tokens to the AMM and transfers LP tokens to the specified address * @param token0Amount amount of token0 to deposit * @param token1Amount amount of token1 to deposit * @param to address that will receive tokens * @param minShare minimal required amount of LP tokens received * @return share amount of LP tokens received * * @dev fully balanced deposit happens when ratio of amounts of deposit matches ratio of balances. * To make a fair deposit when ratios do not match the contract finds the amount that is needed to swap to * equalize ratios and makes that swap virtually to capture the swap fees. Then final share is calculated from * fair deposit of virtual amounts. */ function depositFor(uint256 token0Amount, uint256 token1Amount, address to, uint256 minShare) public returns(uint256 share) { uint256 token0Balance = token0.balanceOf(address(this)); uint256 token1Balance = token1.balanceOf(address(this)); (uint256 token0VirtualAmount, uint256 token1VirtualAmount) = _getVirtualAmountsForDeposit(token0Amount, token1Amount, token0Balance, token1Balance); uint256 inputAmount = token0VirtualAmount + token1VirtualAmount; require(inputAmount > 0, "Empty deposit is not allowed"); require(to != address(this), "Deposit to this is forbidden"); // _mint also checks require(to != address(0)) uint256 _totalSupply = totalSupply(); if (_totalSupply > 0) { uint256 totalBalance = token0Balance + token1Balance + token0Amount + token1Amount - inputAmount; share = inputAmount * _totalSupply / totalBalance; } else { share = inputAmount; } require(share >= minShare, "Share is not enough"); _mint(to, share); emit Deposit(to, token0Amount, token1Amount, share); if (token0Amount > 0) { token0.safeTransferFrom(msg.sender, address(this), token0Amount); } if (token1Amount > 0) { token1.safeTransferFrom(msg.sender, address(this), token1Amount); } } /** * @notice makes a proportional withdrawal of both tokens * @param amount amount of LP tokens to burn * @param minToken0Amount minimal required amount of token0 * @param minToken1Amount minimal required amount of token1 * @return token0Amount amount of token0 received * @return token1Amount amount of token1 received */ function withdraw(uint256 amount, uint256 minToken0Amount, uint256 minToken1Amount) external returns(uint256 token0Amount, uint256 token1Amount) { (token0Amount, token1Amount) = withdrawFor(amount, msg.sender, minToken0Amount, minToken1Amount); } /** * @notice makes a proportional withdrawal of both tokens and transfers them to the specified address * @param amount amount of LP tokens to burn * @param to address that will receive tokens * @param minToken0Amount minimal required amount of token0 * @param minToken1Amount minimal required amount of token1 * @return token0Amount amount of token0 received * @return token1Amount amount of token1 received */ function withdrawFor(uint256 amount, address to, uint256 minToken0Amount, uint256 minToken1Amount) public returns(uint256 token0Amount, uint256 token1Amount) { require(amount > 0, "Empty withdrawal is not allowed"); require(to != address(this), "Withdrawal to this is forbidden"); require(to != address(0), "Withdrawal to zero is forbidden"); uint256 _totalSupply = totalSupply(); _burn(msg.sender, amount); token0Amount = token0.balanceOf(address(this)) * amount / _totalSupply; token1Amount = token1.balanceOf(address(this)) * amount / _totalSupply; _handleWithdraw(to, amount, token0Amount, token1Amount, minToken0Amount, minToken1Amount); } /** * @notice makes a withdrawal with custom ratio * @param amount amount of LP tokens to burn * @param token0Share percentage of token0 to receive with 100% equals to 1e18 * @param minToken0Amount minimal required amount of token0 * @param minToken1Amount minimal required amount of token1 * @return token0Amount amount of token0 received * @return token1Amount amount of token1 received */ function withdrawWithRatio(uint256 amount, uint256 token0Share, uint256 minToken0Amount, uint256 minToken1Amount) external returns(uint256 token0Amount, uint256 token1Amount) { return withdrawForWithRatio(amount, msg.sender, token0Share, minToken0Amount, minToken1Amount); } /** * @notice makes a withdrawal with custom ratio and transfers tokens to the specified address * @param amount amount of LP tokens to burn * @param to address that will receive tokens * @param token0Share percentage of token0 to receive with 100% equals to 1e18 * @param minToken0Amount minimal required amount of token0 * @param minToken1Amount minimal required amount of token1 * @return token0Amount amount of token0 received * @return token1Amount amount of token1 received * * @dev withdrawal with custom ratio is semantically equal to proportional withdrawal with extra swap afterwards to * get to the specified ratio. The contract does exactly this by making virtual proportional withdrawal and then * finds the amount needed for an extra virtual swap to achieve specified ratio. */ function withdrawForWithRatio(uint256 amount, address to, uint256 token0Share, uint256 minToken0Amount, uint256 minToken1Amount) public returns(uint256 token0Amount, uint256 token1Amount) { require(amount > 0, "Empty withdrawal is not allowed"); require(to != address(this), "Withdrawal to this is forbidden"); require(to != address(0), "Withdrawal to zero is forbidden"); require(token0Share <= _ONE, "Ratio should be in [0, 1]"); uint256 _totalSupply = totalSupply(); // burn happens before amounts calculations intentionally — to validate amount _burn(msg.sender, amount); (token0Amount, token1Amount) = _getRealAmountsForWithdraw(amount, token0Share, _totalSupply); _handleWithdraw(to, amount, token0Amount, token1Amount, minToken0Amount, minToken1Amount); } /** * @notice swaps token0 for token1 * @param inputAmount amount of token0 to sell * @param minReturnAmount minimal required amount of token1 to buy * @return outputAmount amount of token1 bought */ function swap0To1(uint256 inputAmount, uint256 minReturnAmount) external returns(uint256 outputAmount) { outputAmount = _swap(token0, token1, inputAmount, msg.sender, minReturnAmount); emit Swap(msg.sender, inputAmount.toInt256(), -outputAmount.toInt256()); } /** * @notice swaps token1 for token0 * @param inputAmount amount of token1 to sell * @param minReturnAmount minimal required amount of token0 to buy * @return outputAmount amount of token0 bought */ function swap1To0(uint256 inputAmount, uint256 minReturnAmount) external returns(uint256 outputAmount) { outputAmount = _swap(token1, token0, inputAmount, msg.sender, minReturnAmount); emit Swap(msg.sender, -outputAmount.toInt256(), inputAmount.toInt256()); } /** * @notice swaps token0 for token1 and transfers them to specified receiver address * @param inputAmount amount of token0 to sell * @param to address that will receive tokens * @param minReturnAmount minimal required amount of token1 to buy * @return outputAmount amount of token1 bought */ function swap0To1For(uint256 inputAmount, address to, uint256 minReturnAmount) external returns(uint256 outputAmount) { require(to != address(this), "Swap to this is forbidden"); require(to != address(0), "Swap to zero is forbidden"); outputAmount = _swap(token0, token1, inputAmount, to, minReturnAmount); emit Swap(msg.sender, inputAmount.toInt256(), -outputAmount.toInt256()); } /** * @notice swaps token1 for token0 and transfers them to specified receiver address * @param inputAmount amount of token1 to sell * @param to address that will receive tokens * @param minReturnAmount minimal required amount of token0 to buy * @return outputAmount amount of token0 bought */ function swap1To0For(uint256 inputAmount, address to, uint256 minReturnAmount) external returns(uint256 outputAmount) { require(to != address(this), "Swap to this is forbidden"); require(to != address(0), "Swap to zero is forbidden"); outputAmount = _swap(token1, token0, inputAmount, to, minReturnAmount); emit Swap(msg.sender, -outputAmount.toInt256(), inputAmount.toInt256()); } function _getVirtualAmountsForDeposit(uint256 token0Amount, uint256 token1Amount, uint256 token0Balance, uint256 token1Balance) private pure returns(uint256 token0VirtualAmount, uint256 token1VirtualAmount) { int256 shift = _checkVirtualAmountsFormula(token0Amount, token1Amount, token0Balance, token1Balance); if (shift > 0) { (token0VirtualAmount, token1VirtualAmount) = _getVirtualAmountsForDepositImpl(token0Amount, token1Amount, token0Balance, token1Balance); } else if (shift < 0) { (token1VirtualAmount, token0VirtualAmount) = _getVirtualAmountsForDepositImpl(token1Amount, token0Amount, token1Balance, token0Balance); } else { (token0VirtualAmount, token1VirtualAmount) = (token0Amount, token1Amount); } } function _getRealAmountsForWithdraw(uint256 amount, uint256 token0Share, uint256 _totalSupply) private view returns(uint256 token0RealAmount, uint256 token1RealAmount) { uint256 token0Balance = token0.balanceOf(address(this)); uint256 token1Balance = token1.balanceOf(address(this)); uint256 token0VirtualAmount = token0Balance * amount / _totalSupply; uint256 token1VirtualAmount = token1Balance * amount / _totalSupply; uint256 currentToken0Share = token0VirtualAmount * _ONE / (token0VirtualAmount + token1VirtualAmount); if (token0Share < currentToken0Share) { (token0RealAmount, token1RealAmount) = _getRealAmountsForWithdrawImpl(token0VirtualAmount, token1VirtualAmount, token0Balance - token0VirtualAmount, token1Balance - token1VirtualAmount, token0Share); } else if (token0Share > currentToken0Share) { (token1RealAmount, token0RealAmount) = _getRealAmountsForWithdrawImpl(token1VirtualAmount, token0VirtualAmount, token1Balance - token1VirtualAmount, token0Balance - token0VirtualAmount, _ONE - token0Share); } else { (token0RealAmount, token1RealAmount) = (token0VirtualAmount, token1VirtualAmount); } } function _getReturn(uint256 fromBalance, uint256 toBalance, uint256 inputAmount) private pure returns(uint256 outputAmount) { unchecked { uint256 totalBalance = fromBalance + toBalance; uint256 x0 = _ONE * fromBalance / totalBalance; uint256 x1 = _ONE * (fromBalance + inputAmount) / totalBalance; uint256 scaledInputAmount = _ONE * inputAmount; uint256 amountMultiplier = ( _C1 * scaledInputAmount / totalBalance + _C2 * _powerHelper(x0) - _C2 * _powerHelper(x1) ) * totalBalance / scaledInputAmount; outputAmount = inputAmount * Math.min(amountMultiplier, _ONE) / _ONE; } } function _handleWithdraw(address to, uint256 amount, uint256 token0Amount, uint256 token1Amount, uint256 minToken0Amount, uint256 minToken1Amount) private { require(token0Amount >= minToken0Amount, "Min token0Amount is not reached"); require(token1Amount >= minToken1Amount, "Min token1Amount is not reached"); emit Withdrawal(msg.sender, token0Amount, token1Amount, amount); if (token0Amount > 0) { token0.safeTransfer(to, token0Amount); } if (token1Amount > 0) { token1.safeTransfer(to, token1Amount); } } function _swap(IERC20 tokenFrom, IERC20 tokenTo, uint256 inputAmount, address to, uint256 minReturnAmount) private returns(uint256 outputAmount) { outputAmount = getReturn(tokenFrom, tokenTo, inputAmount); require(outputAmount > 0, "Empty swap is not allowed"); require(outputAmount >= minReturnAmount, "Min return not reached"); tokenFrom.safeTransferFrom(msg.sender, address(this), inputAmount); tokenTo.safeTransfer(to, outputAmount); } /** * @dev We utilize binary search to find proper to swap * * Inital approximation of dx is taken from the same equation by assuming dx ~ dy * * x - dx xBalance + dx * ------ = ------------ * y + dx yBalance - dx * * dx = (x * yBalance - xBalance * y) / (xBalance + yBalance + x + y) */ function _getVirtualAmountsForDepositImpl(uint256 x, uint256 y, uint256 xBalance, uint256 yBalance) private pure returns(uint256, uint256) { uint256 dx = (x * yBalance - y * xBalance) / (xBalance + yBalance + x + y); if (dx == 0) { return (x, y); } uint256 dy; uint256 left = dx * _LOWER_BOUND_NUMERATOR / _DENOMINATOR; uint256 right = Math.min(Math.min(dx * _UPPER_BOUND_NUMERATOR / _DENOMINATOR, yBalance), x); while (left + _THRESHOLD < right) { dy = _getReturn(xBalance, yBalance, dx); int256 shift = _checkVirtualAmountsFormula(x - dx, y + dy, xBalance + dx, yBalance - dy); if (shift > 0) { left = dx; dx = (dx + right) / 2; } else if (shift < 0) { right = dx; dx = (left + dx) / 2; } else { break; } } return (x - dx, y + dy); } /** * @dev We utilize binary search to find proper amount to swap * * Inital approximation of dx is taken from the same equation by assuming dx ~ dy * * x - dx firstTokenShare * ------ = ---------------------- * y + dx _ONE - firstTokenShare * * dx = (x * (_ONE - firstTokenShare) - y * firstTokenShare) / _ONE */ function _getRealAmountsForWithdrawImpl(uint256 virtualX, uint256 virtualY, uint256 balanceX, uint256 balanceY, uint256 firstTokenShare) private pure returns(uint256, uint256) { require(balanceX != 0 || balanceY != 0, "Amount exceeds total balance"); if (firstTokenShare == 0) { return (0, virtualY + _getReturn(balanceX, balanceY, virtualX)); } uint256 secondTokenShare = _ONE - firstTokenShare; uint256 dx = (virtualX * secondTokenShare - virtualY * firstTokenShare) / _ONE; uint256 dy; uint256 left = dx * _LOWER_BOUND_NUMERATOR / _DENOMINATOR; uint256 right = Math.min(dx * _UPPER_BOUND_NUMERATOR / _DENOMINATOR, virtualX); while (left + _THRESHOLD < right) { dy = _getReturn(balanceX, balanceY, dx); int256 shift = _checkVirtualAmountsFormula(virtualX - dx, virtualY + dy, firstTokenShare, secondTokenShare); if (shift > 0) { left = dx; dx = (dx + right) / 2; } else if (shift < 0) { right = dx; dx = (left + dx) / 2; } else { break; } } return (virtualX - dx, virtualY + dy); } /** * @dev * * Equilibrium is when ratio of amounts equals to ratio of balances * * x xBalance * --- == ---------- * y yBalance * */ function _checkVirtualAmountsFormula(uint256 x, uint256 y, uint256 xBalance, uint256 yBalance) private pure returns(int256) { unchecked { return int256(x * yBalance - y * xBalance); } } function _powerHelper(uint256 x) private pure returns(uint256 p) { unchecked { if (x > _C3) { p = x - _C3; } else { p = _C3 - x; } p = p * p / _ONE; // p ^ 2 uint256 pp = p * p / _ONE; // p ^ 4 pp = pp * pp / _ONE; // p ^ 8 pp = pp * pp / _ONE; // p ^ 16 p = p * pp / _ONE; // p ^ 18 } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.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 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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 `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 // OpenZeppelin Contracts v4.4.0 (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.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
* @notice swaps token1 for token0 and transfers them to specified receiver address @param inputAmount amount of token1 to sell @param to address that will receive tokens @param minReturnAmount minimal required amount of token0 to buy @return outputAmount amount of token0 bought/
function swap1To0For(uint256 inputAmount, address to, uint256 minReturnAmount) external returns(uint256 outputAmount) { require(to != address(this), "Swap to this is forbidden"); require(to != address(0), "Swap to zero is forbidden"); outputAmount = _swap(token1, token0, inputAmount, to, minReturnAmount); emit Swap(msg.sender, -outputAmount.toInt256(), inputAmount.toInt256()); }
7,229,282
[ 1, 5328, 6679, 1147, 21, 364, 1147, 20, 471, 29375, 2182, 358, 1269, 5971, 1758, 225, 810, 6275, 3844, 434, 1147, 21, 358, 357, 80, 225, 358, 1758, 716, 903, 6798, 2430, 225, 1131, 990, 6275, 16745, 1931, 3844, 434, 1147, 20, 358, 30143, 327, 876, 6275, 3844, 434, 1147, 20, 800, 9540, 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, 7720, 21, 774, 20, 1290, 12, 11890, 5034, 810, 6275, 16, 1758, 358, 16, 2254, 5034, 1131, 990, 6275, 13, 3903, 1135, 12, 11890, 5034, 876, 6275, 13, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 2211, 3631, 315, 12521, 358, 333, 353, 17987, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 12521, 358, 3634, 353, 17987, 8863, 203, 203, 3639, 876, 6275, 273, 389, 22270, 12, 2316, 21, 16, 1147, 20, 16, 810, 6275, 16, 358, 16, 1131, 990, 6275, 1769, 203, 3639, 3626, 12738, 12, 3576, 18, 15330, 16, 300, 2844, 6275, 18, 869, 1702, 5034, 9334, 810, 6275, 18, 869, 1702, 5034, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x7634991f5533A2D0a984F544c873B6E267D7234C/sources/flasLoan2.sol
Approval(msg.sender, guy, wad);
function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; return true; }
1,937,198
[ 1, 23461, 12, 3576, 18, 15330, 16, 3058, 93, 16, 341, 361, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6617, 537, 12, 2867, 3058, 93, 16, 2254, 341, 361, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 1699, 1359, 63, 3576, 18, 15330, 6362, 6891, 93, 65, 273, 341, 361, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastBytes32Bytes6.sol"; import "@yield-protocol/vault-interfaces/IOracle.sol"; import "./IYvToken.sol"; /** *@title YearnVaultMultiOracle *@notice Provides current values for Yearn Vault tokens (e.g. yvUSDC/USDC) *@dev Both peek() and get() are provided for convenience * Prices are calculated, never based on cached values */ contract YearnVaultMultiOracle is IOracle, AccessControl { using CastBytes32Bytes6 for bytes32; event SourceSet( bytes6 indexed baseId, bytes6 indexed quoteId, address indexed source, uint8 decimals ); struct Source { address source; uint8 decimals; bool inverse; } /** *@notice This is a registry of baseId => quoteId => Source * used to look up the Yearn vault address needed to calculate share price */ mapping(bytes6 => mapping(bytes6 => Source)) public sources; /** *@notice Set or reset a Yearn Vault Token oracle source and its inverse *@param vaultTokenId address for Yearn vault token *@param vaultToken address for Yearn vault token *@param underlyingId id used for underlying base token (e.g. USDC) *@dev parameter ORDER IS crucial! If id's are out of order the math will be wrong */ function setSource( bytes6 underlyingId, bytes6 vaultTokenId, IYvToken vaultToken ) external auth { uint8 decimals = vaultToken.decimals(); _setSource(vaultTokenId, underlyingId, vaultToken, decimals, false); _setSource(underlyingId, vaultTokenId, vaultToken, decimals, true); } /** *@notice internal function to set source and emit event *@param baseId id used for base token *@param quoteId id for quote (represents vaultToken when inverse == false) *@param source address for vault token used to determine price *@param decimals used by vault token (both source and base) *@param inverse set true for inverse pairs (e.g. USDC/yvUSDC) */ function _setSource( bytes6 baseId, bytes6 quoteId, IYvToken source, uint8 decimals, bool inverse ) internal { sources[baseId][quoteId] = Source({ source: address(source), decimals: decimals, inverse: inverse }); emit SourceSet(baseId, quoteId, address(source), decimals); } /** *@notice External function to convert amountBase base at the current vault share price *@dev This external function calls _peek() which calculates current (not cached) price *@param baseId id of base (denominator of rate used) *@param quoteId id of quote (returned amount in this) *@param amountBase amount in base to convert to amount in quote *@return amountQuote product of exchange rate and amountBase *@return updateTime current block timestamp */ function get( bytes32 baseId, bytes32 quoteId, uint256 amountBase ) external override returns (uint256 amountQuote, uint256 updateTime) { return _peek(baseId.b6(), quoteId.b6(), amountBase); } /** *@notice External function to convert amountBase at the current vault share price *@dev This function is exactly the same as get() and provided as a convenience * for contracts that need to call peek */ function peek( bytes32 baseId, bytes32 quoteId, uint256 amountBase ) external view override returns (uint256 amountQuote, uint256 updateTime) { return _peek(baseId.b6(), quoteId.b6(), amountBase); } /** *@notice Used to convert a given amount using the current vault share price *@dev This internal function is called by external functions peek() and get() *@param baseId id of base (denominator of rate used) *@param quoteId id of quote (returned amount converted to this) *@param amountBase amount in base to convert to amount in quote *@return amountQuote product of exchange rate and amountBase *@return updateTime current block timestamp */ function _peek( bytes6 baseId, bytes6 quoteId, uint256 amountBase ) internal view returns (uint256 amountQuote, uint256 updateTime) { updateTime = block.timestamp; if (baseId == quoteId) return (amountBase, updateTime); Source memory source = sources[baseId][quoteId]; require(source.source != address(0), "Source not found"); uint256 price = IYvToken(source.source).pricePerShare(); require(price != 0, "Zero price"); if (source.inverse == true) { // yvUSDC/USDC: 100 USDC (*10^6) * (10^6 / 1083121 USDC per yvUSDC) = 92325788 yvUSDC wei amountQuote = (amountBase * (10**source.decimals)) / price; } else { // USDC/yvUSDC: 100 yvUSDC (*10^6) * 1083121 USDC per yvUSDC / 10^6 = 108312100 USDC wei amountQuote = (amountBase * price) / (10**source.decimals); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "hardhat/console.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes4` identifier. These are expected to be the * signatures for all the functions in the contract. Special roles should be exposed * in the external API and be unique: * * ``` * bytes4 public constant ROOT = 0x00000000; * ``` * * Roles represent restricted access to a function call. For that purpose, use {auth}: * * ``` * function foo() public auth { * ... * } * ``` * * 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 `ROOT`, 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 `ROOT` 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. */ contract AccessControl { struct RoleData { mapping (address => bool) members; bytes4 adminRole; } mapping (bytes4 => RoleData) private _roles; bytes4 public constant ROOT = 0x00000000; bytes4 public constant ROOT4146650865 = 0x00000000; // Collision protection for ROOT, test with ROOT12007226833() bytes4 public constant LOCK = 0xFFFFFFFF; // Used to disable further permissioning of a function bytes4 public constant LOCK8605463013 = 0xFFFFFFFF; // Collision protection for LOCK, test with LOCK10462387368() /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role * * `ROOT` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call. */ event RoleGranted(bytes4 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(bytes4 indexed role, address indexed account, address indexed sender); /** * @dev Give msg.sender the ROOT role and create a LOCK role with itself as the admin role and no members. * Calling setRoleAdmin(msg.sig, LOCK) means no one can grant that msg.sig role anymore. */ constructor () { _grantRole(ROOT, msg.sender); // Grant ROOT to msg.sender _setRoleAdmin(LOCK, LOCK); // Create the LOCK role by setting itself as its own admin, creating an independent role tree } /** * @dev Each function in the contract has its own role, identified by their msg.sig signature. * ROOT can give and remove access to each function, lock any further access being granted to * a specific action, or even create other roles to delegate admin control over a function. */ modifier auth() { require (_hasRole(msg.sig, msg.sender), "Access denied"); _; } /** * @dev Allow only if the caller has been granted the admin role of `role`. */ modifier admin(bytes4 role) { require (_hasRole(_getRoleAdmin(role), msg.sender), "Only admin"); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes4 role, address account) external view returns (bool) { return _hasRole(role, account); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes4 role) external view returns (bytes4) { return _getRoleAdmin(role); } /** * @dev Sets `adminRole` as ``role``'s admin role. * If ``role``'s admin role is not `adminRole` emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) { _setRoleAdmin(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(bytes4 role, address account) external virtual admin(role) { _grantRole(role, account); } /** * @dev Grants all of `role` in `roles` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function grantRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _grantRole(roles[i], account); } } /** * @dev Sets LOCK as ``role``'s admin role. LOCK has no members, so this disables admin management of ``role``. * Emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function lockRole(bytes4 role) external virtual admin(role) { _setRoleAdmin(role, LOCK); } /** * @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(bytes4 role, address account) external virtual admin(role) { _revokeRole(role, account); } /** * @dev Revokes all of `role` in `roles` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function revokeRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _revokeRole(roles[i], account); } } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes4 role, address account) external virtual { require(account == msg.sender, "Renounce only for self"); _revokeRole(role, account); } function _hasRole(bytes4 role, address account) internal view returns (bool) { return _roles[role].members[account]; } function _getRoleAdmin(bytes4 role) internal view returns (bytes4) { return _roles[role].adminRole; } function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual { if (_getRoleAdmin(role) != adminRole) { _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, adminRole); } } function _grantRole(bytes4 role, address account) internal { if (!_hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, msg.sender); } } function _revokeRole(bytes4 role, address account) internal { if (_hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastBytes32Bytes6 { function b6(bytes32 x) internal pure returns (bytes6 y){ require (bytes32(y = bytes6(x)) == x, "Cast overflow"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IOracle { /** * @notice Doesn't refresh the price, but returns the latest value available without doing any transactional operations: * @return value in wei */ function peek(bytes32 base, bytes32 quote, uint256 amount) external view returns (uint256 value, uint256 updateTime); /** * @notice Does whatever work or queries will yield the most up-to-date price, and returns it. * @return value in wei */ function get(bytes32 base, bytes32 quote, uint256 amount) external returns (uint256 value, uint256 updateTime); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "@yield-protocol/utils-v2/contracts/token/IERC20Metadata.sol"; // @notice Interface for Yearn Vault tokens for use with Yield price oracles // @dev see https://github.com/yearn/yearn-vaults/blob/main/contracts/Vault.vy interface IYvToken is IERC20Metadata { // @notice Returns the price for a single Yearn Vault share. // @dev total vault assets / total token supply (calculated not cached) function pricePerShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT // Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; import "./IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 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); }
*@notice Set or reset a Yearn Vault Token oracle source and its inverse@param vaultTokenId address for Yearn vault token@param vaultToken address for Yearn vault token@param underlyingId id used for underlying base token (e.g. USDC)@dev parameter ORDER IS crucial! If id's are out of order the math will be wrong/
function setSource( bytes6 underlyingId, bytes6 vaultTokenId, IYvToken vaultToken ) external auth { uint8 decimals = vaultToken.decimals(); _setSource(vaultTokenId, underlyingId, vaultToken, decimals, false); _setSource(underlyingId, vaultTokenId, vaultToken, decimals, true); }
6,118,046
[ 1, 694, 578, 2715, 279, 1624, 73, 1303, 17329, 3155, 20865, 1084, 471, 2097, 8322, 225, 9229, 1345, 548, 1758, 364, 1624, 73, 1303, 9229, 1147, 225, 9229, 1345, 1758, 364, 1624, 73, 1303, 9229, 1147, 225, 6808, 548, 612, 1399, 364, 6808, 1026, 1147, 261, 73, 18, 75, 18, 11836, 5528, 13, 565, 1569, 10205, 4437, 4422, 5286, 649, 5, 225, 971, 612, 1807, 854, 596, 434, 1353, 326, 4233, 903, 506, 7194, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 18913, 12, 203, 3639, 1731, 26, 6808, 548, 16, 203, 3639, 1731, 26, 9229, 1345, 548, 16, 203, 3639, 467, 61, 90, 1345, 9229, 1345, 203, 565, 262, 3903, 1357, 288, 203, 3639, 2254, 28, 15105, 273, 9229, 1345, 18, 31734, 5621, 203, 203, 3639, 389, 542, 1830, 12, 26983, 1345, 548, 16, 6808, 548, 16, 9229, 1345, 16, 15105, 16, 629, 1769, 203, 3639, 389, 542, 1830, 12, 9341, 6291, 548, 16, 9229, 1345, 548, 16, 9229, 1345, 16, 15105, 16, 638, 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 ]
./full_match/4/0x5d756f47359fD500b646FBf690f104D10360102b/sources/jb3/ERC202.sol
withdraw funds from your account
function withdraw(uint amount) public returns (bool){
758,416
[ 1, 1918, 9446, 284, 19156, 628, 3433, 2236, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 3844, 13, 1071, 1135, 261, 6430, 15329, 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 ]
pragma solidity ^0.4.16; /** * Contract that handles initiatives and all the work around. * This contract holds a total balance which is distributed across the initiatives in determined * ways by this contract. */ contract Initiatives { struct Initiative { uint8 acceptance; // 1..100% (as 0..100) % of votes for this initiative to be accepted bytes20 contentHash; // SHA-1 hash of title and description of an initiative address initiator; // A guy who created this initiative address executor; // A person who completed the initiative and uploaded the evidence address[] backers; // Addresses which backed this initiative address[] voters; // Addresses which voted on this initiative mapping (address => uint) funds; // Amounts funded by backers mapping (address => bool) voted; // Whether the backer already voted mapping (address => bool) vote; // Backer's vote uint numberOfVotes; // A number of votes received so far after executor appears uint totalFunds; // Total funds received by the initiative bool closed; // Determines whether initiative is closed } uint lastInitiativeId = 0; mapping (uint => Initiative) public initiative; event InitiativeCreated(uint id); event InitiativeCompleted(bool success); /** * Return everything about initiative in one call. * @param id Initiative to return. */ function getInitiativeById (uint id) public view returns( address initiator, uint8 acceptance, bytes20 contentHash, address executor, address[] backers, uint totalFunds, bool closed, address[] voters, bool[] votes, uint[] funds ) { uint i; initiator = initiative[id].initiator; acceptance = initiative[id].acceptance; contentHash = initiative[id].contentHash; executor = initiative[id].executor; backers = initiative[id].backers; totalFunds = initiative[id].totalFunds; closed = initiative[id].closed; voters = new address[](initiative[id].numberOfVotes); votes = new bool[](initiative[id].numberOfVotes); funds = new uint[](initiative[id].backers.length); for (i = 0; i < initiative[id].numberOfVotes; ++i) { voters[i] = initiative[id].voters[i]; votes[i] = initiative[id].vote[voters[i]]; } for (i = 0; i < initiative[id].backers.length; ++i) { funds[i] = initiative[id].funds[initiative[id].backers[i]]; } } function getOpenedInitiativesIds () public view returns( uint[] openedInitiativesIds ) { uint i; uint opened = 0; for (i = 1; i <= lastInitiativeId; ++i) { if (initiative[i].closed == false) ++opened; } openedInitiativesIds = new uint[](opened); opened = 0; for (i = 1; i <= lastInitiativeId; ++i) { if (initiative[i].closed == false) { openedInitiativesIds[opened] = i; ++opened; } } } /** * @param contentHash Hash of the title/description. * @param acceptance Percentage of voters needed to accept the executor's work. * @return Created initiative ID. */ function create (bytes20 contentHash, uint8 acceptance) public returns(uint) { require(acceptance > 0 && acceptance <= 100); uint id = ++lastInitiativeId; initiative[id].initiator = msg.sender; initiative[id].acceptance = acceptance; initiative[id].contentHash = contentHash; InitiativeCreated(id); return id; } /** * Mark the initiative completed by the sender. * @param id Initiative to complete. */ function complete (uint id) public { require(initiative[id].initiator != address(0)); // initiative must exists require(initiative[id].totalFunds > 0); // cannot mark "empty" initiative as completed require(initiative[id].executor == address(0)); // cannot mark completed initiative again initiative[id].executor = msg.sender; } /** * Add funds to initiative. * @param id Initiative to back. */ function back (uint id) public payable { require(msg.value > 0); // backer should really transfer some value require(initiative[id].initiator != address(0)); // initiative must exists require(initiative[id].executor == address(0)); // cannot back executed initiative require(initiative[id].closed == false); // cannot back closed initiative if (initiative[id].funds[msg.sender] == 0) { // if backed for the first time initiative[id].backers.push(msg.sender); // add to the list of backers } initiative[id].funds[msg.sender] += msg.value; initiative[id].totalFunds += msg.value; } /** * Vote on executor's job. * @param id Initiative to vote on. * @param isPositive Determine whether the vote is positive. */ function vote (uint id, bool isPositive) public { Initiative storage ini = initiative[id]; require(initiative[id].initiator != address(0)); // initiative must exists require(ini.closed == false); // cannot vote on closed initiatives require(ini.executor != address(0)); // must vote only when executor is set require(ini.voted[msg.sender] == false); // cannot vote twice require(ini.funds[msg.sender] > 0); // must backed at least something to vote if (ini.numberOfVotes < ini.voters.length) { ini.voters[ini.numberOfVotes] = msg.sender; } else { ini.voters.push(msg.sender); } ini.numberOfVotes += 1; ini.voted[msg.sender] = true; ini.vote[msg.sender] = isPositive; onAfterVote(ini); } /** * Check whether given initiative has enough votes to be closed or reverted. */ function onAfterVote (Initiative storage ini) internal { uint positiveFunds = 0; uint negativeFunds = 0; for (uint i = 0; i < ini.numberOfVotes; ++i) { uint funds = ini.funds[ini.voters[i]]; if (ini.vote[ini.voters[i]]) { positiveFunds += funds; // add to positive score } else { negativeFunds += funds; } } if (100 * positiveFunds / ini.totalFunds >= ini.acceptance) { completeInitiative(ini, true); } else if (100 * negativeFunds / ini.totalFunds > 100 - ini.acceptance) { completeInitiative(ini, false); } else if (ini.numberOfVotes == ini.backers.length) { completeInitiative(ini, false); } } /** * Complete initiative and fund the executor or rollback it to a voting state. */ function completeInitiative (Initiative storage ini, bool success) internal { if (success) { ini.executor.transfer(ini.totalFunds); ini.closed = true; } else { for (uint i = 0; i < ini.numberOfVotes; ++i) { ini.voted[ini.voters[i]] = false; } ini.executor = address(0); ini.numberOfVotes = 0; } InitiativeCompleted(success); } }
cannot mark "empty" initiative as completed
require(initiative[id].totalFunds > 0);
1,792,389
[ 1, 12892, 2267, 315, 5531, 6, 1208, 77, 1535, 487, 5951, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 2738, 77, 1535, 63, 350, 8009, 4963, 42, 19156, 405, 374, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// // ___ ___ ________ ________ ___ ___ _________ ___ ___ ________ _______ // |\ \ / /|\ __ \|\ _____\\ \|\ \|\___ ___\\ \|\ \|\ __ \|\ ___ \ // \ \ \ / / | \ \|\ \ \ \__/\ \ \\\ \|___ \ \_\ \ \\\ \ \ \|\ \ \ __/| // \ \ \/ / / \ \ _ _\ \ __\\ \ \\\ \ \ \ \ \ \ \\\ \ \ _ _\ \ \_|/__ // \ \ / / \ \ \\ \\ \ \_| \ \ \\\ \ \ \ \ \ \ \\\ \ \ \\ \\ \ \_|\ \ // \ \__/ / \ \__\\ _\\ \__\ \ \_______\ \ \__\ \ \_______\ \__\\ _\\ \_______\ // \|__|/ \|__|\|__|\|__| \|_______| \|__| \|_______|\|__|\|__|\|_______| // // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "./ERC721A.sol"; contract VRFuture is ERC721A, Ownable { using Strings for uint256; mapping (address => uint256) private mintedWL; uint256 public maxSupply = 7777; uint256 private pricePublic = 0.07 ether; uint256 private priceWL = 0.07 ether; uint256 public maxPerTxPublic = 10; uint256 public maxPerWL = 10; bytes32 public merkleRoot = ""; string private baseURI = ""; string public provenance = ""; string public uriNotRevealed = ""; bool public paused = true; bool public isRevealed; bool private useWhitelist = true; event Minted(address caller); constructor() ERC721A("VRFuture", "VRF", maxPerTxPublic) { } function mintPublic(uint256 qty) external payable{ require(!paused, "Minting is paused"); require(useWhitelist == false, "Sorry, we are still on whitelist mode!"); uint256 supply = totalSupply(); require(supply + qty <= maxSupply, "Sorry, not enough left!"); require(qty <= maxPerTxPublic, "Sorry, too many per transaction"); require(msg.value >= pricePublic * qty, "Sorry, not enough amount sent!"); _safeMint(msg.sender, qty); emit Minted(msg.sender); } function mintGiveaway(address _to, uint256 qty) external onlyOwner{ uint256 supply = totalSupply(); require(supply + qty <= maxSupply, "Sorry, not enough left!"); _safeMint(_to, qty); } function mintWL(uint256 qty, bytes32[] memory proof) external payable { require(!paused, "Minting is paused"); require(useWhitelist, "Whitelist sale must be active to mint."); uint256 supply = totalSupply(); // check if the user was whitelisted bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(_verify(leaf, proof), "You are not whitelisted."); require(msg.value >= priceWL * qty, "Sorry, not enough amount sent!"); require(mintedWL[msg.sender] + qty <= maxPerWL, "Sorry, you have reached the WL limit."); require(supply + qty <= maxSupply, "Sorry, not enough left!"); mintedWL[msg.sender] += qty; _safeMint(msg.sender, qty); emit Minted(msg.sender); } function remaining() public view returns(uint256){ uint256 left = maxSupply - totalSupply(); return left; } function usingWhitelist() public view returns(bool) { return useWhitelist; } function getPriceWL() public view returns (uint256){ return priceWL; } function getPricePublic() public view returns (uint256){ return pricePublic; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (isRevealed == false) { return uriNotRevealed; } string memory base = baseURI; return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : ""; } // verify merkle tree leaf function _verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool){ return MerkleProof.verify(proof, merkleRoot, leaf); } // ADMIN FUNCTIONS function flipUseWhitelist() public onlyOwner { useWhitelist = !useWhitelist; } function flipPaused() public onlyOwner { paused = !paused; } // close minting forever! function closeMinting() public onlyOwner { uint256 supply = totalSupply(); maxSupply = supply; } function flipRevealed(string memory _URI) public onlyOwner { baseURI = _URI; isRevealed = !isRevealed; } function setMaxPerWL(uint256 _max) public onlyOwner { maxPerWL = _max; } function setBaseURI(string memory _URI) public onlyOwner { baseURI = _URI; } function setUriNotRevealed(string memory _URI) public onlyOwner { uriNotRevealed = _URI; } function setPriceWL(uint256 _newPrice) public onlyOwner { priceWL = _newPrice; } function setPricePublic(uint256 _newPrice) public onlyOwner { pricePublic = _newPrice; } function setMaxPerTx(uint256 _newMax) public onlyOwner { maxPerTxPublic = _newMax; } function setProvenanceHash(string memory _provenance) public onlyOwner { provenance = _provenance; } // Set merkle tree root function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; require(payable(0x14Eb25f15d71ECf2A0c4cf2670176D89EB83C905).send((balance * 1000) / 10000)); require(payable(0x6A642E5d347D1F6BDbd5ce7c7004D21D0e97921D).send((balance * 334) / 10000)); require(payable(0x3F88B98E1697B012a111A4d7783EdbF02ca8f238).send((balance * 333) / 10000)); require(payable(0x6308B9B2ac9827F57BE07B2bc8e1E32A9437dC45).send((balance * 333) / 10000)); require(payable(0xd79522Ea71e89BB88BE0c3D5bf7DAf18ED76FB58).send((balance * 500) / 10000)); require(payable(0xa09B9F27dE93e35952702edD8524617D9b467061).send((balance * 500) / 10000)); require(payable(0x558AdFbA73b26a235ff3cc0a906C9e88E9CD75eE).send((balance * 100) / 10000)); require(payable(0xC3b615216362aA20384D74B0dEB082c9a6f1ec20).send((balance * 200) / 10000)); require(payable(0xe6fEC433618adFc516A1270f994B09276ac1380E).send((balance * 6700) / 10000)); } // helpers // list all the tokens ids of a wallet function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } receive() external payable {} } // 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 (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 = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.9; 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"; /** * @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..). * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // 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) private _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; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @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) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), "ERC721A: number minted query for the zero address"); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @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) { 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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = 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 || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved"); require(prevOwnership.addr == from, "ERC721A: transfer from incorrect owner"); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, 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)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership(prevOwnership.addr, prevOwnership.startTimestamp); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership(ownership.addr, ownership.startTimestamp); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } 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. * * 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`. */ 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. * * 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` 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 (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 (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 v4.4.1 (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 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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); }
check if the user was whitelisted
function mintWL(uint256 qty, bytes32[] memory proof) external payable { require(!paused, "Minting is paused"); require(useWhitelist, "Whitelist sale must be active to mint."); uint256 supply = totalSupply(); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(_verify(leaf, proof), "You are not whitelisted."); require(msg.value >= priceWL * qty, "Sorry, not enough amount sent!"); require(mintedWL[msg.sender] + qty <= maxPerWL, "Sorry, you have reached the WL limit."); require(supply + qty <= maxSupply, "Sorry, not enough left!"); mintedWL[msg.sender] += qty; _safeMint(msg.sender, qty); emit Minted(msg.sender); }
488,965
[ 1, 1893, 309, 326, 729, 1703, 26944, 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, 312, 474, 59, 48, 12, 11890, 5034, 26667, 16, 1731, 1578, 8526, 3778, 14601, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 5, 8774, 3668, 16, 315, 49, 474, 310, 353, 17781, 8863, 203, 3639, 2583, 12, 1202, 18927, 16, 315, 18927, 272, 5349, 1297, 506, 2695, 358, 312, 474, 1199, 1769, 203, 540, 203, 3639, 2254, 5034, 14467, 273, 2078, 3088, 1283, 5621, 203, 540, 203, 3639, 1731, 1578, 7839, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3576, 18, 15330, 10019, 203, 3639, 2583, 24899, 8705, 12, 12070, 16, 14601, 3631, 315, 6225, 854, 486, 26944, 1199, 1769, 203, 540, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 6205, 59, 48, 380, 26667, 16, 315, 28898, 16, 486, 7304, 3844, 3271, 4442, 1769, 7010, 3639, 2583, 12, 81, 474, 329, 59, 48, 63, 3576, 18, 15330, 65, 397, 26667, 1648, 943, 2173, 59, 48, 16, 315, 28898, 16, 1846, 1240, 8675, 326, 678, 48, 1800, 1199, 1769, 203, 3639, 2583, 12, 2859, 1283, 397, 26667, 1648, 943, 3088, 1283, 16, 315, 28898, 16, 486, 7304, 2002, 4442, 1769, 203, 1850, 203, 3639, 312, 474, 329, 59, 48, 63, 3576, 18, 15330, 65, 1011, 26667, 31, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 26667, 1769, 203, 540, 203, 3639, 3626, 490, 474, 329, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 377, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x4599E4F3Eea04BADD41501bF79183e67f6Cf569d/sources/contracts/IHighTableVault.sol
platform fee goes here
address platformVault;
17,148,969
[ 1, 9898, 14036, 13998, 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, 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, 3639, 1758, 4072, 12003, 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, -100, -100, -100 ]
pragma solidity ^0.4.16; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( ) public { totalSupply = 15000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "AI Merchandise"; // Set the name for display purposes symbol = "AM"; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } } /******************************************/ /* ADVANCED TOKEN STARTS HERE */ /******************************************/ contract AMToken is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function AMToken( ) TokenERC20() public {} /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) public { require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks } }
Set the symbol for display purposes
symbol = "AM";
13,820,064
[ 1, 694, 326, 3273, 364, 2562, 13694, 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, 3273, 273, 315, 2192, 14432, 27573, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x52B458d6dD2bB849D1a82EC6d9db507A6fAb6e2D/sources/contracts/Pool_Test_Token.sol
calculate burn fee 2%
function calculateBurnFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_burnFee).div( 10**2 ); }
5,688,243
[ 1, 11162, 18305, 14036, 576, 9, 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, 38, 321, 14667, 12, 11890, 5034, 389, 8949, 13, 3238, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 2463, 389, 8949, 18, 16411, 24899, 70, 321, 14667, 2934, 2892, 12, 203, 1082, 202, 2163, 636, 22, 203, 202, 202, 1769, 203, 202, 97, 203, 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, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.22; import "./zeppelin-solidity/contracts/math/SafeMath.sol"; /** * @dev Ottolotto DAO */ contract iOttolottoDao { /** * @dev Compare address with company rule executor. */ function onlyCompany(address) public view returns (bool) {} } /** * @dev Ottolotto platform referral system interface. */ contract iReferralSystem { /** * @dev Create new referral */ function addReferral(address, address) public returns (bool) {} /** * @dev Get percent by referral system. */ function getPercent(address) public view returns (uint8) {} /** * @dev Get partner in referral system by referral address. */ function getPartner(address) public view returns (address) {} } /** * @title KingsLoto game * * In fact, it’s the most transparent and fair lottery in the world! * Player buys a ticket with cryptocurrency and chooses his 6 lucky numbers (from 0 to 15). * Twice a week (Tuesday and Friday) lottery should start from the block hash, * which was set in advance in the draw info. We’ll take the last number of each hash * (this is exactly that ball, which is used in the regular lottery). * Six hashes - six lucky numbers in the end. Then smart-contract is processing the draw * information and sends all prizes automatically to the winners' wallets! * One ticket plays twice - in regular lottery draw and in the Grand Jackpot draw on the 21st of December. * This means somebody will receive all money for sure! */ contract KingsLoto { using SafeMath for uint256; using SafeMath for uint8; /** * @dev Write info to log when the game was started. * * @param _game Started game. * @param _nextGame Next game number. */ event StartedGame(uint256 indexed _game, uint256 _nextGame); /** * @dev Write to log info about bets calculation progress. * * @param _game Processed game. * @param _processed A number of processed bets. * @param _toProcess Total of bets. */ event GameProgress(uint256 indexed _game, uint256 _processed, uint256 _toProcess); /** * @dev Write to log info about ticket selling. * * @param _game The game number on which ticket was sold. * @param _address Buyer address. * @param bet Player bet. */ event Ticket(uint256 indexed _game, address indexed _address, bytes3 bet); /** * @dev Write info to log about winner when calculating stats. * * @param _address Winner address. * @param _game A number of the game. * @param _matches A number of matches. * @param _bet Winning Bet. * @param _time Time of determining the winner. */ event Winning( address indexed _address, uint256 indexed _game, uint8 _matches, bytes3 _bet, uint256 _time ); /** * @dev Write info to log when the bet was paid. * * @param _address Address of the winner (recipient). * @param _game A number of the game. * @param _matches A number of matches. * @param _bet Winning Bet. * @param _amount Prize amount (in wei). * @param _time A time when the bet was paid. */ event BetPaid( address indexed _address, uint256 indexed _game, uint8 _matches, bytes3 _bet, uint256 _amount, uint256 _time ); /** * @dev Write info to log about jackpot winner. * * @param _address Address of the winner (recipient). * @param _game A number of the game. * @param _amount Prize amount (in wei). * @param _time Time of determining the jackpot winner. */ event Jackpot( address indexed _address, uint256 indexed _game, uint256 _amount, uint256 _time ); /** * @dev Write to log info about raised funds in referral system. * * @param _partner Address of the partner which get funds. * @param _referral Referral address. * @param _type Referral payment type (0x00 - ticket selling, 0x01 winnings in the game). * @param _game A number of the game. * @param _amount Raised funds amount by the partner. * @param _time A time when funds were sent to partner. */ event RaisedByPartner( address indexed _partner, address indexed _referral, bytes1 _type, uint256 _game, uint256 _amount, uint256 _time ); /** * @dev Write info to log about grand jackpot game starting. * * @param _game A number of the game. * @param _time A time when the game was started. */ event ChampionGameStarted(uint256 indexed _game, uint256 _time); /** * @dev Write info to log about the new player in the grand jackpot. * * @param _player Player address. * @param _game A number of the grand jackpot game. * @param _number Player number in the game. */ event ChampionPlayer(address indexed _player, uint256 indexed _game, uint256 _number); /** * @dev Write info to log about the winner in the grand jackpot. * * @param _winner Address of the winner. * @param _game A number of the game. * @param _number Player number in the game. * @param _jackpot Prize. * @param _time A time when the prize was sent to the winner. */ event ChampionWinner( address indexed _winner, uint256 indexed _game, uint256 _number, uint256 _jackpot, uint256 indexed _time ); /** * @dev Bet struct * contain info about the player bet. */ struct Bet { address player; bytes3 bet; } /** * @dev Winner struct * contain info about the winner. */ struct Winner { uint256 betIndex; uint8 matches; } /** * @dev Declares a state variable that stores game winners. */ mapping(uint256 => Winner[]) winners; /** * @dev Declares a state variable that stores game bets. */ mapping(uint256 => Bet[]) gameBets; /** * @dev Declares a state variable that stores game jackpots. */ mapping(uint256 => uint256) weiRaised; /** * @dev Declares a state variable that stores game start block. */ mapping(uint256 => uint256) gameStartBlock; /** * @dev Declares a state variable that stores calculated game stats. */ mapping(uint256 => uint32[7]) gameStats; /** * @dev Declares a state variable that stores game miscalculation status. */ mapping(uint256 => bool) gameCalculated; /** * @dev Declares a state variable that stores game calculation progress status. */ mapping(uint256 => uint256) gameCalculationProgress; /** * @dev Declares a state variable that stores bet payments progress. */ mapping(uint256 => uint256) betsPaymentsProgress; /** * @dev Declares a state variable that stores percentages for funds distribution. */ mapping(uint8 => uint8) percents; /** * @dev Declares a state variable that stores a last byte of the game blocks. */ mapping(uint256 => bytes1[6]) gameBlocks; /** * @dev Declares a state variable that stores a game jackpot, * if the jackpot is raised in this game. */ mapping(uint256 => uint256) raisedJackpots; /** * @dev First game interval in seconds. */ uint256 constant GAME_INTERVAL_ONE = 259200; /** * @dev Second game interval in seconds. */ uint256 constant GAME_INTERVAL_TWO = 345600; /** * @dev Last game start time. */ uint256 public gameStartedAt = 1524830400; /** * @dev Marks current lotto interval. */ bool public isFristInterval = false; /** * @dev Variable that store jackpot value. */ uint256 public jackpot; /** * @dev Next game number. */ uint256 public gameNext; /** * @dev Played game number. */ uint256 public gamePlayed; /** * @dev Lotto game duration in blocks. */ uint8 public gameDuration = 6; /** * @dev The interval which will be added to the start block number. */ uint8 public startBlockInterval = 12; /** * @dev Status of the played game (true if the game is in the process, false if the game is finished). */ bool public gamePlayedStatus = false; /** * @dev Ticket price. */ uint256 public ticketPrice = 0.001 ether; /** * @dev New ticket price for the next game. */ uint256 public newPrice = 0; // Stats of the Grand jackpot. /** * @dev Define constant which indicates rules. */ uint8 constant NUMBER = 1; /** * @dev Define constant which indicates rules. */ uint8 constant STRING = 0; /** * @dev Steps for calculation leap year. */ uint8 public leapYearStep = 2; /** * @dev Interval of the Grand jackpot game in the standard year. */ uint256 constant CHAMPION_GAME_INTERVAL_ONE = 31536000; /** * @dev Interval of the Grand jackpot game in the leap year. */ uint256 constant CHAMPION_GAME_INTERVAL_TWO = 31622400; /** * @dev Last start time for the Grand jackpot. */ uint256 public championGameStartedAt = 1482321600; /** * @dev A number of the next Grand jackpot game. */ uint256 public game = 0; /** * @dev A number of the current Grand jackpot game. */ uint256 public currentGameBlockNumber; /** * @dev Declares a state variable that stores game start block. */ mapping(uint256 => uint256) internal championGameStartBlock; /** * @dev Declares a state variable that stores game start block. */ mapping(uint256 => address[]) internal gamePlayers; /** * @dev Commission of the platform in this game. */ uint256 commission = 21; /** * @dev Ottolotto DAO instance. */ iOttolottoDao public dao; /** * @dev Ottolotto referral system instance. */ iReferralSystem public referralSystem; /** * @dev Initialize smart contract. */ constructor() public { gameNext = block.number; game = block.number; percents[1] = 5; percents[2] = 8; percents[3] = 12; percents[4] = 15; percents[5] = 25; percents[6] = 35; dao = iOttolottoDao(0x24643A6432721070943a389f0D6445FC3F57e18C); referralSystem = iReferralSystem(0x0BD15B6A36f6002AEe906ECdf73877387E66AF96); } /** * @dev Get game prize * * @param _game A number of the game. */ function getGamePrize(uint256 _game) public view returns (uint256) { return weiRaised[_game]; } /** * @dev Get game start block * * @param _game A number of the game. */ function getGameStartBlock(uint256 _game) public view returns (uint256) { return gameStartBlock[_game]; } /** * @dev Get game calculation progress. * * @param _game A number of the game. */ function getGameCalculationProgress(uint256 _game) public view returns (uint256) { return gameCalculationProgress[_game]; } /** * @dev Get players counts in the game. * * @param _game A number of the game. */ function getPlayersCount(uint256 _game) public view returns (uint256) { return gameBets[_game].length; } /** * @dev Get game calculated stats. * * @param _game A number of the game. */ function getGameCalculatedStats(uint256 _game) public view returns (uint32[7]) { return gameStats[_game]; } /** * @dev Get stored game blocks in the contract. * * @param _game A number of the game. */ function getStoredGameBlocks(uint256 _game) public view returns (bytes1[6]) { return gameBlocks[_game]; } /** * @dev Get bets payment progress. * * @param _game A number of the game. */ function getBetsPaymentsProgress(uint256 _game) public view returns (uint256) { return betsPaymentsProgress[_game]; } /** * @dev Check if bets are paid in the game. * * @param _game A number of the game. */ function betsArePayed(uint256 _game) public view returns (bool) { return betsPaymentsProgress[_game] == winners[_game].length; } /** * @dev Get current game interval. */ function getCurrentInterval() public view returns (uint256) { if (isFristInterval) { return GAME_INTERVAL_ONE; } return GAME_INTERVAL_TWO; } /** * @dev Get game target date. */ function targetDate() public view returns (uint256) { return gameStartedAt + getCurrentInterval(); } /** * @dev Change game interval. */ function toogleInterval() internal { uint256 interval = getCurrentInterval(); gameStartedAt += interval; isFristInterval = !isFristInterval; } /** * @dev Make bet function. * * @param _bet Player bet. * @param _partner Referral system partner address. */ function makeBet(bytes3 _bet, address _partner) public payable { require(msg.value == ticketPrice); gameBets[gameNext].push(Bet({player: msg.sender, bet: _bet})); uint256 reised = ticketPrice; address partner = referralSystem.getPartner(msg.sender); if (_partner != 0x0 || partner != 0x0) { if (partner == 0x0) { referralSystem.addReferral(msg.sender, _partner); partner = _partner; } uint8 percent = referralSystem.getPercent(partner); uint256 toPartner = reised.mul(percent).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, msg.sender, 0x00, gameNext, toPartner, now ); reised -= toPartner; } weiRaised[gameNext] += reised; emit Ticket(gameNext, msg.sender, _bet); buyChampionTicket(msg.sender); } /** * @dev Add a player to the Grand jackpot game. * * @param _player Player address. */ function buyChampionTicket(address _player) internal { gamePlayers[game].push(_player); emit ChampionPlayer( _player, currentGameBlockNumber, gamePlayers[game].length ); } /** * @dev Starting lotto game. */ function startGame() public { require(targetDate() <= now); gamePlayed = gameNext; gameNext = block.number; gamePlayedStatus = true; gameStartBlock[gamePlayed] = block.number + startBlockInterval; if (weiRaised[gamePlayed] != 0) { jackpot += weiRaised[gamePlayed].mul(percents[6]).div(100); } toogleInterval(); emit StartedGame(gamePlayed, gameNext); if (newPrice != 0) { ticketPrice = newPrice; newPrice = 0; } } /** * @dev Bitwise shifts for bet comparison. * * @param _bet Player bet. * @param _step Step. */ function bitwiseShifts(bytes3 _bet, uint8 _step) internal pure returns (bytes3) { return _bet >> (20 - (_step * 4)) << 20 >> 4; } /** * @dev Get matches in the bet. * * @param _game A number of the game. * @param _bet Bet. */ function getMatches(uint256 _game, bytes3 _bet) public view returns (uint8) { uint8 matches = 0; for (uint8 i = 0; i < gameDuration; i++) { if (gameBlocks[_game][i] ^ bitwiseShifts(_bet, i) == 0) { matches++; continue; } break; } return matches; } /** * @dev Get matches in the game. * * @param _game A number of the game. */ function getAllMatches(uint256 _game) public view returns (uint256[]) { uint256[] memory matches = new uint256[](7); for (uint32 i = 0; i < gameBets[_game].length; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; } return matches; } /** * @dev Check if the game is over. * * @param _game A number of the game. */ function gameIsOver(uint256 _game) public view returns (bool) { if (gameStartBlock[_game] == 0) { return false; } return (gameStartBlock[_game] + gameDuration - 1) < block.number; } /** * @dev Check if the game is calculated. * * @param _game A number of the game. */ function gameIsCalculated(uint256 _game) public view returns (bool) { return gameCalculated[_game]; } /** * @dev Update game to calculated. * * @param _game A number of the game. */ function updateGameToCalculated(uint256 _game) internal { gameCalculated[_game] = true; gamePlayedStatus = false; } /** * @dev Init game blocks. * * @param _game A number of the game. * @param _startBlock A number of the start block. */ function initGameBlocks(uint256 _game,uint256 _startBlock) internal { for (uint8 i = 0; i < gameDuration; i++) { bytes32 blockHash = blockhash(_startBlock + i); gameBlocks[_game][i] = blockHash[31] << 4 >> 4; } } /** * @dev Process game. * * @param _game A number of the game. * @param _calculationStep Calculation step. */ function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } /** * @dev Distribute raised Wei to Jackpot if there are no matches. * * @param _game A number of the game. */ function distributeRaisedWeiToJackpot(uint256 _game) internal { for (uint8 i = 1; i <= 5; i ++) { if (gameStats[_game][i] == 0) { jackpot += weiRaised[_game].mul(percents[i]).div(100); } } } /** * @dev Change ticket price on the next game. * * @param _newPrice New ticket price. */ function changeTicketPrice(uint256 _newPrice) public { require(dao.onlyCompany(msg.sender)); newPrice = _newPrice; } /** * @dev Distribute funds to the winner, platform, and partners. * * @param _weiWin Funds for distribution. * @param _game A number of the game. * @param _matched A number of the player matches. * @param _player Player address. * @param _bet Player bet. */ function distributeFunds( uint256 _weiWin, uint256 _game, uint8 _matched, address _player, bytes3 _bet ) internal { uint256 toOwner = _weiWin.mul(commission).div(100); uint256 toPartner = 0; address partner = referralSystem.getPartner(msg.sender); if (partner != 0x0) { toPartner = toOwner.div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, _player, 0x01, _game, toPartner, now ); } _player.transfer(_weiWin - toOwner); bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } emit BetPaid( _player, _game, _matched, _bet, _weiWin, now ); if (_matched == 6) { emit Jackpot( _player, _game, _weiWin, now ); } } /** * @dev Make payments in calculated game. * * @param _game A number of the game. * @param _toProcess Amount of payments for the process. */ function makePayments(uint256 _game, uint256 _toProcess) public { require(gameIsCalculated(_game)); require(winners[_game].length != 0); require(betsPaymentsProgress[_game] < winners[_game].length); uint256 steps = _toProcess; if (betsPaymentsProgress[_game] + steps > winners[_game].length) { steps -= betsPaymentsProgress[_game] + steps - winners[_game].length; } uint256 weiWin = 0; uint256 to = betsPaymentsProgress[_game] + steps; for (uint256 i = betsPaymentsProgress[_game]; i < to; i++) { if (winners[_game][i].matches != 6) { uint256 weiByMatch = weiRaised[gamePlayed].mul(percents[winners[_game][i].matches]).div(100); weiWin = weiByMatch.div(gameStats[_game][winners[_game][i].matches]); } else { if (raisedJackpots[_game] == 0 && jackpot != 0) { raisedJackpots[_game] = jackpot; jackpot = 0; } weiWin = raisedJackpots[_game].div(gameStats[_game][winners[_game][i].matches]); } distributeFunds( weiWin, _game, winners[_game][i].matches, gameBets[game][winners[_game][i].betIndex].player, gameBets[game][winners[_game][i].betIndex].bet ); } betsPaymentsProgress[_game] = i; } /** * @dev Get Grand jackpot start block. * * @param _game A number of the game. */ function getChampionStartBlock(uint256 _game) public view returns (uint256) { return championGameStartBlock[_game]; } /** * @dev Get players in Grand jackpot. * * @param _game A number of the game. */ function getChampionPlayersCountByGame(uint256 _game) public view returns (uint256) { return gamePlayers[_game].length; } /** * @dev Check if is number at the end of the game hash. * * @param _game A number of the game. */ function isNumber(uint256 _game) private view returns (bool) { bytes32 hash = blockhash(_game); require(hash != 0x0); byte b = byte(hash[31]); uint hi = uint8(b) / 16; uint lo = uint8(b) - 16 * uint8(hi); if (lo <= 9) { return true; } return false; } /** * @dev Get Grand jackpot interval. */ function getChampionCurrentInterval() public view returns (uint256) { if (leapYearStep != 4) { return CHAMPION_GAME_INTERVAL_ONE; } return CHAMPION_GAME_INTERVAL_TWO; } /** * @dev Get target Grand jackpot date. */ function targetChampionDate() public view returns (uint256) { return championGameStartedAt + getChampionCurrentInterval(); } /** * @dev Change step. */ function changeChampionStep() internal { uint256 interval = getChampionCurrentInterval(); championGameStartedAt += interval; if (leapYearStep == 4) { leapYearStep = 1; } else { leapYearStep += 1; } } /** * @dev Starts Grand jackpot game. */ function startChampionGame() public { require(currentGameBlockNumber == 0); require(targetChampionDate() <= now); currentGameBlockNumber = game; game = block.number; championGameStartBlock[currentGameBlockNumber] = block.number + startBlockInterval; emit ChampionGameStarted(currentGameBlockNumber, now); changeChampionStep(); } /** * @dev Finish Grand jackpot game. */ function finishChampionGame() public { require(currentGameBlockNumber != 0); uint8 steps = getCurrentGameSteps(); uint256 startBlock = getChampionStartBlock(currentGameBlockNumber); require(startBlock + steps < block.number); if (gamePlayers[currentGameBlockNumber].length != 0) { uint256 lMin = 0; uint256 lMax = 0; uint256 rMin = 0; uint256 rMax = 0; (lMin, lMax, rMin, rMax) = processSteps(currentGameBlockNumber, steps); address winner = gamePlayers[currentGameBlockNumber][rMax]; uint256 toOwner = jackpot.mul(commission).div(100); uint256 jp = jackpot - toOwner; emit ChampionWinner( winner, currentGameBlockNumber, rMax, jackpot, now ); winner.transfer(jp); uint256 toPartner = 0; address partner = referralSystem.getPartner(winner); if (partner != 0x0) { toPartner = toOwner.mul(1).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, winner, 0x01, currentGameBlockNumber, toPartner, now ); } bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } jackpot = 0; } currentGameBlockNumber = 0; } /** * @dev Get steps in this Grand jackpot game. */ function getCurrentGameSteps() public view returns (uint8) { return uint8(getStepsCount(currentGameBlockNumber)); } /** * @dev Calculate game steps. * * @param _game A number of the game. */ function getStepsCount(uint256 _game) public view returns (uint256 y) { uint256 x = getChampionPlayersCountByGame(_game); assembly { let arg := x x := sub(x,1) x := or(x, div(x, 0x02)) x := or(x, div(x, 0x04)) x := or(x, div(x, 0x10)) x := or(x, div(x, 0x100)) x := or(x, div(x, 0x10000)) x := or(x, div(x, 0x100000000)) x := or(x, div(x, 0x10000000000000000)) x := or(x, div(x, 0x100000000000000000000000000000000)) x := add(x, 1) let m := mload(0x40) mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd) mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe) mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616) mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff) mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e) mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707) mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606) mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100) mstore(0x40, add(m, 0x100)) let value := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff let shift := 0x100000000000000000000000000000000000000000000000000000000000000 let a := div(mul(x, value), shift) y := div(mload(add(m,sub(255,a))), shift) y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000))) } } /** * @dev Refill the Jackpot. */ function refillTheJackpot() public payable { require(msg.value > 0); jackpot += msg.value; } /** * @dev Get Grand jackpot game rules. * * @param _game A number of the game. */ function getChampionGameRules(uint256 _game) public view returns (uint8 left, uint8 right) { if (isNumber(_game)) { left = NUMBER; right = STRING; } else { left = STRING; right = NUMBER; } return (left, right); } /** * @dev Process Grand jackpot steps. * * @param _gameBlock A number of the game. * @param _step Step to which needed calculation. */ function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; } else if (isEvenNumber(rMax)) { lMax = rMax / 2; rMin = rMax / 2 + 1; } else { lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; } else { lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } /** * @dev Check if is even number. * * @param _v1 Number. */ function isEvenNumber(uint _v1) internal pure returns (bool) { uint v1u = _v1 * 100; uint v2 = 2; uint vuResult = v1u / v2; uint vResult = _v1 / v2; if (vuResult != vResult * 100) { return false; } return true; } }
* @title KingsLoto game In fact, it’s the most transparent and fair lottery in the world! Player buys a ticket with cryptocurrency and chooses his 6 lucky numbers (from 0 to 15). Twice a week (Tuesday and Friday) lottery should start from the block hash, which was set in advance in the draw info. We’ll take the last number of each hash (this is exactly that ball, which is used in the regular lottery). Six hashes - six lucky numbers in the end. Then smart-contract is processing the draw information and sends all prizes automatically to the winners' wallets! One ticket plays twice - in regular lottery draw and in the Grand Jackpot draw on the 21st of December. This means somebody will receive all money for sure!/
contract KingsLoto { using SafeMath for uint256; using SafeMath for uint8; event StartedGame(uint256 indexed _game, uint256 _nextGame); event GameProgress(uint256 indexed _game, uint256 _processed, uint256 _toProcess); event Ticket(uint256 indexed _game, address indexed _address, bytes3 bet); event Winning( address indexed _address, uint256 indexed _game, uint8 _matches, bytes3 _bet, uint256 _time ); event BetPaid( address indexed _address, uint256 indexed _game, uint8 _matches, bytes3 _bet, uint256 _amount, uint256 _time ); event Jackpot( address indexed _address, uint256 indexed _game, uint256 _amount, uint256 _time ); event RaisedByPartner( address indexed _partner, address indexed _referral, bytes1 _type, uint256 _game, uint256 _amount, uint256 _time ); event ChampionGameStarted(uint256 indexed _game, uint256 _time); event ChampionPlayer(address indexed _player, uint256 indexed _game, uint256 _number); event ChampionWinner( address indexed _winner, uint256 indexed _game, uint256 _number, uint256 _jackpot, uint256 indexed _time ); struct Bet { address player; bytes3 bet; } struct Winner { uint256 betIndex; uint8 matches; } mapping(uint256 => Winner[]) winners; mapping(uint256 => Bet[]) gameBets; mapping(uint256 => uint256) weiRaised; mapping(uint256 => uint256) gameStartBlock; mapping(uint256 => uint32[7]) gameStats; mapping(uint256 => bool) gameCalculated; mapping(uint256 => uint256) gameCalculationProgress; mapping(uint256 => uint256) betsPaymentsProgress; mapping(uint8 => uint8) percents; mapping(uint256 => bytes1[6]) gameBlocks; mapping(uint256 => uint256) raisedJackpots; uint256 constant GAME_INTERVAL_ONE = 259200; uint256 constant GAME_INTERVAL_TWO = 345600; uint256 public gameStartedAt = 1524830400; bool public isFristInterval = false; uint256 public jackpot; uint256 public gameNext; uint256 public gamePlayed; uint8 public gameDuration = 6; uint8 public startBlockInterval = 12; bool public gamePlayedStatus = false; uint256 public ticketPrice = 0.001 ether; uint256 public newPrice = 0; uint8 constant NUMBER = 1; uint8 constant STRING = 0; uint8 public leapYearStep = 2; uint256 constant CHAMPION_GAME_INTERVAL_ONE = 31536000; uint256 constant CHAMPION_GAME_INTERVAL_TWO = 31622400; uint256 public championGameStartedAt = 1482321600; uint256 public game = 0; uint256 public currentGameBlockNumber; mapping(uint256 => uint256) internal championGameStartBlock; mapping(uint256 => address[]) internal gamePlayers; uint256 commission = 21; iOttolottoDao public dao; iReferralSystem public referralSystem; constructor() public { gameNext = block.number; game = block.number; percents[1] = 5; percents[2] = 8; percents[3] = 12; percents[4] = 15; percents[5] = 25; percents[6] = 35; dao = iOttolottoDao(0x24643A6432721070943a389f0D6445FC3F57e18C); referralSystem = iReferralSystem(0x0BD15B6A36f6002AEe906ECdf73877387E66AF96); } function getGamePrize(uint256 _game) public view returns (uint256) { return weiRaised[_game]; } function getGameStartBlock(uint256 _game) public view returns (uint256) { return gameStartBlock[_game]; } function getGameCalculationProgress(uint256 _game) public view returns (uint256) { return gameCalculationProgress[_game]; } function getPlayersCount(uint256 _game) public view returns (uint256) { return gameBets[_game].length; } function getGameCalculatedStats(uint256 _game) public view returns (uint32[7]) { return gameStats[_game]; } function getStoredGameBlocks(uint256 _game) public view returns (bytes1[6]) { return gameBlocks[_game]; } function getBetsPaymentsProgress(uint256 _game) public view returns (uint256) { return betsPaymentsProgress[_game]; } function betsArePayed(uint256 _game) public view returns (bool) { return betsPaymentsProgress[_game] == winners[_game].length; } function getCurrentInterval() public view returns (uint256) { if (isFristInterval) { return GAME_INTERVAL_ONE; } return GAME_INTERVAL_TWO; } function getCurrentInterval() public view returns (uint256) { if (isFristInterval) { return GAME_INTERVAL_ONE; } return GAME_INTERVAL_TWO; } function targetDate() public view returns (uint256) { return gameStartedAt + getCurrentInterval(); } function toogleInterval() internal { uint256 interval = getCurrentInterval(); gameStartedAt += interval; isFristInterval = !isFristInterval; } function makeBet(bytes3 _bet, address _partner) public payable { require(msg.value == ticketPrice); uint256 reised = ticketPrice; address partner = referralSystem.getPartner(msg.sender); if (_partner != 0x0 || partner != 0x0) { if (partner == 0x0) { referralSystem.addReferral(msg.sender, _partner); partner = _partner; } uint8 percent = referralSystem.getPercent(partner); uint256 toPartner = reised.mul(percent).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, msg.sender, 0x00, gameNext, toPartner, now ); reised -= toPartner; } weiRaised[gameNext] += reised; emit Ticket(gameNext, msg.sender, _bet); buyChampionTicket(msg.sender); } gameBets[gameNext].push(Bet({player: msg.sender, bet: _bet})); function makeBet(bytes3 _bet, address _partner) public payable { require(msg.value == ticketPrice); uint256 reised = ticketPrice; address partner = referralSystem.getPartner(msg.sender); if (_partner != 0x0 || partner != 0x0) { if (partner == 0x0) { referralSystem.addReferral(msg.sender, _partner); partner = _partner; } uint8 percent = referralSystem.getPercent(partner); uint256 toPartner = reised.mul(percent).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, msg.sender, 0x00, gameNext, toPartner, now ); reised -= toPartner; } weiRaised[gameNext] += reised; emit Ticket(gameNext, msg.sender, _bet); buyChampionTicket(msg.sender); } function makeBet(bytes3 _bet, address _partner) public payable { require(msg.value == ticketPrice); uint256 reised = ticketPrice; address partner = referralSystem.getPartner(msg.sender); if (_partner != 0x0 || partner != 0x0) { if (partner == 0x0) { referralSystem.addReferral(msg.sender, _partner); partner = _partner; } uint8 percent = referralSystem.getPercent(partner); uint256 toPartner = reised.mul(percent).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, msg.sender, 0x00, gameNext, toPartner, now ); reised -= toPartner; } weiRaised[gameNext] += reised; emit Ticket(gameNext, msg.sender, _bet); buyChampionTicket(msg.sender); } function buyChampionTicket(address _player) internal { gamePlayers[game].push(_player); emit ChampionPlayer( _player, currentGameBlockNumber, gamePlayers[game].length ); } function startGame() public { require(targetDate() <= now); gamePlayed = gameNext; gameNext = block.number; gamePlayedStatus = true; gameStartBlock[gamePlayed] = block.number + startBlockInterval; if (weiRaised[gamePlayed] != 0) { jackpot += weiRaised[gamePlayed].mul(percents[6]).div(100); } toogleInterval(); emit StartedGame(gamePlayed, gameNext); if (newPrice != 0) { ticketPrice = newPrice; newPrice = 0; } } function startGame() public { require(targetDate() <= now); gamePlayed = gameNext; gameNext = block.number; gamePlayedStatus = true; gameStartBlock[gamePlayed] = block.number + startBlockInterval; if (weiRaised[gamePlayed] != 0) { jackpot += weiRaised[gamePlayed].mul(percents[6]).div(100); } toogleInterval(); emit StartedGame(gamePlayed, gameNext); if (newPrice != 0) { ticketPrice = newPrice; newPrice = 0; } } function startGame() public { require(targetDate() <= now); gamePlayed = gameNext; gameNext = block.number; gamePlayedStatus = true; gameStartBlock[gamePlayed] = block.number + startBlockInterval; if (weiRaised[gamePlayed] != 0) { jackpot += weiRaised[gamePlayed].mul(percents[6]).div(100); } toogleInterval(); emit StartedGame(gamePlayed, gameNext); if (newPrice != 0) { ticketPrice = newPrice; newPrice = 0; } } function bitwiseShifts(bytes3 _bet, uint8 _step) internal pure returns (bytes3) { return _bet >> (20 - (_step * 4)) << 20 >> 4; } function getMatches(uint256 _game, bytes3 _bet) public view returns (uint8) { uint8 matches = 0; for (uint8 i = 0; i < gameDuration; i++) { if (gameBlocks[_game][i] ^ bitwiseShifts(_bet, i) == 0) { matches++; continue; } break; } return matches; } function getMatches(uint256 _game, bytes3 _bet) public view returns (uint8) { uint8 matches = 0; for (uint8 i = 0; i < gameDuration; i++) { if (gameBlocks[_game][i] ^ bitwiseShifts(_bet, i) == 0) { matches++; continue; } break; } return matches; } function getMatches(uint256 _game, bytes3 _bet) public view returns (uint8) { uint8 matches = 0; for (uint8 i = 0; i < gameDuration; i++) { if (gameBlocks[_game][i] ^ bitwiseShifts(_bet, i) == 0) { matches++; continue; } break; } return matches; } function getAllMatches(uint256 _game) public view returns (uint256[]) { uint256[] memory matches = new uint256[](7); for (uint32 i = 0; i < gameBets[_game].length; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; } return matches; } function getAllMatches(uint256 _game) public view returns (uint256[]) { uint256[] memory matches = new uint256[](7); for (uint32 i = 0; i < gameBets[_game].length; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; } return matches; } function getAllMatches(uint256 _game) public view returns (uint256[]) { uint256[] memory matches = new uint256[](7); for (uint32 i = 0; i < gameBets[_game].length; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; } return matches; } function gameIsOver(uint256 _game) public view returns (bool) { if (gameStartBlock[_game] == 0) { return false; } return (gameStartBlock[_game] + gameDuration - 1) < block.number; } function gameIsOver(uint256 _game) public view returns (bool) { if (gameStartBlock[_game] == 0) { return false; } return (gameStartBlock[_game] + gameDuration - 1) < block.number; } function gameIsCalculated(uint256 _game) public view returns (bool) { return gameCalculated[_game]; } function updateGameToCalculated(uint256 _game) internal { gameCalculated[_game] = true; gamePlayedStatus = false; } function initGameBlocks(uint256 _game,uint256 _startBlock) internal { for (uint8 i = 0; i < gameDuration; i++) { bytes32 blockHash = blockhash(_startBlock + i); gameBlocks[_game][i] = blockHash[31] << 4 >> 4; } } function initGameBlocks(uint256 _game,uint256 _startBlock) internal { for (uint8 i = 0; i < gameDuration; i++) { bytes32 blockHash = blockhash(_startBlock + i); gameBlocks[_game][i] = blockHash[31] << 4 >> 4; } } function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } function distributeRaisedWeiToJackpot(uint256 _game) internal { for (uint8 i = 1; i <= 5; i ++) { if (gameStats[_game][i] == 0) { jackpot += weiRaised[_game].mul(percents[i]).div(100); } } } function distributeRaisedWeiToJackpot(uint256 _game) internal { for (uint8 i = 1; i <= 5; i ++) { if (gameStats[_game][i] == 0) { jackpot += weiRaised[_game].mul(percents[i]).div(100); } } } function distributeRaisedWeiToJackpot(uint256 _game) internal { for (uint8 i = 1; i <= 5; i ++) { if (gameStats[_game][i] == 0) { jackpot += weiRaised[_game].mul(percents[i]).div(100); } } } function changeTicketPrice(uint256 _newPrice) public { require(dao.onlyCompany(msg.sender)); newPrice = _newPrice; } function distributeFunds( uint256 _weiWin, uint256 _game, uint8 _matched, address _player, bytes3 _bet ) internal { uint256 toOwner = _weiWin.mul(commission).div(100); uint256 toPartner = 0; address partner = referralSystem.getPartner(msg.sender); if (partner != 0x0) { toPartner = toOwner.div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, _player, 0x01, _game, toPartner, now ); } _player.transfer(_weiWin - toOwner); bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } emit BetPaid( _player, _game, _matched, _bet, _weiWin, now ); if (_matched == 6) { emit Jackpot( _player, _game, _weiWin, now ); } } function distributeFunds( uint256 _weiWin, uint256 _game, uint8 _matched, address _player, bytes3 _bet ) internal { uint256 toOwner = _weiWin.mul(commission).div(100); uint256 toPartner = 0; address partner = referralSystem.getPartner(msg.sender); if (partner != 0x0) { toPartner = toOwner.div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, _player, 0x01, _game, toPartner, now ); } _player.transfer(_weiWin - toOwner); bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } emit BetPaid( _player, _game, _matched, _bet, _weiWin, now ); if (_matched == 6) { emit Jackpot( _player, _game, _weiWin, now ); } } function distributeFunds( uint256 _weiWin, uint256 _game, uint8 _matched, address _player, bytes3 _bet ) internal { uint256 toOwner = _weiWin.mul(commission).div(100); uint256 toPartner = 0; address partner = referralSystem.getPartner(msg.sender); if (partner != 0x0) { toPartner = toOwner.div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, _player, 0x01, _game, toPartner, now ); } _player.transfer(_weiWin - toOwner); bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } emit BetPaid( _player, _game, _matched, _bet, _weiWin, now ); if (_matched == 6) { emit Jackpot( _player, _game, _weiWin, now ); } } function distributeFunds( uint256 _weiWin, uint256 _game, uint8 _matched, address _player, bytes3 _bet ) internal { uint256 toOwner = _weiWin.mul(commission).div(100); uint256 toPartner = 0; address partner = referralSystem.getPartner(msg.sender); if (partner != 0x0) { toPartner = toOwner.div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, _player, 0x01, _game, toPartner, now ); } _player.transfer(_weiWin - toOwner); bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } emit BetPaid( _player, _game, _matched, _bet, _weiWin, now ); if (_matched == 6) { emit Jackpot( _player, _game, _weiWin, now ); } } function makePayments(uint256 _game, uint256 _toProcess) public { require(gameIsCalculated(_game)); require(winners[_game].length != 0); require(betsPaymentsProgress[_game] < winners[_game].length); uint256 steps = _toProcess; if (betsPaymentsProgress[_game] + steps > winners[_game].length) { steps -= betsPaymentsProgress[_game] + steps - winners[_game].length; } uint256 weiWin = 0; uint256 to = betsPaymentsProgress[_game] + steps; for (uint256 i = betsPaymentsProgress[_game]; i < to; i++) { if (winners[_game][i].matches != 6) { uint256 weiByMatch = weiRaised[gamePlayed].mul(percents[winners[_game][i].matches]).div(100); weiWin = weiByMatch.div(gameStats[_game][winners[_game][i].matches]); if (raisedJackpots[_game] == 0 && jackpot != 0) { raisedJackpots[_game] = jackpot; jackpot = 0; } weiWin = raisedJackpots[_game].div(gameStats[_game][winners[_game][i].matches]); } distributeFunds( weiWin, _game, winners[_game][i].matches, gameBets[game][winners[_game][i].betIndex].player, gameBets[game][winners[_game][i].betIndex].bet ); } betsPaymentsProgress[_game] = i; } function makePayments(uint256 _game, uint256 _toProcess) public { require(gameIsCalculated(_game)); require(winners[_game].length != 0); require(betsPaymentsProgress[_game] < winners[_game].length); uint256 steps = _toProcess; if (betsPaymentsProgress[_game] + steps > winners[_game].length) { steps -= betsPaymentsProgress[_game] + steps - winners[_game].length; } uint256 weiWin = 0; uint256 to = betsPaymentsProgress[_game] + steps; for (uint256 i = betsPaymentsProgress[_game]; i < to; i++) { if (winners[_game][i].matches != 6) { uint256 weiByMatch = weiRaised[gamePlayed].mul(percents[winners[_game][i].matches]).div(100); weiWin = weiByMatch.div(gameStats[_game][winners[_game][i].matches]); if (raisedJackpots[_game] == 0 && jackpot != 0) { raisedJackpots[_game] = jackpot; jackpot = 0; } weiWin = raisedJackpots[_game].div(gameStats[_game][winners[_game][i].matches]); } distributeFunds( weiWin, _game, winners[_game][i].matches, gameBets[game][winners[_game][i].betIndex].player, gameBets[game][winners[_game][i].betIndex].bet ); } betsPaymentsProgress[_game] = i; } function makePayments(uint256 _game, uint256 _toProcess) public { require(gameIsCalculated(_game)); require(winners[_game].length != 0); require(betsPaymentsProgress[_game] < winners[_game].length); uint256 steps = _toProcess; if (betsPaymentsProgress[_game] + steps > winners[_game].length) { steps -= betsPaymentsProgress[_game] + steps - winners[_game].length; } uint256 weiWin = 0; uint256 to = betsPaymentsProgress[_game] + steps; for (uint256 i = betsPaymentsProgress[_game]; i < to; i++) { if (winners[_game][i].matches != 6) { uint256 weiByMatch = weiRaised[gamePlayed].mul(percents[winners[_game][i].matches]).div(100); weiWin = weiByMatch.div(gameStats[_game][winners[_game][i].matches]); if (raisedJackpots[_game] == 0 && jackpot != 0) { raisedJackpots[_game] = jackpot; jackpot = 0; } weiWin = raisedJackpots[_game].div(gameStats[_game][winners[_game][i].matches]); } distributeFunds( weiWin, _game, winners[_game][i].matches, gameBets[game][winners[_game][i].betIndex].player, gameBets[game][winners[_game][i].betIndex].bet ); } betsPaymentsProgress[_game] = i; } function makePayments(uint256 _game, uint256 _toProcess) public { require(gameIsCalculated(_game)); require(winners[_game].length != 0); require(betsPaymentsProgress[_game] < winners[_game].length); uint256 steps = _toProcess; if (betsPaymentsProgress[_game] + steps > winners[_game].length) { steps -= betsPaymentsProgress[_game] + steps - winners[_game].length; } uint256 weiWin = 0; uint256 to = betsPaymentsProgress[_game] + steps; for (uint256 i = betsPaymentsProgress[_game]; i < to; i++) { if (winners[_game][i].matches != 6) { uint256 weiByMatch = weiRaised[gamePlayed].mul(percents[winners[_game][i].matches]).div(100); weiWin = weiByMatch.div(gameStats[_game][winners[_game][i].matches]); if (raisedJackpots[_game] == 0 && jackpot != 0) { raisedJackpots[_game] = jackpot; jackpot = 0; } weiWin = raisedJackpots[_game].div(gameStats[_game][winners[_game][i].matches]); } distributeFunds( weiWin, _game, winners[_game][i].matches, gameBets[game][winners[_game][i].betIndex].player, gameBets[game][winners[_game][i].betIndex].bet ); } betsPaymentsProgress[_game] = i; } } else { function makePayments(uint256 _game, uint256 _toProcess) public { require(gameIsCalculated(_game)); require(winners[_game].length != 0); require(betsPaymentsProgress[_game] < winners[_game].length); uint256 steps = _toProcess; if (betsPaymentsProgress[_game] + steps > winners[_game].length) { steps -= betsPaymentsProgress[_game] + steps - winners[_game].length; } uint256 weiWin = 0; uint256 to = betsPaymentsProgress[_game] + steps; for (uint256 i = betsPaymentsProgress[_game]; i < to; i++) { if (winners[_game][i].matches != 6) { uint256 weiByMatch = weiRaised[gamePlayed].mul(percents[winners[_game][i].matches]).div(100); weiWin = weiByMatch.div(gameStats[_game][winners[_game][i].matches]); if (raisedJackpots[_game] == 0 && jackpot != 0) { raisedJackpots[_game] = jackpot; jackpot = 0; } weiWin = raisedJackpots[_game].div(gameStats[_game][winners[_game][i].matches]); } distributeFunds( weiWin, _game, winners[_game][i].matches, gameBets[game][winners[_game][i].betIndex].player, gameBets[game][winners[_game][i].betIndex].bet ); } betsPaymentsProgress[_game] = i; } function getChampionStartBlock(uint256 _game) public view returns (uint256) { return championGameStartBlock[_game]; } function getChampionPlayersCountByGame(uint256 _game) public view returns (uint256) { return gamePlayers[_game].length; } function isNumber(uint256 _game) private view returns (bool) { bytes32 hash = blockhash(_game); require(hash != 0x0); byte b = byte(hash[31]); uint hi = uint8(b) / 16; uint lo = uint8(b) - 16 * uint8(hi); if (lo <= 9) { return true; } return false; } function isNumber(uint256 _game) private view returns (bool) { bytes32 hash = blockhash(_game); require(hash != 0x0); byte b = byte(hash[31]); uint hi = uint8(b) / 16; uint lo = uint8(b) - 16 * uint8(hi); if (lo <= 9) { return true; } return false; } function getChampionCurrentInterval() public view returns (uint256) { if (leapYearStep != 4) { return CHAMPION_GAME_INTERVAL_ONE; } return CHAMPION_GAME_INTERVAL_TWO; } function getChampionCurrentInterval() public view returns (uint256) { if (leapYearStep != 4) { return CHAMPION_GAME_INTERVAL_ONE; } return CHAMPION_GAME_INTERVAL_TWO; } function targetChampionDate() public view returns (uint256) { return championGameStartedAt + getChampionCurrentInterval(); } function changeChampionStep() internal { uint256 interval = getChampionCurrentInterval(); championGameStartedAt += interval; if (leapYearStep == 4) { leapYearStep = 1; leapYearStep += 1; } } function changeChampionStep() internal { uint256 interval = getChampionCurrentInterval(); championGameStartedAt += interval; if (leapYearStep == 4) { leapYearStep = 1; leapYearStep += 1; } } } else { function startChampionGame() public { require(currentGameBlockNumber == 0); require(targetChampionDate() <= now); currentGameBlockNumber = game; game = block.number; championGameStartBlock[currentGameBlockNumber] = block.number + startBlockInterval; emit ChampionGameStarted(currentGameBlockNumber, now); changeChampionStep(); } function finishChampionGame() public { require(currentGameBlockNumber != 0); uint8 steps = getCurrentGameSteps(); uint256 startBlock = getChampionStartBlock(currentGameBlockNumber); require(startBlock + steps < block.number); if (gamePlayers[currentGameBlockNumber].length != 0) { uint256 lMin = 0; uint256 lMax = 0; uint256 rMin = 0; uint256 rMax = 0; (lMin, lMax, rMin, rMax) = processSteps(currentGameBlockNumber, steps); address winner = gamePlayers[currentGameBlockNumber][rMax]; uint256 toOwner = jackpot.mul(commission).div(100); uint256 jp = jackpot - toOwner; emit ChampionWinner( winner, currentGameBlockNumber, rMax, jackpot, now ); winner.transfer(jp); uint256 toPartner = 0; address partner = referralSystem.getPartner(winner); if (partner != 0x0) { toPartner = toOwner.mul(1).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, winner, 0x01, currentGameBlockNumber, toPartner, now ); } bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } jackpot = 0; } currentGameBlockNumber = 0; } function finishChampionGame() public { require(currentGameBlockNumber != 0); uint8 steps = getCurrentGameSteps(); uint256 startBlock = getChampionStartBlock(currentGameBlockNumber); require(startBlock + steps < block.number); if (gamePlayers[currentGameBlockNumber].length != 0) { uint256 lMin = 0; uint256 lMax = 0; uint256 rMin = 0; uint256 rMax = 0; (lMin, lMax, rMin, rMax) = processSteps(currentGameBlockNumber, steps); address winner = gamePlayers[currentGameBlockNumber][rMax]; uint256 toOwner = jackpot.mul(commission).div(100); uint256 jp = jackpot - toOwner; emit ChampionWinner( winner, currentGameBlockNumber, rMax, jackpot, now ); winner.transfer(jp); uint256 toPartner = 0; address partner = referralSystem.getPartner(winner); if (partner != 0x0) { toPartner = toOwner.mul(1).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, winner, 0x01, currentGameBlockNumber, toPartner, now ); } bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } jackpot = 0; } currentGameBlockNumber = 0; } function finishChampionGame() public { require(currentGameBlockNumber != 0); uint8 steps = getCurrentGameSteps(); uint256 startBlock = getChampionStartBlock(currentGameBlockNumber); require(startBlock + steps < block.number); if (gamePlayers[currentGameBlockNumber].length != 0) { uint256 lMin = 0; uint256 lMax = 0; uint256 rMin = 0; uint256 rMax = 0; (lMin, lMax, rMin, rMax) = processSteps(currentGameBlockNumber, steps); address winner = gamePlayers[currentGameBlockNumber][rMax]; uint256 toOwner = jackpot.mul(commission).div(100); uint256 jp = jackpot - toOwner; emit ChampionWinner( winner, currentGameBlockNumber, rMax, jackpot, now ); winner.transfer(jp); uint256 toPartner = 0; address partner = referralSystem.getPartner(winner); if (partner != 0x0) { toPartner = toOwner.mul(1).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, winner, 0x01, currentGameBlockNumber, toPartner, now ); } bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } jackpot = 0; } currentGameBlockNumber = 0; } function finishChampionGame() public { require(currentGameBlockNumber != 0); uint8 steps = getCurrentGameSteps(); uint256 startBlock = getChampionStartBlock(currentGameBlockNumber); require(startBlock + steps < block.number); if (gamePlayers[currentGameBlockNumber].length != 0) { uint256 lMin = 0; uint256 lMax = 0; uint256 rMin = 0; uint256 rMax = 0; (lMin, lMax, rMin, rMax) = processSteps(currentGameBlockNumber, steps); address winner = gamePlayers[currentGameBlockNumber][rMax]; uint256 toOwner = jackpot.mul(commission).div(100); uint256 jp = jackpot - toOwner; emit ChampionWinner( winner, currentGameBlockNumber, rMax, jackpot, now ); winner.transfer(jp); uint256 toPartner = 0; address partner = referralSystem.getPartner(winner); if (partner != 0x0) { toPartner = toOwner.mul(1).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, winner, 0x01, currentGameBlockNumber, toPartner, now ); } bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } jackpot = 0; } currentGameBlockNumber = 0; } function getCurrentGameSteps() public view returns (uint8) { return uint8(getStepsCount(currentGameBlockNumber)); } function getStepsCount(uint256 _game) public view returns (uint256 y) { uint256 x = getChampionPlayersCountByGame(_game); assembly { let arg := x x := sub(x,1) x := or(x, div(x, 0x02)) x := or(x, div(x, 0x04)) x := or(x, div(x, 0x10)) x := or(x, div(x, 0x100)) x := or(x, div(x, 0x10000)) x := or(x, div(x, 0x100000000)) x := or(x, div(x, 0x10000000000000000)) x := or(x, div(x, 0x100000000000000000000000000000000)) x := add(x, 1) let m := mload(0x40) mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd) mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe) mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616) mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff) mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e) mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707) mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606) mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100) mstore(0x40, add(m, 0x100)) let value := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff let shift := 0x100000000000000000000000000000000000000000000000000000000000000 let a := div(mul(x, value), shift) y := div(mload(add(m,sub(255,a))), shift) y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000))) } } function getStepsCount(uint256 _game) public view returns (uint256 y) { uint256 x = getChampionPlayersCountByGame(_game); assembly { let arg := x x := sub(x,1) x := or(x, div(x, 0x02)) x := or(x, div(x, 0x04)) x := or(x, div(x, 0x10)) x := or(x, div(x, 0x100)) x := or(x, div(x, 0x10000)) x := or(x, div(x, 0x100000000)) x := or(x, div(x, 0x10000000000000000)) x := or(x, div(x, 0x100000000000000000000000000000000)) x := add(x, 1) let m := mload(0x40) mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd) mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe) mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616) mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff) mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e) mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707) mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606) mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100) mstore(0x40, add(m, 0x100)) let value := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff let shift := 0x100000000000000000000000000000000000000000000000000000000000000 let a := div(mul(x, value), shift) y := div(mload(add(m,sub(255,a))), shift) y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000))) } } function refillTheJackpot() public payable { require(msg.value > 0); jackpot += msg.value; } function getChampionGameRules(uint256 _game) public view returns (uint8 left, uint8 right) { if (isNumber(_game)) { left = NUMBER; right = STRING; left = STRING; right = NUMBER; } return (left, right); } function getChampionGameRules(uint256 _game) public view returns (uint8 left, uint8 right) { if (isNumber(_game)) { left = NUMBER; right = STRING; left = STRING; right = NUMBER; } return (left, right); } } else { function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } } else if (isEvenNumber(rMax)) { } else { function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } } else { function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; lMax = rMax / 2; rMin = rMax / 2 + 1; lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } function isEvenNumber(uint _v1) internal pure returns (bool) { uint v1u = _v1 * 100; uint v2 = 2; uint vuResult = v1u / v2; uint vResult = _v1 / v2; if (vuResult != vResult * 100) { return false; } return true; } function isEvenNumber(uint _v1) internal pure returns (bool) { uint v1u = _v1 * 100; uint v2 = 2; uint vuResult = v1u / v2; uint vResult = _v1 / v2; if (vuResult != vResult * 100) { return false; } return true; } }
12,946,949
[ 1, 47, 899, 48, 6302, 7920, 657, 5410, 16, 518, 163, 227, 252, 87, 326, 4486, 17270, 471, 284, 1826, 17417, 387, 93, 316, 326, 9117, 5, 19185, 25666, 1900, 279, 9322, 598, 13231, 504, 295, 3040, 471, 24784, 281, 18423, 1666, 328, 9031, 93, 5600, 261, 2080, 374, 358, 4711, 2934, 12694, 1812, 279, 4860, 261, 56, 3610, 2881, 471, 478, 1691, 528, 13, 17417, 387, 93, 1410, 787, 628, 326, 1203, 1651, 16, 1492, 1703, 444, 316, 8312, 316, 326, 3724, 1123, 18, 1660, 163, 227, 252, 2906, 4862, 326, 1142, 1300, 434, 1517, 1651, 261, 2211, 353, 8950, 716, 26503, 16, 1492, 353, 1399, 316, 326, 6736, 17417, 387, 93, 2934, 348, 697, 9869, 300, 5050, 328, 9031, 93, 5600, 316, 326, 679, 18, 9697, 13706, 17, 16351, 353, 4929, 326, 3724, 1779, 471, 9573, 777, 846, 3128, 6635, 358, 326, 5657, 9646, 11, 17662, 2413, 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, 16351, 1475, 899, 48, 6302, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 28, 31, 203, 203, 565, 871, 29386, 12496, 12, 11890, 5034, 8808, 389, 13957, 16, 2254, 5034, 389, 4285, 12496, 1769, 203, 203, 565, 871, 14121, 5491, 12, 11890, 5034, 8808, 389, 13957, 16, 2254, 5034, 389, 11005, 16, 2254, 5034, 389, 869, 2227, 1769, 203, 377, 203, 565, 871, 22023, 12, 11890, 5034, 8808, 389, 13957, 16, 1758, 8808, 389, 2867, 16, 1731, 23, 2701, 1769, 203, 203, 565, 871, 21628, 2093, 12, 203, 3639, 1758, 8808, 389, 2867, 16, 203, 3639, 2254, 5034, 8808, 389, 13957, 16, 203, 3639, 2254, 28, 389, 8436, 16, 203, 3639, 1731, 23, 389, 70, 278, 16, 203, 3639, 2254, 5034, 389, 957, 203, 565, 11272, 203, 377, 203, 565, 871, 605, 278, 16507, 350, 12, 203, 3639, 1758, 8808, 389, 2867, 16, 203, 3639, 2254, 5034, 8808, 389, 13957, 16, 203, 3639, 2254, 28, 389, 8436, 16, 203, 3639, 1731, 23, 389, 70, 278, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 957, 203, 565, 11272, 203, 377, 203, 565, 871, 804, 484, 13130, 12, 203, 3639, 1758, 8808, 389, 2867, 16, 203, 3639, 2254, 5034, 8808, 389, 13957, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 957, 203, 565, 11272, 203, 377, 203, 565, 871, 9040, 5918, 858, 1988, 1224, 12, 203, 3639, 1758, 8808, 389, 31993, 16, 203, 3639, 1758, 8808, 389, 2 ]
./full_match/4/0x53cD729B185c4B37c4935eD2EAE62B3D8976BB72/sources/MyNFT.sol
max total for public mint
uint256 public maxQtyPerWalletAddressPublicSale = 1000;
674,109
[ 1, 1896, 2078, 364, 1071, 312, 474, 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, 2254, 5034, 1071, 943, 53, 4098, 2173, 16936, 1887, 4782, 30746, 273, 4336, 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 ]
// Be name Khoda // Bime Abolfazl // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.13; pragma abicoder v2; // ================================================================================================================= // _|_|_| _|_|_|_| _| _| _|_|_| _|_|_|_| _| | // _| _| _| _| _| _| _| _|_|_| _|_|_| _|_|_| _|_|_| _|_| | // _| _| _|_|_| _| _| _|_| _|_|_| _| _| _| _| _| _| _| _| _|_|_|_| | // _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| | // _|_|_| _|_|_|_| _|_| _|_|_| _| _| _| _| _|_|_| _| _| _|_|_| _|_|_| | // ================================================================================================================= // ============================= DEIPool ============================= // =================================================================== // DEUS Finance: https://github.com/DeusFinance // Primary Author(s) // Vahid: https://github.com/vahid-dev import "@openzeppelin/contracts/access/AccessControl.sol"; import "../Uniswap/TransferHelper.sol"; import "./interfaces/IPoolLibrary.sol"; import "./interfaces/IPoolV2.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IDEUS.sol"; import "./interfaces/IDEI.sol"; /// @title Minter Pool Contract V2 /// @author DEUS Finance /// @notice Minter pool of DEI stablecoin /// @dev Uses twap and vwap for DEUS price in DEI redemption by using muon oracles /// Usable for stablecoins as collateral contract DEIPool is IDEIPool, AccessControl { /* ========== STATE VARIABLES ========== */ address public collateral; address private dei; address private deus; uint256 public mintingFee; uint256 public redemptionFee = 10000; uint256 public buybackFee = 5000; uint256 public recollatFee = 5000; mapping(address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; mapping(address => uint256) public lastCollateralRedeemed; // position data mapping(address => IDEIPool.RedeemPosition[]) public redeemPositions; mapping(address => uint256) public nextRedeemId; uint256 public collateralRedemptionDelay; uint256 public deusRedemptionDelay; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; uint256 private constant COLLATERAL_PRICE = 1e6; uint256 private constant SCALE = 1e6; // Number of decimals needed to get to 18 uint256 private immutable missingDecimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public poolCeiling; // Bonus rate on DEUS minted during RecollateralizeDei(); 6 decimals of precision, set to 0.75% on genesis uint256 public bonusRate = 7500; uint256 public daoShare = 0; // fees goes to daoWallet address public poolLibrary; // Pool library contract address public muon; uint32 public appId; uint256 minimumRequiredSignatures; // AccessControl Roles bytes32 public constant PARAMETER_SETTER_ROLE = keccak256("PARAMETER_SETTER_ROLE"); bytes32 public constant DAO_SHARE_COLLECTOR = keccak256("DAO_SHARE_COLLECTOR"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant TRUSTY_ROLE = keccak256("TRUSTY_ROLE"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; /* ========== MODIFIERS ========== */ modifier notRedeemPaused() { require(redeemPaused == false, "DEIPool: REDEEM_PAUSED"); _; } modifier notMintPaused() { require(mintPaused == false, "DEIPool: MINTING_PAUSED"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address dei_, address deus_, address collateral_, address muon_, address library_, address admin, uint256 minimumRequiredSignatures_, uint256 collateralRedemptionDelay_, uint256 deusRedemptionDelay_, uint256 poolCeiling_, uint32 appId_ ) { require( (dei_ != address(0)) && (deus_ != address(0)) && (collateral_ != address(0)) && (library_ != address(0)) && (admin != address(0)), "DEIPool: ZERO_ADDRESS_DETECTED" ); dei = dei_; deus = deus_; collateral = collateral_; muon = muon_; appId = appId_; minimumRequiredSignatures = minimumRequiredSignatures_; collateralRedemptionDelay = collateralRedemptionDelay_; deusRedemptionDelay = deusRedemptionDelay_; poolCeiling = poolCeiling_; poolLibrary = library_; missingDecimals = uint256(18) - IERC20(collateral).decimals(); _setupRole(DEFAULT_ADMIN_ROLE, admin); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this DEI pool function collatDollarBalance(uint256 collateralPrice) public view returns (uint256 balance) { balance = ((IERC20(collateral).balanceOf(address(this)) - unclaimedPoolCollateral) * (10**missingDecimals) * collateralPrice) / (PRICE_PRECISION); } // Returns the value of excess collateral held in this DEI pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV(uint256[] memory collateralPrice) public view returns (uint256) { uint256 totalSupply = IDEI(dei).totalSupply(); uint256 globalCollateralRatio = IDEI(dei).global_collateral_ratio(); uint256 globalCollateralValue = IDEI(dei).globalCollateralValue( collateralPrice ); if (globalCollateralRatio > COLLATERAL_RATIO_PRECISION) globalCollateralRatio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 requiredCollateralDollarValued18 = (totalSupply * globalCollateralRatio) / (COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 DEI with $1 of collateral at current collat ratio if (globalCollateralValue > requiredCollateralDollarValued18) return globalCollateralValue - requiredCollateralDollarValued18; else return 0; } function positionsLength(address user) external view returns (uint256 length) { length = redeemPositions[user].length; } function getAllPositions(address user) external view returns (RedeemPosition[] memory positions) { positions = redeemPositions[user]; } function getUnRedeemedPositions(address user) external view returns (RedeemPosition[] memory) { uint256 totalRedeemPositions = redeemPositions[user].length; uint256 redeemId = nextRedeemId[user]; RedeemPosition[] memory positions = new RedeemPosition[]( totalRedeemPositions - redeemId + 1 ); uint256 index = 0; for (uint256 i = redeemId; i < totalRedeemPositions; i++) { positions[index] = redeemPositions[user][i]; index++; } return positions; } function _getChainId() internal view returns (uint256 id) { assembly { id := chainid() } } /* ========== PUBLIC FUNCTIONS ========== */ // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1DEI(uint256 collateralAmount) external notMintPaused returns (uint256 deiAmount) { require( IDEI(dei).global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "DEIPool: INVALID_COLLATERAL_RATIO" ); require( IERC20(collateral).balanceOf(address(this)) - unclaimedPoolCollateral + collateralAmount <= poolCeiling, "DEIPool: CEILING_REACHED" ); uint256 collateralAmountD18 = collateralAmount * (10**missingDecimals); deiAmount = IPoolLibrary(poolLibrary).calcMint1t1DEI( COLLATERAL_PRICE, collateralAmountD18 ); //1 DEI for each $1 worth of collateral deiAmount = (deiAmount * (SCALE - mintingFee)) / SCALE; //remove precision at the end TransferHelper.safeTransferFrom( collateral, msg.sender, address(this), collateralAmount ); daoShare += (deiAmount * mintingFee) / SCALE; IDEI(dei).pool_mint(msg.sender, deiAmount); } // 0% collateral-backed function mintAlgorithmicDEI( uint256 deusAmount, uint256 deusPrice, uint256 expireBlock, bytes[] calldata sigs ) external notMintPaused returns (uint256 deiAmount) { require( IDEI(dei).global_collateral_ratio() == 0, "DEIPool: INVALID_COLLATERAL_RATIO" ); require(expireBlock >= block.number, "DEIPool: EXPIRED_SIGNATURE"); bytes32 sighash = keccak256( abi.encodePacked(deus, deusPrice, expireBlock, _getChainId()) ); require( IDEI(dei).verify_price(sighash, sigs), "DEIPool: UNVERIFIED_SIGNATURE" ); deiAmount = IPoolLibrary(poolLibrary).calcMintAlgorithmicDEI( deusPrice, // X DEUS / 1 USD deusAmount ); deiAmount = (deiAmount * (SCALE - (mintingFee))) / SCALE; daoShare += (deiAmount * mintingFee) / SCALE; IDEUS(deus).pool_burn_from(msg.sender, deusAmount); IDEI(dei).pool_mint(msg.sender, deiAmount); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalDEI( uint256 collateralAmount, uint256 deusAmount, uint256 deusPrice, uint256 expireBlock, bytes[] calldata sigs ) external notMintPaused returns (uint256 mintAmount) { uint256 globalCollateralRatio = IDEI(dei).global_collateral_ratio(); require( globalCollateralRatio < COLLATERAL_RATIO_MAX && globalCollateralRatio > 0, "DEIPool: INVALID_COLLATERAL_RATIO" ); require( IERC20(collateral).balanceOf(address(this)) - unclaimedPoolCollateral + collateralAmount <= poolCeiling, "DEIPool: CEILING_REACHED" ); require(expireBlock >= block.number, "DEIPool: EXPIRED_SIGNATURE"); bytes32 sighash = keccak256( abi.encodePacked(deus, deusPrice, expireBlock, _getChainId()) ); require( IDEI(dei).verify_price(sighash, sigs), "DEIPool: UNVERIFIED_SIGNATURE" ); IPoolLibrary.MintFractionalDeiParams memory inputParams; // Blocking is just for solving stack depth problem { uint256 collateralAmountD18 = collateralAmount * (10**missingDecimals); inputParams = IPoolLibrary.MintFractionalDeiParams( deusPrice, COLLATERAL_PRICE, collateralAmountD18, globalCollateralRatio ); } uint256 deusNeeded; (mintAmount, deusNeeded) = IPoolLibrary(poolLibrary) .calcMintFractionalDEI(inputParams); require(deusNeeded <= deusAmount, "INSUFFICIENT_DEUS_INPUTTED"); mintAmount = (mintAmount * (SCALE - mintingFee)) / SCALE; IDEUS(deus).pool_burn_from(msg.sender, deusNeeded); TransferHelper.safeTransferFrom( collateral, msg.sender, address(this), collateralAmount ); daoShare += (mintAmount * mintingFee) / SCALE; IDEI(dei).pool_mint(msg.sender, mintAmount); } // Redeem collateral. 100% collateral-backed function redeem1t1DEI(uint256 deiAmount) external notRedeemPaused { require( IDEI(dei).global_collateral_ratio() == COLLATERAL_RATIO_MAX, "DEIPool: INVALID_COLLATERAL_RATIO" ); // Need to adjust for decimals of collateral uint256 deiAmountPrecision = deiAmount / (10**missingDecimals); uint256 collateralNeeded = IPoolLibrary(poolLibrary).calcRedeem1t1DEI( COLLATERAL_PRICE, deiAmountPrecision ); collateralNeeded = (collateralNeeded * (SCALE - redemptionFee)) / SCALE; require( collateralNeeded <= IERC20(collateral).balanceOf(address(this)) - unclaimedPoolCollateral, "DEIPool: INSUFFICIENT_COLLATERAL_BALANCE" ); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender] + collateralNeeded; unclaimedPoolCollateral = unclaimedPoolCollateral + collateralNeeded; lastCollateralRedeemed[msg.sender] = block.number; daoShare += (deiAmount * redemptionFee) / SCALE; // Move all external functions to the end IDEI(dei).pool_burn_from(msg.sender, deiAmount); } // Will fail if fully collateralized or algorithmic // Redeem DEI for collateral and DEUS. > 0% and < 100% collateral-backed function redeemFractionalDEI(uint256 deiAmount) external notRedeemPaused { uint256 globalCollateralRatio = IDEI(dei).global_collateral_ratio(); require( globalCollateralRatio < COLLATERAL_RATIO_MAX && globalCollateralRatio > 0, "DEIPool: INVALID_COLLATERAL_RATIO" ); // Blocking is just for solving stack depth problem uint256 collateralAmount; { uint256 deiAmountPostFee = (deiAmount * (SCALE - redemptionFee)) / (PRICE_PRECISION); uint256 deiAmountPrecision = deiAmountPostFee / (10**missingDecimals); collateralAmount = (deiAmountPrecision * globalCollateralRatio) / PRICE_PRECISION; } require( collateralAmount <= IERC20(collateral).balanceOf(address(this)) - unclaimedPoolCollateral, "DEIPool: NOT_ENOUGH_COLLATERAL" ); redeemCollateralBalances[msg.sender] += collateralAmount; lastCollateralRedeemed[msg.sender] = block.timestamp; unclaimedPoolCollateral = unclaimedPoolCollateral + collateralAmount; { uint256 deiAmountPostFee = (deiAmount * (SCALE - redemptionFee)) / SCALE; uint256 deusDollarAmount = (deiAmountPostFee * (SCALE - globalCollateralRatio)) / SCALE; redeemPositions[msg.sender].push( RedeemPosition({ amount: deusDollarAmount, timestamp: block.timestamp }) ); } daoShare += (deiAmount * redemptionFee) / SCALE; IDEI(dei).pool_burn_from(msg.sender, deiAmount); } // Redeem DEI for DEUS. 0% collateral-backed function redeemAlgorithmicDEI(uint256 deiAmount) external notRedeemPaused { require( IDEI(dei).global_collateral_ratio() == 0, "DEIPool: INVALID_COLLATERAL_RATIO" ); uint256 deusDollarAmount = (deiAmount * (SCALE - redemptionFee)) / (PRICE_PRECISION); redeemPositions[msg.sender].push( RedeemPosition({ amount: deusDollarAmount, timestamp: block.timestamp }) ); daoShare += (deiAmount * redemptionFee) / SCALE; IDEI(dei).pool_burn_from(msg.sender, deiAmount); } function collectCollateral() external { require( (lastCollateralRedeemed[msg.sender] + collateralRedemptionDelay) <= block.timestamp, "DEIPool: COLLATERAL_REDEMPTION_DELAY" ); if (redeemCollateralBalances[msg.sender] > 0) { uint256 collateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; TransferHelper.safeTransfer( collateral, msg.sender, collateralAmount ); unclaimedPoolCollateral = unclaimedPoolCollateral - collateralAmount; } } function collectDeus( uint256 price, bytes calldata _reqId, SchnorrSign[] calldata sigs ) external { require( sigs.length >= minimumRequiredSignatures, "DEIPool: INSUFFICIENT_SIGNATURES" ); uint256 redeemId = nextRedeemId[msg.sender]++; require( redeemPositions[msg.sender][redeemId].timestamp + deusRedemptionDelay <= block.timestamp, "DEIPool: DEUS_REDEMPTION_DELAY" ); { bytes32 hash = keccak256( abi.encodePacked( appId, msg.sender, redeemId, price, _getChainId() ) ); require( IMuonV02(muon).verify(_reqId, uint256(hash), sigs), "DEIPool: UNVERIFIED_SIGNATURES" ); } uint256 deusAmount = (redeemPositions[msg.sender][redeemId].amount * 1e18) / price; IDEUS(deus).pool_mint(msg.sender, deusAmount); } // When the protocol is recollateralizing, we need to give a discount of DEUS to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get DEUS for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of DEUS + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra DEUS value from the bonus rate as an arb opportunity function RecollateralizeDei(RecollateralizeDeiParams memory inputs) external { require( recollateralizePaused == false, "DEIPool: RECOLLATERALIZE_PAUSED" ); require( inputs.expireBlock >= block.number, "DEIPool: EXPIRE_SIGNATURE" ); bytes32 sighash = keccak256( abi.encodePacked( deus, inputs.deusPrice, inputs.expireBlock, _getChainId() ) ); require( IDEI(dei).verify_price(sighash, inputs.sigs), "DEIPool: UNVERIFIED_SIGNATURES" ); uint256 collateralAmountD18 = inputs.collateralAmount * (10**missingDecimals); uint256 deiTotalSupply = IDEI(dei).totalSupply(); uint256 globalCollateralRatio = IDEI(dei).global_collateral_ratio(); uint256 globalCollateralValue = IDEI(dei).globalCollateralValue( inputs.collateralPrice ); (uint256 collateralUnits, uint256 amountToRecollat) = IPoolLibrary( poolLibrary ).calcRecollateralizeDEIInner( collateralAmountD18, inputs.collateralPrice[inputs.collateralPrice.length - 1], // pool collateral price exist in last index globalCollateralValue, deiTotalSupply, globalCollateralRatio ); uint256 collateralUnitsPrecision = collateralUnits / (10**missingDecimals); uint256 deusPaidBack = (amountToRecollat * (SCALE + bonusRate - recollatFee)) / inputs.deusPrice; TransferHelper.safeTransferFrom( collateral, msg.sender, address(this), collateralUnitsPrecision ); IDEUS(deus).pool_mint(msg.sender, deusPaidBack); } // Function can be called by an DEUS holder to have the protocol buy back DEUS with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackDeus( uint256 deusAmount, uint256[] memory collateralPrice, uint256 deusPrice, uint256 expireBlock, bytes[] calldata sigs ) external { require(buyBackPaused == false, "DEIPool: BUYBACK_PAUSED"); require(expireBlock >= block.number, "DEIPool: EXPIRED_SIGNATURE"); bytes32 sighash = keccak256( abi.encodePacked( collateral, collateralPrice, deus, deusPrice, expireBlock, _getChainId() ) ); require( IDEI(dei).verify_price(sighash, sigs), "DEIPool: UNVERIFIED_SIGNATURE" ); IPoolLibrary.BuybackDeusParams memory inputParams = IPoolLibrary .BuybackDeusParams( availableExcessCollatDV(collateralPrice), deusPrice, collateralPrice[collateralPrice.length - 1], // pool collateral price exist in last index deusAmount ); uint256 collateralEquivalentD18 = (IPoolLibrary(poolLibrary) .calcBuyBackDEUS(inputParams) * (SCALE - buybackFee)) / SCALE; uint256 collateralPrecision = collateralEquivalentD18 / (10**missingDecimals); // Give the sender their desired collateral and burn the DEUS IDEUS(deus).pool_burn_from(msg.sender, deusAmount); TransferHelper.safeTransfer( collateral, msg.sender, collateralPrecision ); } /* ========== RESTRICTED FUNCTIONS ========== */ function collectDaoShare(uint256 amount, address to) external onlyRole(DAO_SHARE_COLLECTOR) { require(amount <= daoShare, "DEIPool: INVALID_AMOUNT"); IDEI(dei).pool_mint(to, amount); daoShare -= amount; emit daoShareCollected(amount, to); } function emergencyWithdrawERC20( address token, uint256 amount, address to ) external onlyRole(TRUSTY_ROLE) { IERC20(token).transfer(to, amount); } function toggleMinting() external onlyRole(PAUSER_ROLE) { mintPaused = !mintPaused; emit MintingToggled(mintPaused); } function toggleRedeeming() external onlyRole(PAUSER_ROLE) { redeemPaused = !redeemPaused; emit RedeemingToggled(redeemPaused); } function toggleRecollateralize() external onlyRole(PAUSER_ROLE) { recollateralizePaused = !recollateralizePaused; emit RecollateralizeToggled(recollateralizePaused); } function toggleBuyBack() external onlyRole(PAUSER_ROLE) { buyBackPaused = !buyBackPaused; emit BuybackToggled(buyBackPaused); } // Combined into one function due to 24KiB contract memory limit function setPoolParameters( uint256 poolCeiling_, uint256 bonusRate_, uint256 collateralRedemptionDelay_, uint256 deusRedemptionDelay_, uint256 mintingFee_, uint256 redemptionFee_, uint256 buybackFee_, uint256 recollatFee_, address muon_, uint32 appId_, uint256 minimumRequiredSignatures_ ) external onlyRole(PARAMETER_SETTER_ROLE) { poolCeiling = poolCeiling_; bonusRate = bonusRate_; collateralRedemptionDelay = collateralRedemptionDelay_; deusRedemptionDelay = deusRedemptionDelay_; mintingFee = mintingFee_; redemptionFee = redemptionFee_; buybackFee = buybackFee_; recollatFee = recollatFee_; muon = muon_; appId = appId_; minimumRequiredSignatures = minimumRequiredSignatures_; emit PoolParametersSet( poolCeiling_, bonusRate_, collateralRedemptionDelay_, deusRedemptionDelay_, mintingFee_, redemptionFee_, buybackFee_, recollatFee_, muon_, appId_, minimumRequiredSignatures_ ); } } //Dar panah khoda // 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 pragma solidity >=0.6.11; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: GPL-3.0-or-later interface IPoolLibrary { struct MintFractionalDeiParams { uint256 deusPrice; uint256 collateralPrice; uint256 collateralAmount; uint256 collateralRatio; } struct BuybackDeusParams { uint256 excessCollateralValueD18; uint256 deusPrice; uint256 collateralPrice; uint256 deusAmount; } function calcMint1t1DEI(uint256 col_price, uint256 collateral_amount_d18) external pure returns (uint256); function calcMintAlgorithmicDEI( uint256 deus_price_usd, uint256 deus_amount_d18 ) external pure returns (uint256); function calcMintFractionalDEI(MintFractionalDeiParams memory params) external pure returns (uint256, uint256); function calcRedeem1t1DEI(uint256 col_price_usd, uint256 DEI_amount) external pure returns (uint256); function calcBuyBackDEUS(BuybackDeusParams memory params) external pure returns (uint256); function recollateralizeAmount( uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value ) external pure returns (uint256); function calcRecollateralizeDEIInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 dei_total_supply, uint256 global_collateral_ratio ) external pure returns (uint256, uint256); } // SPDX-License-Identifier: MIT // ================================================================================================================= // _|_|_| _|_|_|_| _| _| _|_|_| _|_|_|_| _| | // _| _| _| _| _| _| _| _|_|_| _|_|_| _|_|_| _|_|_| _|_| | // _| _| _|_|_| _| _| _|_| _|_|_| _| _| _| _| _| _| _| _| _|_|_|_| | // _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _| | // _|_|_| _|_|_|_| _|_| _|_|_| _| _| _| _| _|_|_| _| _| _|_|_| _|_|_| | // ================================================================================================================= // ============================= Oracle ============================= // ================================================================== // DEUS Finance: https://github.com/DeusFinance // Primary Author(s) // Sina: https://github.com/spsina // Vahid: https://github.com/vahid-dev import "./IMuonV02.sol"; interface IDEIPool { struct RecollateralizeDeiParams { uint256 collateralAmount; uint256 poolCollateralPrice; uint256[] collateralPrice; uint256 deusPrice; uint256 expireBlock; bytes[] sigs; } struct RedeemPosition { uint256 amount; uint256 timestamp; } /* ========== PUBLIC VIEWS ========== */ function collatDollarBalance(uint256 collateralPrice) external view returns (uint256 balance); function positionsLength(address user) external view returns (uint256 length); function getAllPositions(address user) external view returns (RedeemPosition[] memory positinos); function getUnRedeemedPositions(address user) external view returns (RedeemPosition[] memory positions); function mint1t1DEI(uint256 collateralAmount) external returns (uint256 deiAmount); function mintAlgorithmicDEI( uint256 deusAmount, uint256 deusPrice, uint256 expireBlock, bytes[] calldata sigs ) external returns (uint256 deiAmount); function mintFractionalDEI( uint256 collateralAmount, uint256 deusAmount, uint256 deusPrice, uint256 expireBlock, bytes[] calldata sigs ) external returns (uint256 mintAmount); function redeem1t1DEI(uint256 deiAmount) external; function redeemFractionalDEI(uint256 deiAmount) external; function redeemAlgorithmicDEI(uint256 deiAmount) external; function collectCollateral() external; function collectDeus( uint256 price, bytes calldata _reqId, SchnorrSign[] calldata sigs ) external; function RecollateralizeDei(RecollateralizeDeiParams memory inputs) external; function buyBackDeus( uint256 deusAmount, uint256[] memory collateralPrice, uint256 deusPrice, uint256 expireBlock, bytes[] calldata sigs ) external; /* ========== RESTRICTED FUNCTIONS ========== */ function collectDaoShare(uint256 amount, address to) external; function emergencyWithdrawERC20( address token, uint256 amount, address to ) external; function toggleMinting() external; function toggleRedeeming() external; function toggleRecollateralize() external; function toggleBuyBack() external; function setPoolParameters( uint256 poolCeiling_, uint256 bonusRate_, uint256 collateralRedemptionDelay_, uint256 deusRedemptionDelay_, uint256 mintingFee_, uint256 redemptionFee_, uint256 buybackFee_, uint256 recollatFee_, address muon_, uint32 appId_, uint256 minimumRequiredSignatures_ ) external; /* ========== EVENTS ========== */ event PoolParametersSet( uint256 poolCeiling, uint256 bonusRate, uint256 collateralRedemptionDelay, uint256 deusRedemptionDelay, uint256 mintingFee, uint256 redemptionFee, uint256 buybackFee, uint256 recollatFee, address muon, uint32 appId, uint256 minimumRequiredSignatures ); event daoShareCollected(uint256 daoShare, address to); event MintingToggled(bool toggled); event RedeemingToggled(bool toggled); event RecollateralizeToggled(bool toggled); event BuybackToggled(bool toggled); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); function decimals() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address from, address to, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later interface IDEUS { function name() external view returns (string memory); function symbol() external view returns (string memory); function pool_burn_from(address b_address, uint256 b_amount) external; function pool_mint(address m_address, uint256 m_amount) external; function mint(address to, uint256 amount) external; function setDEIAddress(address dei_contract_address) external; function setNameAndSymbol(string memory _name, string memory _symbol) external; } // SPDX-License-Identifier: GPL-3.0-or-later interface IDEI { function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function global_collateral_ratio() external view returns (uint256); function dei_pools(address _address) external view returns (bool); function dei_pools_array() external view returns (address[] memory); function verify_price(bytes32 sighash, bytes[] calldata sigs) external view returns (bool); function dei_info(uint256[] memory collat_usd_price) external view returns (uint256, uint256, uint256); function getChainID() external view returns (uint256); function globalCollateralValue(uint256[] memory collat_usd_price) external view returns (uint256); function refreshCollateralRatio(uint deus_price, uint dei_price, uint256 expire_block, bytes[] calldata sigs) external; function useGrowthRatio(bool _use_growth_ratio) external; function setGrowthRatioBands(uint256 _GR_top_band, uint256 _GR_bottom_band) external; function setPriceBands(uint256 _top_band, uint256 _bottom_band) external; function activateDIP(bool _activate) external; function pool_burn_from(address b_address, uint256 b_amount) external; function pool_mint(address m_address, uint256 m_amount) external; function addPool(address pool_address) external; function removePool(address pool_address) external; function setNameAndSymbol(string memory _name, string memory _symbol) external; function setOracle(address _oracle) external; function setDEIStep(uint256 _new_step) external; function setReserveTracker(address _reserve_tracker_address) external; function setRefreshCooldown(uint256 _new_cooldown) external; function setDEUSAddress(address _deus_address) external; function toggleCollateralRatio() external; } // 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/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); } // SPDX-License-Identifier: GPL-3.0 struct SchnorrSign { uint256 signature; address owner; address nonce; } interface IMuonV02 { function verify( bytes calldata reqId, uint256 hash, SchnorrSign[] calldata _sigs ) external returns (bool); }
When the protocol is recollateralizing, we need to give a discount of DEUS to hit the new CR target Thus, if the target collateral ratio is higher than the actual value of collateral, minters get DEUS for adding collateral This function simply rewards anyone that sends collateral to a pool with the same amount of DEUS + the bonus rate Anyone can call this function to recollateralize the protocol and take the extra DEUS value from the bonus rate as an arb opportunity
function RecollateralizeDei(RecollateralizeDeiParams memory inputs) external { require( recollateralizePaused == false, "DEIPool: RECOLLATERALIZE_PAUSED" ); require( inputs.expireBlock >= block.number, "DEIPool: EXPIRE_SIGNATURE" ); bytes32 sighash = keccak256( abi.encodePacked( deus, inputs.deusPrice, inputs.expireBlock, _getChainId() ) ); require( IDEI(dei).verify_price(sighash, inputs.sigs), "DEIPool: UNVERIFIED_SIGNATURES" ); uint256 collateralAmountD18 = inputs.collateralAmount * (10**missingDecimals); uint256 deiTotalSupply = IDEI(dei).totalSupply(); uint256 globalCollateralRatio = IDEI(dei).global_collateral_ratio(); uint256 globalCollateralValue = IDEI(dei).globalCollateralValue( inputs.collateralPrice ); (uint256 collateralUnits, uint256 amountToRecollat) = IPoolLibrary( poolLibrary ).calcRecollateralizeDEIInner( collateralAmountD18, globalCollateralValue, deiTotalSupply, globalCollateralRatio ); uint256 collateralUnitsPrecision = collateralUnits / (10**missingDecimals); uint256 deusPaidBack = (amountToRecollat * (SCALE + bonusRate - recollatFee)) / inputs.deusPrice; TransferHelper.safeTransferFrom( collateral, msg.sender, address(this), collateralUnitsPrecision ); IDEUS(deus).pool_mint(msg.sender, deusPaidBack); }
9,929,601
[ 1, 9434, 326, 1771, 353, 283, 12910, 2045, 287, 6894, 16, 732, 1608, 358, 8492, 279, 12137, 434, 2030, 3378, 358, 6800, 326, 394, 6732, 1018, 22073, 16, 309, 326, 1018, 4508, 2045, 287, 7169, 353, 10478, 2353, 326, 3214, 460, 434, 4508, 2045, 287, 16, 1131, 5432, 336, 2030, 3378, 364, 6534, 4508, 2045, 287, 1220, 445, 8616, 283, 6397, 1281, 476, 716, 9573, 4508, 2045, 287, 358, 279, 2845, 598, 326, 1967, 3844, 434, 2030, 3378, 397, 326, 324, 22889, 4993, 5502, 476, 848, 745, 333, 445, 358, 283, 12910, 2045, 287, 554, 326, 1771, 471, 4862, 326, 2870, 2030, 3378, 460, 628, 326, 324, 22889, 4993, 487, 392, 419, 70, 1061, 655, 13352, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 868, 12910, 2045, 287, 554, 758, 77, 12, 426, 12910, 2045, 287, 554, 758, 77, 1370, 3778, 4540, 13, 203, 3639, 3903, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 283, 12910, 2045, 287, 554, 28590, 422, 629, 16, 203, 5411, 315, 1639, 2579, 1371, 30, 2438, 4935, 12190, 654, 1013, 15641, 67, 4066, 20093, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 4540, 18, 14070, 1768, 1545, 1203, 18, 2696, 16, 203, 5411, 315, 1639, 2579, 1371, 30, 31076, 862, 67, 26587, 6, 203, 3639, 11272, 203, 3639, 1731, 1578, 272, 2031, 961, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 443, 407, 16, 203, 7734, 4540, 18, 323, 407, 5147, 16, 203, 7734, 4540, 18, 14070, 1768, 16, 203, 7734, 389, 588, 3893, 548, 1435, 203, 5411, 262, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1599, 41, 45, 12, 323, 77, 2934, 8705, 67, 8694, 12, 87, 2031, 961, 16, 4540, 18, 7340, 87, 3631, 203, 5411, 315, 1639, 2579, 1371, 30, 5019, 2204, 13519, 67, 26587, 55, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 4508, 2045, 287, 6275, 40, 2643, 273, 4540, 18, 12910, 2045, 287, 6275, 380, 203, 5411, 261, 2163, 636, 7337, 31809, 1769, 203, 203, 3639, 2254, 5034, 443, 77, 5269, 3088, 1283, 273, 1599, 41, 45, 12, 323, 77, 2934, 4963, 3088, 1283, 5621, 203, 3639, 2254, 5034, 2552, 13535, 2045, 287, 8541, 273, 1599, 41, 45, 12, 323, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-03-17 */ /* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: DebtCache.sol * * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/DebtCache.sol * Docs: https://docs.synthetix.io/contracts/DebtCache * * Contract Dependencies: * - BaseDebtCache * - IAddressResolver * - IDebtCache * - MixinResolver * - MixinSystemSettings * - Owned * Libraries: * - SafeDecimalMath * - SafeMath * * MIT License * =========== * * Copyright (c) 2022 Synthetix * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Libraries // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } // Computes `a - b`, setting the value to 0 if b > a. function floorsub(uint a, uint b) internal pure returns (uint) { return b >= a ? 0 : a - b; } /* ---------- Utilities ---------- */ /* * Absolute value of the input, returned as a signed number. */ function signedAbs(int x) internal pure returns (int) { return x < 0 ? -x : x; } /* * Absolute value of the input, returned as an unsigned number. */ function abs(int x) internal pure returns (uint) { return uint(signedAbs(x)); } } // https://docs.synthetix.io/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } // https://docs.synthetix.io/contracts/source/interfaces/iissuer interface IIssuer { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function canBurnSynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function issuanceRatio() external view returns (uint); function lastIssueEvent(address account) external view returns (uint); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function minimumStakeTime() external view returns (uint); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint); function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid); // Restricted: used internally to Synthetix function issueSynths(address from, uint amount) external; function issueSynthsOnBehalf( address issueFor, address from, uint amount ) external; function issueMaxSynths(address from) external; function issueMaxSynthsOnBehalf(address issueFor, address from) external; function burnSynths(address from, uint amount) external; function burnSynthsOnBehalf( address burnForAddress, address from, uint amount ) external; function burnSynthsToTarget(address from) external; function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external; function burnForRedemption( address deprecatedSynthProxy, address account, uint balance ) external; function liquidateDelinquentAccount( address account, uint susdAmount, address liquidator ) external returns (uint totalRedeemed, uint amountToLiquidate); function setCurrentPeriodId(uint128 periodId) external; } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/addressresolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(MixinResolver[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getSynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.synths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // Internal references // https://docs.synthetix.io/contracts/source/contracts/mixinresolver contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } // https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage interface IFlexibleStorage { // Views function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint); function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory); function getIntValue(bytes32 contractName, bytes32 record) external view returns (int); function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory); function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address); function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory); function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool); function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory); function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32); function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory); // Mutative functions function deleteUIntValue(bytes32 contractName, bytes32 record) external; function deleteIntValue(bytes32 contractName, bytes32 record) external; function deleteAddressValue(bytes32 contractName, bytes32 record) external; function deleteBoolValue(bytes32 contractName, bytes32 record) external; function deleteBytes32Value(bytes32 contractName, bytes32 record) external; function setUIntValue( bytes32 contractName, bytes32 record, uint value ) external; function setUIntValues( bytes32 contractName, bytes32[] calldata records, uint[] calldata values ) external; function setIntValue( bytes32 contractName, bytes32 record, int value ) external; function setIntValues( bytes32 contractName, bytes32[] calldata records, int[] calldata values ) external; function setAddressValue( bytes32 contractName, bytes32 record, address value ) external; function setAddressValues( bytes32 contractName, bytes32[] calldata records, address[] calldata values ) external; function setBoolValue( bytes32 contractName, bytes32 record, bool value ) external; function setBoolValues( bytes32 contractName, bytes32[] calldata records, bool[] calldata values ) external; function setBytes32Value( bytes32 contractName, bytes32 record, bytes32 value ) external; function setBytes32Values( bytes32 contractName, bytes32[] calldata records, bytes32[] calldata values ) external; } // Internal references // https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings contract MixinSystemSettings is MixinResolver { // must match the one defined SystemSettingsLib, defined in both places due to sol v0.5 limitations bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings"; bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs"; bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor"; bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio"; bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration"; bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold"; bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay"; bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio"; bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty"; bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod"; /* ========== Exchange Fees Related ========== */ bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate"; bytes32 internal constant SETTING_EXCHANGE_DYNAMIC_FEE_THRESHOLD = "exchangeDynamicFeeThreshold"; bytes32 internal constant SETTING_EXCHANGE_DYNAMIC_FEE_WEIGHT_DECAY = "exchangeDynamicFeeWeightDecay"; bytes32 internal constant SETTING_EXCHANGE_DYNAMIC_FEE_ROUNDS = "exchangeDynamicFeeRounds"; bytes32 internal constant SETTING_EXCHANGE_MAX_DYNAMIC_FEE = "exchangeMaxDynamicFee"; /* ========== End Exchange Fees Related ========== */ bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime"; bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags"; bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled"; bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime"; bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_FEE_PERIOD_CLOSE_GAS_LIMIT = "crossDomainCloseGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT = "crossDomainRelayGasLimit"; bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH"; bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate"; bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate"; bytes32 internal constant SETTING_WRAPPER_MAX_TOKEN_AMOUNT = "wrapperMaxTokens"; bytes32 internal constant SETTING_WRAPPER_MINT_FEE_RATE = "wrapperMintFeeRate"; bytes32 internal constant SETTING_WRAPPER_BURN_FEE_RATE = "wrapperBurnFeeRate"; bytes32 internal constant SETTING_INTERACTION_DELAY = "interactionDelay"; bytes32 internal constant SETTING_COLLAPSE_FEE_RATE = "collapseFeeRate"; bytes32 internal constant SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK = "atomicMaxVolumePerBlock"; bytes32 internal constant SETTING_ATOMIC_TWAP_WINDOW = "atomicTwapWindow"; bytes32 internal constant SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING = "atomicEquivalentForDexPricing"; bytes32 internal constant SETTING_ATOMIC_EXCHANGE_FEE_RATE = "atomicExchangeFeeRate"; bytes32 internal constant SETTING_ATOMIC_PRICE_BUFFER = "atomicPriceBuffer"; bytes32 internal constant SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW = "atomicVolConsiderationWindow"; bytes32 internal constant SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD = "atomicVolUpdateThreshold"; bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage"; enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal, CloseFeePeriod, Relay} struct DynamicFeeConfig { uint threshold; uint weightDecay; uint rounds; uint maxFee; } constructor(address _resolver) internal MixinResolver(_resolver) {} function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](1); addresses[0] = CONTRACT_FLEXIBLESTORAGE; } function flexibleStorage() internal view returns (IFlexibleStorage) { return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE)); } function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) { if (gasLimitType == CrossDomainMessageGasLimits.Deposit) { return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) { return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Reward) { return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) { return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Relay) { return SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.CloseFeePeriod) { return SETTING_CROSS_DOMAIN_FEE_PERIOD_CLOSE_GAS_LIMIT; } else { revert("Unknown gas limit type"); } } function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType)); } function getTradingRewardsEnabled() internal view returns (bool) { return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED); } function getWaitingPeriodSecs() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS); } function getPriceDeviationThresholdFactor() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR); } function getIssuanceRatio() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO); } function getFeePeriodDuration() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION); } function getTargetThreshold() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD); } function getLiquidationDelay() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY); } function getLiquidationRatio() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO); } function getLiquidationPenalty() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY); } function getRateStalePeriod() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD); } /* ========== Exchange Related Fees ========== */ function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey)) ); } /// @notice Get exchange dynamic fee related keys /// @return threshold, weight decay, rounds, and max fee function getExchangeDynamicFeeConfig() internal view returns (DynamicFeeConfig memory) { bytes32[] memory keys = new bytes32[](4); keys[0] = SETTING_EXCHANGE_DYNAMIC_FEE_THRESHOLD; keys[1] = SETTING_EXCHANGE_DYNAMIC_FEE_WEIGHT_DECAY; keys[2] = SETTING_EXCHANGE_DYNAMIC_FEE_ROUNDS; keys[3] = SETTING_EXCHANGE_MAX_DYNAMIC_FEE; uint[] memory values = flexibleStorage().getUIntValues(SETTING_CONTRACT_NAME, keys); return DynamicFeeConfig({threshold: values[0], weightDecay: values[1], rounds: values[2], maxFee: values[3]}); } /* ========== End Exchange Related Fees ========== */ function getMinimumStakeTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME); } function getAggregatorWarningFlags() internal view returns (address) { return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS); } function getDebtSnapshotStaleTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME); } function getEtherWrapperMaxETH() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH); } function getEtherWrapperMintFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE); } function getEtherWrapperBurnFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE); } function getWrapperMaxTokenAmount(address wrapper) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_MAX_TOKEN_AMOUNT, wrapper)) ); } function getWrapperMintFeeRate(address wrapper) internal view returns (int) { return flexibleStorage().getIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_MINT_FEE_RATE, wrapper)) ); } function getWrapperBurnFeeRate(address wrapper) internal view returns (int) { return flexibleStorage().getIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_BURN_FEE_RATE, wrapper)) ); } function getInteractionDelay(address collateral) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_INTERACTION_DELAY, collateral)) ); } function getCollapseFeeRate(address collateral) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_COLLAPSE_FEE_RATE, collateral)) ); } function getAtomicMaxVolumePerBlock() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK); } function getAtomicTwapWindow() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_TWAP_WINDOW); } function getAtomicEquivalentForDexPricing(bytes32 currencyKey) internal view returns (address) { return flexibleStorage().getAddressValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING, currencyKey)) ); } function getAtomicExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_EXCHANGE_FEE_RATE, currencyKey)) ); } function getAtomicPriceBuffer(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_PRICE_BUFFER, currencyKey)) ); } function getAtomicVolatilityConsiderationWindow(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW, currencyKey)) ); } function getAtomicVolatilityUpdateThreshold(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD, currencyKey)) ); } } interface IDebtCache { // Views function cachedDebt() external view returns (uint); function cachedSynthDebt(bytes32 currencyKey) external view returns (uint); function cacheTimestamp() external view returns (uint); function cacheInvalid() external view returns (bool); function cacheStale() external view returns (bool); function isInitialized() external view returns (bool); function currentSynthDebts(bytes32[] calldata currencyKeys) external view returns ( uint[] memory debtValues, uint futuresDebt, uint excludedDebt, bool anyRateIsInvalid ); function cachedSynthDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory debtValues); function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid); function currentDebt() external view returns (uint debt, bool anyRateIsInvalid); function cacheInfo() external view returns ( uint debt, uint timestamp, bool isInvalid, bool isStale ); function excludedIssuedDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory excludedDebts); // Mutative functions function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external; function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external; function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external; function updateDebtCacheValidity(bool currentlyInvalid) external; function purgeCachedSynthDebt(bytes32 currencyKey) external; function takeDebtSnapshot() external; function recordExcludedDebtChange(bytes32 currencyKey, int256 delta) external; function updateCachedsUSDDebt(int amount) external; function importExcludedIssuedDebts(IDebtCache prevDebtCache, IIssuer prevIssuer) external; } interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { struct ExchangeEntrySettlement { bytes32 src; uint amount; bytes32 dest; uint reclaim; uint rebate; uint srcRoundIdAtPeriodEnd; uint destRoundIdAtPeriodEnd; uint timestamp; } struct ExchangeEntry { uint sourceRate; uint destinationRate; uint destinationAmount; uint exchangeFeeRate; uint exchangeDynamicFeeRate; uint roundIdForSrc; uint roundIdForDest; } // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint); function dynamicFeeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint feeRate, bool tooVolatile); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); function lastExchangeRate(bytes32 currencyKey) external view returns (uint); // Mutative functions function exchange( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bool virtualSynth, address rewardAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function exchangeAtomically( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } // https://docs.synthetix.io/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function anyRateIsInvalidAtRound(bytes32[] calldata currencyKeys, uint[] calldata roundIds) external view returns (bool); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAndRatesAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveAtomicValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint systemValue, uint systemSourceRate, uint systemDestinationRate ); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds( bytes32 currencyKey, uint numRounds, uint roundId ) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); function synthTooVolatileForAtomicExchange(bytes32 currencyKey) external view returns (bool); } // https://docs.synthetix.io/contracts/source/interfaces/isystemstatus interface ISystemStatus { struct Status { bool canSuspend; bool canResume; } struct Suspension { bool suspended; // reason is an integer code, // 0 => no reason, 1 => upgrading, 2+ => defined by system usage uint248 reason; } // Views function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume); function requireSystemActive() external view; function systemSuspended() external view returns (bool); function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireFuturesActive() external view; function requireFuturesMarketActive(bytes32 marketKey) external view; function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function requireSynthActive(bytes32 currencyKey) external view; function synthSuspended(bytes32 currencyKey) external view returns (bool); function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function systemSuspension() external view returns (bool suspended, uint248 reason); function issuanceSuspension() external view returns (bool suspended, uint248 reason); function exchangeSuspension() external view returns (bool suspended, uint248 reason); function futuresSuspension() external view returns (bool suspended, uint248 reason); function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function futuresMarketSuspension(bytes32 marketKey) external view returns (bool suspended, uint248 reason); function getSynthExchangeSuspensions(bytes32[] calldata synths) external view returns (bool[] memory exchangeSuspensions, uint256[] memory reasons); function getSynthSuspensions(bytes32[] calldata synths) external view returns (bool[] memory suspensions, uint256[] memory reasons); function getFuturesMarketSuspensions(bytes32[] calldata marketKeys) external view returns (bool[] memory suspensions, uint256[] memory reasons); // Restricted functions function suspendIssuance(uint256 reason) external; function suspendSynth(bytes32 currencyKey, uint256 reason) external; function suspendFuturesMarket(bytes32 marketKey, uint256 reason) external; function updateAccessControl( bytes32 section, address account, bool canSuspend, bool canResume ) external; } // https://docs.synthetix.io/contracts/source/interfaces/ierc20 interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface ICollateralManager { // Manager information function hasCollateral(address collateral) external view returns (bool); function isSynthManaged(bytes32 currencyKey) external view returns (bool); // State information function long(bytes32 synth) external view returns (uint amount); function short(bytes32 synth) external view returns (uint amount); function totalLong() external view returns (uint susdValue, bool anyRateIsInvalid); function totalShort() external view returns (uint susdValue, bool anyRateIsInvalid); function getBorrowRate() external view returns (uint borrowRate, bool anyRateIsInvalid); function getShortRate(bytes32 synth) external view returns (uint shortRate, bool rateIsInvalid); function getRatesAndTime(uint index) external view returns ( uint entryRate, uint lastRate, uint lastUpdated, uint newIndex ); function getShortRatesAndTime(bytes32 currency, uint index) external view returns ( uint entryRate, uint lastRate, uint lastUpdated, uint newIndex ); function exceedsDebtLimit(uint amount, bytes32 currency) external view returns (bool canIssue, bool anyRateIsInvalid); function areSynthsAndCurrenciesSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys) external view returns (bool); function areShortableSynthsSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys) external view returns (bool); // Loans function getNewLoanId() external returns (uint id); // Manager mutative function addCollaterals(address[] calldata collaterals) external; function removeCollaterals(address[] calldata collaterals) external; function addSynths(bytes32[] calldata synthNamesInResolver, bytes32[] calldata synthKeys) external; function removeSynths(bytes32[] calldata synths, bytes32[] calldata synthKeys) external; function addShortableSynths(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys) external; function removeShortableSynths(bytes32[] calldata synths) external; // State mutative function incrementLongs(bytes32 synth, uint amount) external; function decrementLongs(bytes32 synth, uint amount) external; function incrementShorts(bytes32 synth, uint amount) external; function decrementShorts(bytes32 synth, uint amount) external; function accrueInterest( uint interestIndex, bytes32 currency, bool isShort ) external returns (uint difference, uint index); function updateBorrowRatesCollateral(uint rate) external; function updateShortRatesCollateral(bytes32 currency, uint rate) external; } interface IWETH { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // WETH-specific functions. function deposit() external payable; function withdraw(uint amount) external; // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); event Deposit(address indexed to, uint amount); event Withdrawal(address indexed to, uint amount); } // https://docs.synthetix.io/contracts/source/interfaces/ietherwrapper contract IEtherWrapper { function mint(uint amount) external; function burn(uint amount) external; function distributeFees() external; function capacity() external view returns (uint); function getReserves() external view returns (uint); function totalIssuedSynths() external view returns (uint); function calculateMintFee(uint amount) public view returns (uint); function calculateBurnFee(uint amount) public view returns (uint); function maxETH() public view returns (uint256); function mintFeeRate() public view returns (uint256); function burnFeeRate() public view returns (uint256); function weth() public view returns (IWETH); } // https://docs.synthetix.io/contracts/source/interfaces/iwrapperfactory interface IWrapperFactory { function isWrapper(address possibleWrapper) external view returns (bool); function createWrapper( IERC20 token, bytes32 currencyKey, bytes32 synthContractName ) external returns (address); function distributeFees() external; } interface IFuturesMarketManager { function markets(uint index, uint pageSize) external view returns (address[] memory); function numMarkets() external view returns (uint); function allMarkets() external view returns (address[] memory); function marketForKey(bytes32 marketKey) external view returns (address); function marketsForKeys(bytes32[] calldata marketKeys) external view returns (address[] memory); function totalDebt() external view returns (uint debt, bool isInvalid); } // Inheritance // Libraries // Internal references // https://docs.synthetix.io/contracts/source/contracts/debtcache contract BaseDebtCache is Owned, MixinSystemSettings, IDebtCache { using SafeMath for uint; using SafeDecimalMath for uint; uint internal _cachedDebt; mapping(bytes32 => uint) internal _cachedSynthDebt; mapping(bytes32 => uint) internal _excludedIssuedDebt; uint internal _cacheTimestamp; bool internal _cacheInvalid = true; // flag to ensure importing excluded debt is invoked only once bool public isInitialized = false; // public to avoid needing an event /* ========== ENCODED NAMES ========== */ bytes32 internal constant sUSD = "sUSD"; bytes32 internal constant sETH = "sETH"; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager"; bytes32 private constant CONTRACT_ETHER_WRAPPER = "EtherWrapper"; bytes32 private constant CONTRACT_FUTURESMARKETMANAGER = "FuturesMarketManager"; bytes32 private constant CONTRACT_WRAPPER_FACTORY = "WrapperFactory"; constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {} /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](8); newAddresses[0] = CONTRACT_ISSUER; newAddresses[1] = CONTRACT_EXCHANGER; newAddresses[2] = CONTRACT_EXRATES; newAddresses[3] = CONTRACT_SYSTEMSTATUS; newAddresses[4] = CONTRACT_COLLATERALMANAGER; newAddresses[5] = CONTRACT_WRAPPER_FACTORY; newAddresses[6] = CONTRACT_ETHER_WRAPPER; newAddresses[7] = CONTRACT_FUTURESMARKETMANAGER; addresses = combineArrays(existingAddresses, newAddresses); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function collateralManager() internal view returns (ICollateralManager) { return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER)); } function etherWrapper() internal view returns (IEtherWrapper) { return IEtherWrapper(requireAndGetAddress(CONTRACT_ETHER_WRAPPER)); } function futuresMarketManager() internal view returns (IFuturesMarketManager) { return IFuturesMarketManager(requireAndGetAddress(CONTRACT_FUTURESMARKETMANAGER)); } function wrapperFactory() internal view returns (IWrapperFactory) { return IWrapperFactory(requireAndGetAddress(CONTRACT_WRAPPER_FACTORY)); } function debtSnapshotStaleTime() external view returns (uint) { return getDebtSnapshotStaleTime(); } function cachedDebt() external view returns (uint) { return _cachedDebt; } function cachedSynthDebt(bytes32 currencyKey) external view returns (uint) { return _cachedSynthDebt[currencyKey]; } function cacheTimestamp() external view returns (uint) { return _cacheTimestamp; } function cacheInvalid() external view returns (bool) { return _cacheInvalid; } function _cacheStale(uint timestamp) internal view returns (bool) { // Note a 0 timestamp means that the cache is uninitialised. // We'll keep the check explicitly in case the stale time is // ever set to something higher than the current unix time (e.g. to turn off staleness). return getDebtSnapshotStaleTime() < block.timestamp - timestamp || timestamp == 0; } function cacheStale() external view returns (bool) { return _cacheStale(_cacheTimestamp); } function _issuedSynthValues(bytes32[] memory currencyKeys, uint[] memory rates) internal view returns (uint[] memory values) { uint numValues = currencyKeys.length; values = new uint[](numValues); ISynth[] memory synths = issuer().getSynths(currencyKeys); for (uint i = 0; i < numValues; i++) { address synthAddress = address(synths[i]); require(synthAddress != address(0), "Synth does not exist"); uint supply = IERC20(synthAddress).totalSupply(); values[i] = supply.multiplyDecimalRound(rates[i]); } return (values); } function _currentSynthDebts(bytes32[] memory currencyKeys) internal view returns ( uint[] memory snxIssuedDebts, uint _futuresDebt, uint _excludedDebt, bool anyRateIsInvalid ) { (uint[] memory rates, bool isInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys); uint[] memory values = _issuedSynthValues(currencyKeys, rates); (uint excludedDebt, bool isAnyNonSnxDebtRateInvalid) = _totalNonSnxBackedDebt(currencyKeys, rates, isInvalid); (uint futuresDebt, bool futuresDebtIsInvalid) = futuresMarketManager().totalDebt(); return (values, futuresDebt, excludedDebt, isInvalid || futuresDebtIsInvalid || isAnyNonSnxDebtRateInvalid); } function currentSynthDebts(bytes32[] calldata currencyKeys) external view returns ( uint[] memory debtValues, uint futuresDebt, uint excludedDebt, bool anyRateIsInvalid ) { return _currentSynthDebts(currencyKeys); } function _cachedSynthDebts(bytes32[] memory currencyKeys) internal view returns (uint[] memory) { uint numKeys = currencyKeys.length; uint[] memory debts = new uint[](numKeys); for (uint i = 0; i < numKeys; i++) { debts[i] = _cachedSynthDebt[currencyKeys[i]]; } return debts; } function cachedSynthDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory snxIssuedDebts) { return _cachedSynthDebts(currencyKeys); } function _excludedIssuedDebts(bytes32[] memory currencyKeys) internal view returns (uint[] memory) { uint numKeys = currencyKeys.length; uint[] memory debts = new uint[](numKeys); for (uint i = 0; i < numKeys; i++) { debts[i] = _excludedIssuedDebt[currencyKeys[i]]; } return debts; } function excludedIssuedDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory excludedDebts) { return _excludedIssuedDebts(currencyKeys); } /// used when migrating to new DebtCache instance in order to import the excluded debt records /// If this method is not run after upgrading the contract, the debt will be /// incorrect w.r.t to wrapper factory assets until the values are imported from /// previous instance of the contract /// Also, in addition to this method it's possible to use recordExcludedDebtChange since /// it's accessible to owner in case additional adjustments are required function importExcludedIssuedDebts(IDebtCache prevDebtCache, IIssuer prevIssuer) external onlyOwner { // this can only be run once so that recorded debt deltas aren't accidentally // lost or double counted require(!isInitialized, "already initialized"); isInitialized = true; // get the currency keys from **previous** issuer, in case current issuer // doesn't have all the synths at this point // warning: if a synth won't be added to the current issuer before the next upgrade of this contract, // its entry will be lost (because it won't be in the prevIssuer for next time). // if for some reason this is a problem, it should be possible to use recordExcludedDebtChange() to amend bytes32[] memory keys = prevIssuer.availableCurrencyKeys(); require(keys.length > 0, "previous Issuer has no synths"); // query for previous debt records uint[] memory debts = prevDebtCache.excludedIssuedDebts(keys); // store the values for (uint i = 0; i < keys.length; i++) { if (debts[i] > 0) { // adding the values instead of overwriting in case some deltas were recorded in this // contract already (e.g. if the upgrade was not atomic) _excludedIssuedDebt[keys[i]] = _excludedIssuedDebt[keys[i]].add(debts[i]); } } } // Returns the total sUSD debt backed by non-SNX collateral. function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid) { bytes32[] memory currencyKeys = issuer().availableCurrencyKeys(); (uint[] memory rates, bool ratesAreInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys); return _totalNonSnxBackedDebt(currencyKeys, rates, ratesAreInvalid); } function _totalNonSnxBackedDebt( bytes32[] memory currencyKeys, uint[] memory rates, bool ratesAreInvalid ) internal view returns (uint excludedDebt, bool isInvalid) { // Calculate excluded debt. // 1. MultiCollateral long debt + short debt. (uint longValue, bool anyTotalLongRateIsInvalid) = collateralManager().totalLong(); (uint shortValue, bool anyTotalShortRateIsInvalid) = collateralManager().totalShort(); isInvalid = ratesAreInvalid || anyTotalLongRateIsInvalid || anyTotalShortRateIsInvalid; excludedDebt = longValue.add(shortValue); // 2. EtherWrapper. // Subtract sETH and sUSD issued by EtherWrapper. excludedDebt = excludedDebt.add(etherWrapper().totalIssuedSynths()); // 3. WrapperFactory. // Get the debt issued by the Wrappers. for (uint i = 0; i < currencyKeys.length; i++) { excludedDebt = excludedDebt.add(_excludedIssuedDebt[currencyKeys[i]].multiplyDecimalRound(rates[i])); } return (excludedDebt, isInvalid); } function _currentDebt() internal view returns (uint debt, bool anyRateIsInvalid) { bytes32[] memory currencyKeys = issuer().availableCurrencyKeys(); (uint[] memory rates, bool isInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys); // Sum all issued synth values based on their supply. uint[] memory values = _issuedSynthValues(currencyKeys, rates); (uint excludedDebt, bool isAnyNonSnxDebtRateInvalid) = _totalNonSnxBackedDebt(currencyKeys, rates, isInvalid); uint numValues = values.length; uint total; for (uint i; i < numValues; i++) { total = total.add(values[i]); } // Add in the debt accounted for by futures (uint futuresDebt, bool futuresDebtIsInvalid) = futuresMarketManager().totalDebt(); total = total.add(futuresDebt); // Ensure that if the excluded non-SNX debt exceeds SNX-backed debt, no overflow occurs total = total < excludedDebt ? 0 : total.sub(excludedDebt); return (total, isInvalid || futuresDebtIsInvalid || isAnyNonSnxDebtRateInvalid); } function currentDebt() external view returns (uint debt, bool anyRateIsInvalid) { return _currentDebt(); } function cacheInfo() external view returns ( uint debt, uint timestamp, bool isInvalid, bool isStale ) { uint time = _cacheTimestamp; return (_cachedDebt, time, _cacheInvalid, _cacheStale(time)); } /* ========== MUTATIVE FUNCTIONS ========== */ // Stub out all mutative functions as no-ops; // since they do nothing, there are no restrictions function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external {} function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external {} function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external {} function updateDebtCacheValidity(bool currentlyInvalid) external {} function purgeCachedSynthDebt(bytes32 currencyKey) external {} function takeDebtSnapshot() external {} function recordExcludedDebtChange(bytes32 currencyKey, int256 delta) external {} function updateCachedsUSDDebt(int amount) external {} /* ========== MODIFIERS ========== */ function _requireSystemActiveIfNotOwner() internal view { if (msg.sender != owner) { systemStatus().requireSystemActive(); } } modifier requireSystemActiveIfNotOwner() { _requireSystemActiveIfNotOwner(); _; } function _onlyIssuer() internal view { require(msg.sender == address(issuer()), "Sender is not Issuer"); } modifier onlyIssuer() { _onlyIssuer(); _; } function _onlyIssuerOrExchanger() internal view { require(msg.sender == address(issuer()) || msg.sender == address(exchanger()), "Sender is not Issuer or Exchanger"); } modifier onlyIssuerOrExchanger() { _onlyIssuerOrExchanger(); _; } function _onlyDebtIssuer() internal view { bool isWrapper = wrapperFactory().isWrapper(msg.sender); // owner included for debugging and fixing in emergency situation bool isOwner = msg.sender == owner; require(isOwner || isWrapper, "Only debt issuers may call this"); } modifier onlyDebtIssuer() { _onlyDebtIssuer(); _; } } // Libraries // Inheritance // https://docs.synthetix.io/contracts/source/contracts/debtcache contract DebtCache is BaseDebtCache { using SafeDecimalMath for uint; bytes32 public constant CONTRACT_NAME = "DebtCache"; constructor(address _owner, address _resolver) public BaseDebtCache(_owner, _resolver) {} bytes32 internal constant EXCLUDED_DEBT_KEY = "EXCLUDED_DEBT"; bytes32 internal constant FUTURES_DEBT_KEY = "FUTURES_DEBT"; /* ========== MUTATIVE FUNCTIONS ========== */ // This function exists in case a synth is ever somehow removed without its snapshot being updated. function purgeCachedSynthDebt(bytes32 currencyKey) external onlyOwner { require(issuer().synths(currencyKey) == ISynth(0), "Synth exists"); delete _cachedSynthDebt[currencyKey]; } function takeDebtSnapshot() external requireSystemActiveIfNotOwner { bytes32[] memory currencyKeys = issuer().availableCurrencyKeys(); (uint[] memory values, uint futuresDebt, uint excludedDebt, bool isInvalid) = _currentSynthDebts(currencyKeys); // The total SNX-backed debt is the debt of futures markets plus the debt of circulating synths. uint snxCollateralDebt = futuresDebt; _cachedSynthDebt[FUTURES_DEBT_KEY] = futuresDebt; uint numValues = values.length; for (uint i; i < numValues; i++) { uint value = values[i]; snxCollateralDebt = snxCollateralDebt.add(value); _cachedSynthDebt[currencyKeys[i]] = value; } // Subtract out the excluded non-SNX backed debt from our total _cachedSynthDebt[EXCLUDED_DEBT_KEY] = excludedDebt; uint newDebt = snxCollateralDebt.floorsub(excludedDebt); _cachedDebt = newDebt; _cacheTimestamp = block.timestamp; emit DebtCacheUpdated(newDebt); emit DebtCacheSnapshotTaken(block.timestamp); // (in)validate the cache if necessary _updateDebtCacheValidity(isInvalid); } function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external requireSystemActiveIfNotOwner { (uint[] memory rates, bool anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(currencyKeys); _updateCachedSynthDebtsWithRates(currencyKeys, rates, anyRateInvalid); } function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external onlyIssuer { bytes32[] memory synthKeyArray = new bytes32[](1); synthKeyArray[0] = currencyKey; uint[] memory synthRateArray = new uint[](1); synthRateArray[0] = currencyRate; _updateCachedSynthDebtsWithRates(synthKeyArray, synthRateArray, false); } function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external onlyIssuerOrExchanger { _updateCachedSynthDebtsWithRates(currencyKeys, currencyRates, false); } function updateDebtCacheValidity(bool currentlyInvalid) external onlyIssuer { _updateDebtCacheValidity(currentlyInvalid); } function recordExcludedDebtChange(bytes32 currencyKey, int256 delta) external onlyDebtIssuer { int256 newExcludedDebt = int256(_excludedIssuedDebt[currencyKey]) + delta; require(newExcludedDebt >= 0, "Excluded debt cannot become negative"); _excludedIssuedDebt[currencyKey] = uint(newExcludedDebt); } function updateCachedsUSDDebt(int amount) external onlyIssuer { uint delta = SafeDecimalMath.abs(amount); if (amount > 0) { _cachedSynthDebt[sUSD] = _cachedSynthDebt[sUSD].add(delta); _cachedDebt = _cachedDebt.add(delta); } else { _cachedSynthDebt[sUSD] = _cachedSynthDebt[sUSD].sub(delta); _cachedDebt = _cachedDebt.sub(delta); } emit DebtCacheUpdated(_cachedDebt); } /* ========== INTERNAL FUNCTIONS ========== */ function _updateDebtCacheValidity(bool currentlyInvalid) internal { if (_cacheInvalid != currentlyInvalid) { _cacheInvalid = currentlyInvalid; emit DebtCacheValidityChanged(currentlyInvalid); } } // Updated the global debt according to a rate/supply change in a subset of issued synths. function _updateCachedSynthDebtsWithRates( bytes32[] memory currencyKeys, uint[] memory currentRates, bool anyRateIsInvalid ) internal { uint numKeys = currencyKeys.length; require(numKeys == currentRates.length, "Input array lengths differ"); // Compute the cached and current debt sum for the subset of synths provided. uint cachedSum; uint currentSum; uint[] memory currentValues = _issuedSynthValues(currencyKeys, currentRates); for (uint i = 0; i < numKeys; i++) { bytes32 key = currencyKeys[i]; uint currentSynthDebt = currentValues[i]; cachedSum = cachedSum.add(_cachedSynthDebt[key]); currentSum = currentSum.add(currentSynthDebt); _cachedSynthDebt[key] = currentSynthDebt; } // Apply the debt update. if (cachedSum != currentSum) { uint debt = _cachedDebt; // apply the delta between the cachedSum and currentSum // add currentSum before sub cachedSum to prevent overflow as cachedSum > debt for large amount of excluded debt debt = debt.add(currentSum).sub(cachedSum); _cachedDebt = debt; emit DebtCacheUpdated(debt); } // Invalidate the cache if necessary if (anyRateIsInvalid) { _updateDebtCacheValidity(anyRateIsInvalid); } } /* ========== EVENTS ========== */ event DebtCacheUpdated(uint cachedDebt); event DebtCacheSnapshotTaken(uint timestamp); event DebtCacheValidityChanged(bool indexed isInvalid); }
The total SNX-backed debt is the debt of futures markets plus the debt of circulating synths.
function takeDebtSnapshot() external requireSystemActiveIfNotOwner { bytes32[] memory currencyKeys = issuer().availableCurrencyKeys(); (uint[] memory values, uint futuresDebt, uint excludedDebt, bool isInvalid) = _currentSynthDebts(currencyKeys); uint snxCollateralDebt = futuresDebt; _cachedSynthDebt[FUTURES_DEBT_KEY] = futuresDebt; uint numValues = values.length; for (uint i; i < numValues; i++) { uint value = values[i]; snxCollateralDebt = snxCollateralDebt.add(value); _cachedSynthDebt[currencyKeys[i]] = value; } uint newDebt = snxCollateralDebt.floorsub(excludedDebt); _cachedDebt = newDebt; _cacheTimestamp = block.timestamp; emit DebtCacheUpdated(newDebt); emit DebtCacheSnapshotTaken(block.timestamp); }
8,008,561
[ 1, 1986, 2078, 14204, 60, 17, 823, 329, 18202, 88, 353, 326, 18202, 88, 434, 15583, 2267, 2413, 8737, 326, 18202, 88, 434, 5886, 1934, 1776, 6194, 451, 87, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 4862, 758, 23602, 4568, 1435, 3903, 2583, 3163, 3896, 10288, 5541, 288, 203, 3639, 1731, 1578, 8526, 3778, 5462, 2396, 273, 9715, 7675, 5699, 7623, 2396, 5621, 203, 3639, 261, 11890, 8526, 3778, 924, 16, 2254, 15583, 758, 23602, 16, 2254, 8845, 758, 23602, 16, 1426, 353, 1941, 13, 273, 389, 2972, 10503, 451, 758, 70, 3428, 12, 7095, 2396, 1769, 203, 203, 3639, 2254, 4556, 92, 13535, 2045, 287, 758, 23602, 273, 15583, 758, 23602, 31, 203, 3639, 389, 7097, 10503, 451, 758, 23602, 63, 42, 1693, 4830, 55, 67, 1639, 38, 56, 67, 3297, 65, 273, 15583, 758, 23602, 31, 203, 3639, 2254, 818, 1972, 273, 924, 18, 2469, 31, 203, 3639, 364, 261, 11890, 277, 31, 277, 411, 818, 1972, 31, 277, 27245, 288, 203, 5411, 2254, 460, 273, 924, 63, 77, 15533, 203, 5411, 4556, 92, 13535, 2045, 287, 758, 23602, 273, 4556, 92, 13535, 2045, 287, 758, 23602, 18, 1289, 12, 1132, 1769, 203, 5411, 389, 7097, 10503, 451, 758, 23602, 63, 7095, 2396, 63, 77, 13563, 273, 460, 31, 203, 3639, 289, 203, 203, 3639, 2254, 394, 758, 23602, 273, 4556, 92, 13535, 2045, 287, 758, 23602, 18, 74, 383, 1383, 373, 12, 24602, 758, 23602, 1769, 203, 3639, 389, 7097, 758, 23602, 273, 394, 758, 23602, 31, 203, 3639, 389, 2493, 4921, 273, 1203, 18, 5508, 31, 203, 3639, 3626, 1505, 23602, 1649, 7381, 12, 2704, 758, 23602, 1769, 203, 3639, 3626, 1505, 23602, 1649, 4568, 27486, 12, 2629, 18, 5508, 1769, 203, 203, 565, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-08-28 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @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 ; //inject UNINIT LOCAL/STATE VAR 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 ; //inject UNINIT LOCAL/STATE VAR 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 ; //inject UNINIT LOCAL/STATE VAR require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c ; //inject UNINIT LOCAL/STATE VAR // 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; } } interface IAmp { function registerCollateralManager() external; } /** * @title Ownable is a contract the provides contract ownership functionality, including a two- * phase transfer. */ contract Ownable { address private _owner; address private _authorizedNewOwner; /** * @notice Emitted when the owner authorizes ownership transfer to a new address * @param authorizedAddress New owner address */ event OwnershipTransferAuthorization(address indexed authorizedAddress); /** * @notice Emitted when the authorized address assumed ownership * @param oldValue Old owner * @param newValue New owner */ event OwnerUpdate(address indexed oldValue, address indexed newValue); /** * @notice Sets the owner to the sender / contract creator */ constructor() internal { _owner = msg.sender; } /** * @notice Retrieves the owner of the contract * @return The contract owner */ function owner() public view returns (address) { return _owner; } /** * @notice Retrieves the authorized new owner of the contract * @return The authorized new contract owner */ function authorizedNewOwner() public view returns (address) { return _authorizedNewOwner; } /** * @notice Authorizes the transfer of ownership from owner to the provided address. * NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership(). * This authorization may be removed by another call to this function authorizing the zero * address. * @param _authorizedAddress The address authorized to become the new owner */ function authorizeOwnershipTransfer(address _authorizedAddress) external { require(msg.sender == _owner, "Invalid sender"); _authorizedNewOwner = _authorizedAddress; emit OwnershipTransferAuthorization(_authorizedNewOwner); } /** * @notice Transfers ownership of this contract to the _authorizedNewOwner * @dev Error invalid sender. */ function assumeOwnership() external { require(msg.sender == _authorizedNewOwner, "Invalid sender"); address oldValue ; //inject UNINIT LOCAL/STATE VAR _owner = _authorizedNewOwner; _authorizedNewOwner = address(0); emit OwnerUpdate(oldValue, _owner); } } abstract contract ERC1820Registry { function setInterfaceImplementer( address _addr, bytes32 _interfaceHash, address _implementer ) external virtual; function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external virtual view returns (address); function setManager(address _addr, address _newManager) external virtual; function getManager(address _addr) public virtual view returns (address); } /// Base client to interact with the registry. contract ERC1820Client { ERC1820Registry constant ERC1820REGISTRY = ERC1820Registry( 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24 ); function setInterfaceImplementation( string memory _interfaceLabel, address _implementation ) internal { bytes32 interfaceHash ; //inject UNINIT LOCAL/STATE VAR ERC1820REGISTRY.setInterfaceImplementer( address(this), interfaceHash, _implementation ); } function interfaceAddr(address addr, string memory _interfaceLabel) internal view returns (address) { bytes32 interfaceHash ; //inject UNINIT LOCAL/STATE VAR return ERC1820REGISTRY.getInterfaceImplementer(addr, interfaceHash); } function delegateManagement(address _newManager) internal { ERC1820REGISTRY.setManager(address(this), _newManager); } } /** * @title IAmpTokensRecipient * @dev IAmpTokensRecipient token transfer hook interface */ interface IAmpTokensRecipient { /** * @dev Report if the recipient will successfully receive the tokens */ function canReceive( bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external view returns (bool); /** * @dev Hook executed upon a transfer to the recipient */ function tokensReceived( bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external; } /** * @title IAmpTokensSender * @dev IAmpTokensSender token transfer hook interface */ interface IAmpTokensSender { /** * @dev Report if the transfer will succeed from the pespective of the * token sender */ function canTransfer( bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external view returns (bool); /** * @dev Hook executed upon a transfer on behalf of the sender */ function tokensToTransfer( bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external; } /** * @title PartitionUtils * @notice Partition related helper functions. */ library PartitionUtils { bytes32 public constant CHANGE_PARTITION_FLAG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /** * @notice Retrieve the destination partition from the 'data' field. * A partition change is requested ONLY when 'data' starts with the flag: * * 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff * * When the flag is detected, the destination partition is extracted from the * 32 bytes following the flag. * @param _data Information attached to the transfer. Will contain the * destination partition if a change is requested. * @param _fallbackPartition Partition value to return if a partition change * is not requested in the `_data`. * @return toPartition Destination partition. If the `_data` does not contain * the prefix and bytes32 partition in the first 64 bytes, the method will * return the provided `_fromPartition`. */ function _getDestinationPartition(bytes memory _data, bytes32 _fallbackPartition) internal pure returns (bytes32) { if (_data.length < 64) { return _fallbackPartition; } (bytes32 flag, bytes32 toPartition) = abi.decode(_data, (bytes32, bytes32)); if (flag == CHANGE_PARTITION_FLAG) { return toPartition; } return _fallbackPartition; } /** * @notice Helper to get the strategy identifying prefix from the `_partition`. * @param _partition Partition to get the prefix for. * @return 4 byte partition strategy prefix. */ function _getPartitionPrefix(bytes32 _partition) internal pure returns (bytes4) { return bytes4(_partition); } /** * @notice Helper method to split the partition into the prefix, sub partition * and partition owner components. * @param _partition The partition to split into parts. * @return The 4 byte partition prefix, 8 byte sub partition, and final 20 * bytes representing an address. */ function _splitPartition(bytes32 _partition) internal pure returns ( bytes4, bytes8, address ) { bytes4 prefix ; //inject UNINIT LOCAL/STATE VAR bytes8 subPartition ; //inject UNINIT LOCAL/STATE VAR address addressPart ; //inject UNINIT LOCAL/STATE VAR return (prefix, subPartition, addressPart); } /** * @notice Helper method to get a partition strategy ERC1820 interface name * based on partition prefix. * @param _prefix 4 byte partition prefix. * @dev Each 4 byte prefix has a unique interface name so that an individual * hook implementation can be set for each prefix. */ function _getPartitionStrategyValidatorIName(bytes4 _prefix) internal pure returns (string memory) { return string(abi.encodePacked("AmpPartitionStrategyValidator", _prefix)); } } /** * @title FlexaCollateralManager is an implementation of IAmpTokensSender and IAmpTokensRecipient * which serves as the Amp collateral manager for the Flexa Network. */ contract FlexaCollateralManager is Ownable, IAmpTokensSender, IAmpTokensRecipient, ERC1820Client { /** * @dev AmpTokensSender interface label. */ string internal constant AMP_TOKENS_SENDER = "AmpTokensSender"; /** * @dev AmpTokensRecipient interface label. */ string internal constant AMP_TOKENS_RECIPIENT = "AmpTokensRecipient"; /** * @dev Change Partition Flag used in transfer data parameters to signal which partition * will receive the tokens. */ bytes32 internal constant CHANGE_PARTITION_FLAG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /** * @dev Required prefix for all registered partitions. Used to ensure the Collateral Pool * Partition Validator is used within Amp. */ bytes4 internal constant PARTITION_PREFIX = 0xCCCCCCCC; /********************************************************************************************** * Operator Data Flags *********************************************************************************************/ /** * @dev Flag used in operator data parameters to indicate the transfer is a withdrawal */ bytes32 internal constant WITHDRAWAL_FLAG = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /** * @dev Flag used in operator data parameters to indicate the transfer is a fallback * withdrawal */ bytes32 internal constant FALLBACK_WITHDRAWAL_FLAG = 0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /** * @dev Flag used in operator data parameters to indicate the transfer is a supply refund */ bytes32 internal constant REFUND_FLAG = 0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc; /** * @dev Flag used in operator data parameters to indicate the transfer is a direct transfer */ bytes32 internal constant DIRECT_TRANSFER_FLAG = 0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd; /********************************************************************************************** * Configuration *********************************************************************************************/ /** * @notice Address of the Amp contract. Immutable. */ address public amp; /** * @notice Permitted partitions */ mapping(bytes32 => bool) public partitions; /********************************************************************************************** * Roles *********************************************************************************************/ /** * @notice Address authorized to publish withdrawal roots */ address public withdrawalPublisher; /** * @notice Address authorized to publish fallback withdrawal roots */ address public fallbackPublisher; /** * @notice Address authorized to adjust the withdrawal limit */ address public withdrawalLimitPublisher; /** * @notice Address authorized to directly transfer tokens */ address public directTransferer; /** * @notice Address authorized to manage permitted partition */ address public partitionManager; /** * @notice Struct used to record received tokens that can be recovered during the fallback * withdrawal period * @param supplier Token supplier * @param partition Partition which received the tokens * @param amount Number of tokens received */ struct Supply { address supplier; bytes32 partition; uint256 amount; } /********************************************************************************************** * Supply State *********************************************************************************************/ /** * @notice Supply nonce used to track incoming token transfers */ uint256 public supplyNonce = 0; /** * @notice Mapping of all incoming token transfers */ mapping(uint256 => Supply) public nonceToSupply; /********************************************************************************************** * Withdrawal State *********************************************************************************************/ /** * @notice Remaining withdrawal limit. Initially set to 100,000 Amp. */ uint256 public withdrawalLimit = 100 * 1000 * (10**18); /** * @notice Withdrawal maximum root nonce */ uint256 public maxWithdrawalRootNonce = 0; /** * @notice Active set of withdrawal roots */ mapping(bytes32 => uint256) public withdrawalRootToNonce; /** * @notice Last invoked withdrawal root for each account, per partition */ mapping(bytes32 => mapping(address => uint256)) public addressToWithdrawalNonce; /** * @notice Total amount withdrawn for each account, per partition */ mapping(bytes32 => mapping(address => uint256)) public addressToCumulativeAmountWithdrawn; /********************************************************************************************** * Fallback Withdrawal State *********************************************************************************************/ /** * @notice Withdrawal fallback delay. Initially set to one week. */ uint256 public fallbackWithdrawalDelaySeconds = 1 weeks; /** * @notice Current fallback withdrawal root */ bytes32 public fallbackRoot; /** * @notice Timestamp of when the last fallback root was published */ uint256 public fallbackSetDate = 2**200; // very far in the future /** * @notice Latest supply reflected in the fallback withdrawal authorization tree */ uint256 public fallbackMaxIncludedSupplyNonce = 0; /********************************************************************************************** * Supplier Events *********************************************************************************************/ /** * @notice Indicates a token supply has been received * @param supplier Token supplier * @param amount Number of tokens transferred * @param nonce Nonce of the supply */ event SupplyReceipt( address indexed supplier, bytes32 indexed partition, uint256 amount, uint256 indexed nonce ); /** * @notice Indicates that a withdrawal was executed * @param supplier Address whose withdrawal authorization was executed * @param partition Partition from which the tokens were transferred * @param amount Amount of tokens transferred * @param rootNonce Nonce of the withdrawal root used for authorization * @param authorizedAccountNonce Maximum previous nonce used by the account */ event Withdrawal( address indexed supplier, bytes32 indexed partition, uint256 amount, uint256 indexed rootNonce, uint256 authorizedAccountNonce ); /** * @notice Indicates a fallback withdrawal was executed * @param supplier Address whose fallback withdrawal authorization was executed * @param partition Partition from which the tokens were transferred * @param amount Amount of tokens transferred */ event FallbackWithdrawal( address indexed supplier, bytes32 indexed partition, uint256 indexed amount ); /** * @notice Indicates a release of supply is requested * @param supplier Token supplier * @param partition Parition from which the tokens should be released * @param amount Number of tokens requested to be released * @param data Metadata provided by the requestor */ event ReleaseRequest( address indexed supplier, bytes32 indexed partition, uint256 indexed amount, bytes data ); /** * @notice Indicates a supply refund was executed * @param supplier Address whose refund authorization was executed * @param partition Partition from which the tokens were transferred * @param amount Amount of tokens transferred * @param nonce Nonce of the original supply */ event SupplyRefund( address indexed supplier, bytes32 indexed partition, uint256 amount, uint256 indexed nonce ); /********************************************************************************************** * Direct Transfer Events *********************************************************************************************/ /** * @notice Emitted when tokens are directly transfered * @param operator Address that executed the direct transfer * @param from_partition Partition from which the tokens were transferred * @param to_address Address to which the tokens were transferred * @param to_partition Partition to which the tokens were transferred * @param value Amount of tokens transferred */ event DirectTransfer( address operator, bytes32 indexed from_partition, address indexed to_address, bytes32 indexed to_partition, uint256 value ); /********************************************************************************************** * Admin Configuration Events *********************************************************************************************/ /** * @notice Emitted when a partition is permitted for supply * @param partition Partition added to the permitted set */ event PartitionAdded(bytes32 indexed partition); /** * @notice Emitted when a partition is removed from the set permitted for supply * @param partition Partition removed from the permitted set */ event PartitionRemoved(bytes32 indexed partition); /********************************************************************************************** * Admin Withdrawal Management Events *********************************************************************************************/ /** * @notice Emitted when a new withdrawal root hash is added to the active set * @param rootHash Merkle root hash. * @param nonce Nonce of the Merkle root hash. */ event WithdrawalRootHashAddition(bytes32 indexed rootHash, uint256 indexed nonce); /** * @notice Emitted when a withdrawal root hash is removed from the active set * @param rootHash Merkle root hash. * @param nonce Nonce of the Merkle root hash. */ event WithdrawalRootHashRemoval(bytes32 indexed rootHash, uint256 indexed nonce); /** * @notice Emitted when the withdrawal limit is updated * @param oldValue Old limit. * @param newValue New limit. */ event WithdrawalLimitUpdate(uint256 indexed oldValue, uint256 indexed newValue); /********************************************************************************************** * Admin Fallback Management Events *********************************************************************************************/ /** * @notice Emitted when a new fallback withdrawal root hash is set * @param rootHash Merkle root hash * @param maxSupplyNonceIncluded Nonce of the last supply reflected in the tree data * @param setDate Timestamp of when the root hash was set */ event FallbackRootHashSet( bytes32 indexed rootHash, uint256 indexed maxSupplyNonceIncluded, uint256 setDate ); /** * @notice Emitted when the fallback root hash set date is reset * @param newDate Timestamp of when the fallback reset date was set */ event FallbackMechanismDateReset(uint256 indexed newDate); /** * @notice Emitted when the fallback delay is updated * @param oldValue Old delay * @param newValue New delay */ event FallbackWithdrawalDelayUpdate(uint256 indexed oldValue, uint256 indexed newValue); /********************************************************************************************** * Role Management Events *********************************************************************************************/ /** * @notice Emitted when the Withdrawal Publisher is updated * @param oldValue Old publisher * @param newValue New publisher */ event WithdrawalPublisherUpdate(address indexed oldValue, address indexed newValue); /** * @notice Emitted when the Fallback Publisher is updated * @param oldValue Old publisher * @param newValue New publisher */ event FallbackPublisherUpdate(address indexed oldValue, address indexed newValue); /** * @notice Emitted when Withdrawal Limit Publisher is updated * @param oldValue Old publisher * @param newValue New publisher */ event WithdrawalLimitPublisherUpdate(address indexed oldValue, address indexed newValue); /** * @notice Emitted when the DirectTransferer address is updated * @param oldValue Old DirectTransferer address * @param newValue New DirectTransferer address */ event DirectTransfererUpdate(address indexed oldValue, address indexed newValue); /** * @notice Emitted when the Partition Manager address is updated * @param oldValue Old Partition Manager address * @param newValue New Partition Manager address */ event PartitionManagerUpdate(address indexed oldValue, address indexed newValue); /********************************************************************************************** * Constructor *********************************************************************************************/ /** * @notice FlexaCollateralManager constructor * @param _amp Address of the Amp token contract */ constructor(address _amp) public { amp = _amp; ERC1820Client.setInterfaceImplementation(AMP_TOKENS_RECIPIENT, address(this)); ERC1820Client.setInterfaceImplementation(AMP_TOKENS_SENDER, address(this)); IAmp(amp).registerCollateralManager(); } /********************************************************************************************** * IAmpTokensRecipient Hooks *********************************************************************************************/ /** * @notice Validates where the supplied parameters are valid for a transfer of tokens to this * contract * @dev Implements IAmpTokensRecipient * @param _partition Partition from which the tokens were transferred * @param _to The destination address of the tokens. Must be this. * @param _data Optional data sent with the transfer. Used to set the destination partition. * @return true if the tokens can be received, otherwise false */ function canReceive( bytes4, /* functionSig */ bytes32 _partition, address, /* operator */ address, /* from */ address _to, uint256, /* value */ bytes calldata _data, bytes calldata /* operatorData */ ) external override view returns (bool) { if (msg.sender != amp || _to != address(this)) { return false; } bytes32 _destinationPartition ; //inject UNINIT LOCAL/STATE VAR return partitions[_destinationPartition]; } /** * @notice Function called by the token contract after executing a transfer. * @dev Implements IAmpTokensRecipient * @param _partition Partition from which the tokens were transferred * @param _operator Address which triggered the transfer. This address will be credited with * the supply. * @param _to The destination address of the tokens. Must be this. * @param _value Number of tokens the token holder balance is decreased by. * @param _data Optional data sent with the transfer. Used to set the destination partition. */ function tokensReceived( bytes4, /* functionSig */ bytes32 _partition, address _operator, address, /* from */ address _to, uint256 _value, bytes calldata _data, bytes calldata /* operatorData */ ) external override { require(msg.sender == amp, "Invalid sender"); require(_to == address(this), "Invalid to address"); bytes32 _destinationPartition ; //inject UNINIT LOCAL/STATE VAR require(partitions[_destinationPartition], "Invalid destination partition"); supplyNonce = SafeMath.add(supplyNonce, 1); nonceToSupply[supplyNonce].supplier = _operator; nonceToSupply[supplyNonce].partition = _destinationPartition; nonceToSupply[supplyNonce].amount = _value; emit SupplyReceipt(_operator, _destinationPartition, _value, supplyNonce); } /********************************************************************************************** * IAmpTokensSender Hooks *********************************************************************************************/ /** * @notice Validates where the supplied parameters are valid for a transfer of tokens from this * contract * @dev Implements IAmpTokensSender * @param _partition Source partition of the tokens * @param _operator Address which triggered the transfer * @param _from The source address of the tokens. Must be this. * @param _value Amount of tokens to be transferred * @param _operatorData Extra information attached by the operator. Must include the transfer * operation flag and additional authorization data custom for each transfer operation type. * @return true if the token transfer would succeed, otherwise false */ function canTransfer( bytes4, /*functionSig*/ bytes32 _partition, address _operator, address _from, address, /* to */ uint256 _value, bytes calldata, /* data */ bytes calldata _operatorData ) external override view returns (bool) { if (msg.sender != amp || _from != address(this)) { return false; } bytes32 flag ; //inject UNINIT LOCAL/STATE VAR if (flag == WITHDRAWAL_FLAG) { return _validateWithdrawal(_partition, _operator, _value, _operatorData); } if (flag == FALLBACK_WITHDRAWAL_FLAG) { return _validateFallbackWithdrawal(_partition, _operator, _value, _operatorData); } if (flag == REFUND_FLAG) { return _validateRefund(_partition, _operator, _value, _operatorData); } if (flag == DIRECT_TRANSFER_FLAG) { return _validateDirectTransfer(_operator, _value); } return false; } /** * @notice Function called by the token contract when executing a transfer * @dev Implements IAmpTokensSender * @param _partition Source partition of the tokens * @param _operator Address which triggered the transfer * @param _from The source address of the tokens. Must be this. * @param _to The target address of the tokens. * @param _value Amount of tokens to be transferred * @param _data Data attached to the transfer. Typically includes partition change information. * @param _operatorData Extra information attached by the operator. Must include the transfer * operation flag and additional authorization data custom for each transfer operation type. */ function tokensToTransfer( bytes4, /* functionSig */ bytes32 _partition, address _operator, address _from, address _to, uint256 _value, bytes calldata _data, bytes calldata _operatorData ) external override { require(msg.sender == amp, "Invalid sender"); require(_from == address(this), "Invalid from address"); bytes32 flag ; //inject UNINIT LOCAL/STATE VAR if (flag == WITHDRAWAL_FLAG) { _executeWithdrawal(_partition, _operator, _value, _operatorData); } else if (flag == FALLBACK_WITHDRAWAL_FLAG) { _executeFallbackWithdrawal(_partition, _operator, _value, _operatorData); } else if (flag == REFUND_FLAG) { _executeRefund(_partition, _operator, _value, _operatorData); } else if (flag == DIRECT_TRANSFER_FLAG) { _executeDirectTransfer(_partition, _operator, _to, _value, _data); } else { revert("invalid flag"); } } /********************************************************************************************** * Withdrawals *********************************************************************************************/ /** * @notice Validates withdrawal data * @param _partition Source partition of the withdrawal * @param _operator Address that is invoking the transfer * @param _value Number of tokens to be transferred * @param _operatorData Contains the withdrawal authorization data * @return true if the withdrawal data is valid, otherwise false */ function _validateWithdrawal( bytes32 _partition, address _operator, uint256 _value, bytes memory _operatorData ) internal view returns (bool) { ( address supplier, uint256 maxAuthorizedAccountNonce, uint256 withdrawalRootNonce ) = _getWithdrawalData(_partition, _value, _operatorData); return _validateWithdrawalData( _partition, _operator, _value, supplier, maxAuthorizedAccountNonce, withdrawalRootNonce ); } /** * @notice Validates the withdrawal data and updates state to reflect the transfer * @param _partition Source partition of the withdrawal * @param _operator Address that is invoking the transfer * @param _value Number of tokens to be transferred * @param _operatorData Contains the withdrawal authorization data */ function _executeWithdrawal( bytes32 _partition, address _operator, uint256 _value, bytes memory _operatorData ) internal { ( address supplier, uint256 maxAuthorizedAccountNonce, uint256 withdrawalRootNonce ) = _getWithdrawalData(_partition, _value, _operatorData); require( _validateWithdrawalData( _partition, _operator, _value, supplier, maxAuthorizedAccountNonce, withdrawalRootNonce ), "Transfer unauthorized" ); addressToCumulativeAmountWithdrawn[_partition][supplier] = SafeMath.add( _value, addressToCumulativeAmountWithdrawn[_partition][supplier] ); addressToWithdrawalNonce[_partition][supplier] = withdrawalRootNonce; withdrawalLimit = SafeMath.sub(withdrawalLimit, _value); emit Withdrawal( supplier, _partition, _value, withdrawalRootNonce, maxAuthorizedAccountNonce ); } /** * @notice Extracts withdrawal data from the supplied parameters * @param _partition Source partition of the withdrawal * @param _value Number of tokens to be transferred * @param _operatorData Contains the withdrawal authorization data, including the withdrawal * operation flag, supplier, maximum authorized account nonce, and Merkle proof. * @return supplier, the address whose account is authorized * @return maxAuthorizedAccountNonce, the maximum existing used withdrawal nonce for the * supplier and partition * @return withdrawalRootNonce, the active withdrawal root nonce found based on the supplied * data and Merkle proof */ function _getWithdrawalData( bytes32 _partition, uint256 _value, bytes memory _operatorData ) internal view returns ( address, /* supplier */ uint256, /* maxAuthorizedAccountNonce */ uint256 /* withdrawalRootNonce */ ) { ( address supplier, uint256 maxAuthorizedAccountNonce, bytes32[] memory merkleProof ) = _decodeWithdrawalOperatorData(_operatorData); bytes32 leafDataHash ; //inject UNINIT LOCAL/STATE VAR bytes32 calculatedRoot ; //inject UNINIT LOCAL/STATE VAR uint256 withdrawalRootNonce ; //inject UNINIT LOCAL/STATE VAR return (supplier, maxAuthorizedAccountNonce, withdrawalRootNonce); } /** * @notice Validates that the parameters are valid for the requested withdrawal * @param _partition Source partition of the tokens * @param _operator Address that is executing the withdrawal * @param _value Number of tokens to be transferred * @param _supplier The address whose account is authorized * @param _maxAuthorizedAccountNonce The maximum existing used withdrawal nonce for the * supplier and partition * @param _withdrawalRootNonce The active withdrawal root nonce found based on the supplied * data and Merkle proof * @return true if the withdrawal data is valid, otherwise false */ function _validateWithdrawalData( bytes32 _partition, address _operator, uint256 _value, address _supplier, uint256 _maxAuthorizedAccountNonce, uint256 _withdrawalRootNonce ) internal view returns (bool) { return // Only owner, withdrawal publisher or supplier can invoke withdrawals (_operator == owner() || _operator == withdrawalPublisher || _operator == _supplier) && // Ensure maxAuthorizedAccountNonce has not been exceeded (addressToWithdrawalNonce[_partition][_supplier] <= _maxAuthorizedAccountNonce) && // Ensure we are within the global withdrawal limit (_value <= withdrawalLimit) && // Merkle tree proof is valid (_withdrawalRootNonce > 0) && // Ensure the withdrawal root is more recent than the maxAuthorizedAccountNonce (_withdrawalRootNonce > _maxAuthorizedAccountNonce); } /********************************************************************************************** * Fallback Withdrawals *********************************************************************************************/ /** * @notice Validates fallback withdrawal data * @param _partition Source partition of the withdrawal * @param _operator Address that is invoking the transfer * @param _value Number of tokens to be transferred * @param _operatorData Contains the fallback withdrawal authorization data * @return true if the fallback withdrawal data is valid, otherwise false */ function _validateFallbackWithdrawal( bytes32 _partition, address _operator, uint256 _value, bytes memory _operatorData ) internal view returns (bool) { ( address supplier, uint256 maxCumulativeWithdrawalAmount, uint256 newCumulativeWithdrawalAmount, bytes32 calculatedRoot ) = _getFallbackWithdrawalData(_partition, _value, _operatorData); return _validateFallbackWithdrawalData( _operator, maxCumulativeWithdrawalAmount, newCumulativeWithdrawalAmount, supplier, calculatedRoot ); } /** * @notice Validates the fallback withdrawal data and updates state to reflect the transfer * @param _partition Source partition of the withdrawal * @param _operator Address that is invoking the transfer * @param _value Number of tokens to be transferred * @param _operatorData Contains the fallback withdrawal authorization data */ function _executeFallbackWithdrawal( bytes32 _partition, address _operator, uint256 _value, bytes memory _operatorData ) internal { ( address supplier, uint256 maxCumulativeWithdrawalAmount, uint256 newCumulativeWithdrawalAmount, bytes32 calculatedRoot ) = _getFallbackWithdrawalData(_partition, _value, _operatorData); require( _validateFallbackWithdrawalData( _operator, maxCumulativeWithdrawalAmount, newCumulativeWithdrawalAmount, supplier, calculatedRoot ), "Transfer unauthorized" ); addressToCumulativeAmountWithdrawn[_partition][supplier] = newCumulativeWithdrawalAmount; addressToWithdrawalNonce[_partition][supplier] = maxWithdrawalRootNonce; emit FallbackWithdrawal(supplier, _partition, _value); } /** * @notice Extracts withdrawal data from the supplied parameters * @param _partition Source partition of the withdrawal * @param _value Number of tokens to be transferred * @param _operatorData Contains the fallback withdrawal authorization data, including the * fallback withdrawal operation flag, supplier, max cumulative withdrawal amount, and Merkle * proof. * @return supplier, the address whose account is authorized * @return maxCumulativeWithdrawalAmount, the maximum amount of tokens that can be withdrawn * for the supplier's account, including both withdrawals and fallback withdrawals * @return newCumulativeWithdrawalAmount, the new total of all withdrawals include the * current request * @return calculatedRoot, the Merkle tree root calculated based on the supplied data and proof */ function _getFallbackWithdrawalData( bytes32 _partition, uint256 _value, bytes memory _operatorData ) internal view returns ( address, /* supplier */ uint256, /* maxCumulativeWithdrawalAmount */ uint256, /* newCumulativeWithdrawalAmount */ bytes32 /* calculatedRoot */ ) { ( address supplier, uint256 maxCumulativeWithdrawalAmount, bytes32[] memory merkleProof ) = _decodeWithdrawalOperatorData(_operatorData); uint256 newCumulativeWithdrawalAmount ; //inject UNINIT LOCAL/STATE VAR bytes32 leafDataHash ; //inject UNINIT LOCAL/STATE VAR bytes32 calculatedRoot ; //inject UNINIT LOCAL/STATE VAR return ( supplier, maxCumulativeWithdrawalAmount, newCumulativeWithdrawalAmount, calculatedRoot ); } /** * @notice Validates that the parameters are valid for the requested fallback withdrawal * @param _operator Address that is executing the withdrawal * @param _maxCumulativeWithdrawalAmount, the maximum amount of tokens that can be withdrawn * for the supplier's account, including both withdrawals and fallback withdrawals * @param _newCumulativeWithdrawalAmount, the new total of all withdrawals include the * current request * @param _supplier The address whose account is authorized * @param _calculatedRoot The Merkle tree root calculated based on the supplied data and proof * @return true if the fallback withdrawal data is valid, otherwise false */ function _validateFallbackWithdrawalData( address _operator, uint256 _maxCumulativeWithdrawalAmount, uint256 _newCumulativeWithdrawalAmount, address _supplier, bytes32 _calculatedRoot ) internal view returns (bool) { return // Only owner or supplier can invoke the fallback withdrawal (_operator == owner() || _operator == _supplier) && // Ensure we have entered fallback mode (SafeMath.add(fallbackSetDate, fallbackWithdrawalDelaySeconds) <= block.timestamp) && // Check that the maximum allowable withdrawal for the supplier has not been exceeded (_newCumulativeWithdrawalAmount <= _maxCumulativeWithdrawalAmount) && // Merkle tree proof is valid (fallbackRoot == _calculatedRoot); } /********************************************************************************************** * Supply Refunds *********************************************************************************************/ /** * @notice Validates refund data * @param _partition Source partition of the refund * @param _operator Address that is invoking the transfer * @param _value Number of tokens to be transferred * @param _operatorData Contains the refund authorization data * @return true if the refund data is valid, otherwise false */ function _validateRefund( bytes32 _partition, address _operator, uint256 _value, bytes memory _operatorData ) internal view returns (bool) { (uint256 _supplyNonce, Supply memory supply) = _getRefundData(_operatorData); return _verifyRefundData(_partition, _operator, _value, _supplyNonce, supply); } /** * @notice Validates the refund data and updates state to reflect the transfer * @param _partition Source partition of the refund * @param _operator Address that is invoking the transfer * @param _value Number of tokens to be transferred * @param _operatorData Contains the refund authorization data */ function _executeRefund( bytes32 _partition, address _operator, uint256 _value, bytes memory _operatorData ) internal { (uint256 nonce, Supply memory supply) = _getRefundData(_operatorData); require( _verifyRefundData(_partition, _operator, _value, nonce, supply), "Transfer unauthorized" ); delete nonceToSupply[nonce]; emit SupplyRefund(supply.supplier, _partition, supply.amount, nonce); } /** * @notice Extracts refund data from the supplied parameters * @param _operatorData Contains the refund authorization data, including the refund * operation flag and supply nonce. * @return supplyNonce, nonce of the recorded supply * @return supply, The supplier, partition and amount of tokens in the original supply */ function _getRefundData(bytes memory _operatorData) internal view returns (uint256, Supply memory) { uint256 _supplyNonce ; //inject UNINIT LOCAL/STATE VAR Supply memory supply = nonceToSupply[_supplyNonce]; return (_supplyNonce, supply); } /** * @notice Validates that the parameters are valid for the requested refund * @param _partition Source partition of the tokens * @param _operator Address that is executing the refund * @param _value Number of tokens to be transferred * @param _supplyNonce nonce of the recorded supply * @param _supply The supplier, partition and amount of tokens in the original supply * @return true if the refund data is valid, otherwise false */ function _verifyRefundData( bytes32 _partition, address _operator, uint256 _value, uint256 _supplyNonce, Supply memory _supply ) internal view returns (bool) { return // Supply record exists (_supply.amount > 0) && // Only owner or supplier can invoke the refund (_operator == owner() || _operator == _supply.supplier) && // Requested partition matches the Supply record (_partition == _supply.partition) && // Requested value matches the Supply record (_value == _supply.amount) && // Ensure we have entered fallback mode (SafeMath.add(fallbackSetDate, fallbackWithdrawalDelaySeconds) <= block.timestamp) && // Supply has not already been included in the fallback withdrawal data (_supplyNonce > fallbackMaxIncludedSupplyNonce); } /********************************************************************************************** * Direct Transfers *********************************************************************************************/ /** * @notice Validates direct transfer data * @param _operator Address that is invoking the transfer * @param _value Number of tokens to be transferred * @return true if the direct transfer data is valid, otherwise false */ function _validateDirectTransfer(address _operator, uint256 _value) internal view returns (bool) { return // Only owner and directTransferer can invoke withdrawals (_operator == owner() || _operator == directTransferer) && // Ensure we are within the global withdrawal limit (_value <= withdrawalLimit); } /** * @notice Validates the direct transfer data and updates state to reflect the transfer * @param _partition Source partition of the direct transfer * @param _operator Address that is invoking the transfer * @param _to The target address of the tokens. * @param _value Number of tokens to be transferred * @param _data Data attached to the transfer. Typically includes partition change information. */ function _executeDirectTransfer( bytes32 _partition, address _operator, address _to, uint256 _value, bytes memory _data ) internal { require(_validateDirectTransfer(_operator, _value), "Transfer unauthorized"); withdrawalLimit = SafeMath.sub(withdrawalLimit, _value); bytes32 to_partition ; //inject UNINIT LOCAL/STATE VAR emit DirectTransfer(_operator, _partition, _to, to_partition, _value); } /********************************************************************************************** * Release Request *********************************************************************************************/ /** * @notice Emits a release request event that can be used to trigger the release of tokens * @param _partition Parition from which the tokens should be released * @param _amount Number of tokens requested to be released * @param _data Metadata to include with the release request */ function requestRelease( bytes32 _partition, uint256 _amount, bytes memory _data ) external { emit ReleaseRequest(msg.sender, _partition, _amount, _data); } /********************************************************************************************** * Partition Management *********************************************************************************************/ /** * @notice Adds a partition to the set allowed to receive tokens * @param _partition Parition to be permitted for incoming transfers */ function addPartition(bytes32 _partition) external { require(msg.sender == owner() || msg.sender == partitionManager, "Invalid sender"); require(partitions[_partition] == false, "Partition already permitted"); (bytes4 prefix, , address partitionOwner) = PartitionUtils._splitPartition(_partition); require(prefix == PARTITION_PREFIX, "Invalid partition prefix"); require(partitionOwner == address(this), "Invalid partition owner"); partitions[_partition] = true; emit PartitionAdded(_partition); } /** * @notice Removes a partition from the set allowed to receive tokens * @param _partition Parition to be disallowed from incoming transfers */ function removePartition(bytes32 _partition) external { require(msg.sender == owner() || msg.sender == partitionManager, "Invalid sender"); require(partitions[_partition], "Partition not permitted"); delete partitions[_partition]; emit PartitionRemoved(_partition); } /********************************************************************************************** * Withdrawal Management *********************************************************************************************/ /** * @notice Modifies the withdrawal limit by the provided amount. * @param _amount Limit delta */ function modifyWithdrawalLimit(int256 _amount) external { require(msg.sender == owner() || msg.sender == withdrawalLimitPublisher, "Invalid sender"); uint256 oldLimit ; //inject UNINIT LOCAL/STATE VAR if (_amount < 0) { uint256 unsignedAmount ; //inject UNINIT LOCAL/STATE VAR withdrawalLimit = SafeMath.sub(withdrawalLimit, unsignedAmount); } else { uint256 unsignedAmount ; //inject UNINIT LOCAL/STATE VAR withdrawalLimit = SafeMath.add(withdrawalLimit, unsignedAmount); } emit WithdrawalLimitUpdate(oldLimit, withdrawalLimit); } /** * @notice Adds the root hash of a Merkle tree containing authorized token withdrawals to the * active set * @param _root The root hash to be added to the active set * @param _nonce The nonce of the new root hash. Must be exactly one higher than the existing * max nonce. * @param _replacedRoots The root hashes to be removed from the repository. */ function addWithdrawalRoot( bytes32 _root, uint256 _nonce, bytes32[] calldata _replacedRoots ) external { require(msg.sender == owner() || msg.sender == withdrawalPublisher, "Invalid sender"); require(_root != 0, "Invalid root"); require(maxWithdrawalRootNonce + 1 == _nonce, "Nonce not current max plus one"); require(withdrawalRootToNonce[_root] == 0, "Nonce already used"); withdrawalRootToNonce[_root] = _nonce; maxWithdrawalRootNonce = _nonce; emit WithdrawalRootHashAddition(_root, _nonce); for (uint256 i ; i < _replacedRoots.length; i++) { //inject UNINIT LOCAL/STATE VAR deleteWithdrawalRoot(_replacedRoots[i]); } } /** * @notice Removes withdrawal root hashes from active set * @param _roots The root hashes to be removed from the active set */ function removeWithdrawalRoots(bytes32[] calldata _roots) external { require(msg.sender == owner() || msg.sender == withdrawalPublisher, "Invalid sender"); for (uint256 i ; i < _roots.length; i++) { //inject UNINIT LOCAL/STATE VAR deleteWithdrawalRoot(_roots[i]); } } /** * @notice Removes a withdrawal root hash from active set * @param _root The root hash to be removed from the active set */ function deleteWithdrawalRoot(bytes32 _root) private { uint256 nonce ; //inject UNINIT LOCAL/STATE VAR require(nonce > 0, "Root not found"); delete withdrawalRootToNonce[_root]; emit WithdrawalRootHashRemoval(_root, nonce); } /********************************************************************************************** * Fallback Management *********************************************************************************************/ /** * @notice Sets the root hash of the Merkle tree containing fallback * withdrawal authorizations. * @param _root The root hash of a Merkle tree containing the fallback withdrawal * authorizations * @param _maxSupplyNonce The nonce of the latest supply whose value is reflected in the * fallback withdrawal authorizations. */ function setFallbackRoot(bytes32 _root, uint256 _maxSupplyNonce) external { require(msg.sender == owner() || msg.sender == fallbackPublisher, "Invalid sender"); require(_root != 0, "Invalid root"); require( SafeMath.add(fallbackSetDate, fallbackWithdrawalDelaySeconds) > block.timestamp, "Fallback is active" ); require( _maxSupplyNonce >= fallbackMaxIncludedSupplyNonce, "Included supply nonce decreased" ); require(_maxSupplyNonce <= supplyNonce, "Included supply nonce exceeds latest supply"); fallbackRoot = _root; fallbackMaxIncludedSupplyNonce = _maxSupplyNonce; fallbackSetDate = block.timestamp; emit FallbackRootHashSet(_root, fallbackMaxIncludedSupplyNonce, block.timestamp); } /** * @notice Resets the fallback set date to the current block's timestamp. This can be used to * delay the start of the fallback period without publishing a new root, or to deactivate the * fallback mechanism so a new fallback root may be published. */ function resetFallbackMechanismDate() external { require(msg.sender == owner() || msg.sender == fallbackPublisher, "Invalid sender"); fallbackSetDate = block.timestamp; emit FallbackMechanismDateReset(fallbackSetDate); } /** * @notice Updates the time-lock period before the fallback mechanism is activated after the * last fallback root was published. * @param _newFallbackDelaySeconds The new delay period in seconds */ function setFallbackWithdrawalDelay(uint256 _newFallbackDelaySeconds) external { require(msg.sender == owner(), "Invalid sender"); require(_newFallbackDelaySeconds != 0, "Invalid zero delay seconds"); require(_newFallbackDelaySeconds < 10 * 365 days, "Invalid delay over 10 years"); uint256 oldDelay ; //inject UNINIT LOCAL/STATE VAR fallbackWithdrawalDelaySeconds = _newFallbackDelaySeconds; emit FallbackWithdrawalDelayUpdate(oldDelay, _newFallbackDelaySeconds); } /********************************************************************************************** * Role Management *********************************************************************************************/ /** * @notice Updates the Withdrawal Publisher address, the only address other than the owner that * can publish / remove withdrawal Merkle tree roots. * @param _newWithdrawalPublisher The address of the new Withdrawal Publisher * @dev Error invalid sender. */ function setWithdrawalPublisher(address _newWithdrawalPublisher) external { require(msg.sender == owner(), "Invalid sender"); address oldValue ; //inject UNINIT LOCAL/STATE VAR withdrawalPublisher = _newWithdrawalPublisher; emit WithdrawalPublisherUpdate(oldValue, withdrawalPublisher); } /** * @notice Updates the Fallback Publisher address, the only address other than the owner that * can publish / remove fallback withdrawal Merkle tree roots. * @param _newFallbackPublisher The address of the new Fallback Publisher * @dev Error invalid sender. */ function setFallbackPublisher(address _newFallbackPublisher) external { require(msg.sender == owner(), "Invalid sender"); address oldValue ; //inject UNINIT LOCAL/STATE VAR fallbackPublisher = _newFallbackPublisher; emit FallbackPublisherUpdate(oldValue, fallbackPublisher); } /** * @notice Updates the Withdrawal Limit Publisher address, the only address other than the * owner that can set the withdrawal limit. * @param _newWithdrawalLimitPublisher The address of the new Withdrawal Limit Publisher * @dev Error invalid sender. */ function setWithdrawalLimitPublisher(address _newWithdrawalLimitPublisher) external { require(msg.sender == owner(), "Invalid sender"); address oldValue ; //inject UNINIT LOCAL/STATE VAR withdrawalLimitPublisher = _newWithdrawalLimitPublisher; emit WithdrawalLimitPublisherUpdate(oldValue, withdrawalLimitPublisher); } /** * @notice Updates the DirectTransferer address, the only address other than the owner that * can execute direct transfers * @param _newDirectTransferer The address of the new DirectTransferer */ function setDirectTransferer(address _newDirectTransferer) external { require(msg.sender == owner(), "Invalid sender"); address oldValue ; //inject UNINIT LOCAL/STATE VAR directTransferer = _newDirectTransferer; emit DirectTransfererUpdate(oldValue, directTransferer); } /** * @notice Updates the Partition Manager address, the only address other than the owner that * can add and remove permitted partitions * @param _newPartitionManager The address of the new PartitionManager */ function setPartitionManager(address _newPartitionManager) external { require(msg.sender == owner(), "Invalid sender"); address oldValue ; //inject UNINIT LOCAL/STATE VAR partitionManager = _newPartitionManager; emit PartitionManagerUpdate(oldValue, partitionManager); } /********************************************************************************************** * Operator Data Decoders *********************************************************************************************/ /** * @notice Extract flag from operatorData * @param _operatorData The operator data to be decoded * @return flag, the transfer operation type */ function _decodeOperatorDataFlag(bytes memory _operatorData) internal pure returns (bytes32) { return abi.decode(_operatorData, (bytes32)); } /** * @notice Extracts the supplier, max authorized nonce, and Merkle proof from the operator data * @param _operatorData The operator data to be decoded * @return supplier, the address whose account is authorized * @return For withdrawals: max authorized nonce, the last used withdrawal root nonce for the * supplier and partition. For fallback withdrawals: max cumulative withdrawal amount, the * maximum amount of tokens that can be withdrawn for the supplier's account, including both * withdrawals and fallback withdrawals * @return proof, the Merkle proof to be used for the authorization */ function _decodeWithdrawalOperatorData(bytes memory _operatorData) internal pure returns ( address, uint256, bytes32[] memory ) { (, address supplier, uint256 nonce, bytes32[] memory proof) = abi.decode( _operatorData, (bytes32, address, uint256, bytes32[]) ); return (supplier, nonce, proof); } /** * @notice Extracts the supply nonce from the operator data * @param _operatorData The operator data to be decoded * @return nonce, the nonce of the supply to be refunded */ function _decodeRefundOperatorData(bytes memory _operatorData) internal pure returns (uint256) { (, uint256 nonce) = abi.decode(_operatorData, (bytes32, uint256)); return nonce; } /********************************************************************************************** * Merkle Tree Verification *********************************************************************************************/ /** * @notice Hashes the supplied data and returns the hash to be used in conjunction with a proof * to calculate the Merkle tree root * @param _supplier The address whose account is authorized * @param _partition Source partition of the tokens * @param _value Number of tokens to be transferred * @param _maxAuthorizedAccountNonce The maximum existing used withdrawal nonce for the * supplier and partition * @return leaf, the hash of the supplied data */ function _calculateWithdrawalLeaf( address _supplier, bytes32 _partition, uint256 _value, uint256 _maxAuthorizedAccountNonce ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_supplier, _partition, _value, _maxAuthorizedAccountNonce)); } /** * @notice Hashes the supplied data and returns the hash to be used in conjunction with a proof * to calculate the Merkle tree root * @param _supplier The address whose account is authorized * @param _partition Source partition of the tokens * @param _maxCumulativeWithdrawalAmount, the maximum amount of tokens that can be withdrawn * for the supplier's account, including both withdrawals and fallback withdrawals * @return leaf, the hash of the supplied data */ function _calculateFallbackLeaf( address _supplier, bytes32 _partition, uint256 _maxCumulativeWithdrawalAmount ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_supplier, _partition, _maxCumulativeWithdrawalAmount)); } /** * @notice Calculates the Merkle root for the unique Merkle tree described by the provided Merkle proof and leaf hash. * @param _merkleProof The sibling node hashes at each level of the tree. * @param _leafHash The hash of the leaf data for which merkleProof is an inclusion proof. * @return The calculated Merkle root. */ function _calculateMerkleRoot(bytes32[] memory _merkleProof, bytes32 _leafHash) private pure returns (bytes32) { bytes32 computedHash ; //inject UNINIT LOCAL/STATE VAR for (uint256 i ; i < _merkleProof.length; i++) { //inject UNINIT LOCAL/STATE VAR bytes32 proofElement ; //inject UNINIT LOCAL/STATE VAR if (computedHash < proofElement) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } }
* @notice Adds the root hash of a Merkle tree containing authorized token withdrawals to the active set @param _root The root hash to be added to the active set @param _nonce The nonce of the new root hash. Must be exactly one higher than the existing max nonce. @param _replacedRoots The root hashes to be removed from the repository./
function addWithdrawalRoot( bytes32 _root, uint256 _nonce, bytes32[] calldata _replacedRoots ) external { require(msg.sender == owner() || msg.sender == withdrawalPublisher, "Invalid sender"); require(_root != 0, "Invalid root"); require(maxWithdrawalRootNonce + 1 == _nonce, "Nonce not current max plus one"); require(withdrawalRootToNonce[_root] == 0, "Nonce already used"); withdrawalRootToNonce[_root] = _nonce; maxWithdrawalRootNonce = _nonce; emit WithdrawalRootHashAddition(_root, _nonce); deleteWithdrawalRoot(_replacedRoots[i]); }
5,380,236
[ 1, 3655, 326, 1365, 1651, 434, 279, 31827, 2151, 4191, 10799, 1147, 598, 9446, 1031, 358, 326, 2695, 444, 225, 389, 3085, 1021, 1365, 1651, 358, 506, 3096, 358, 326, 2695, 444, 225, 389, 12824, 1021, 7448, 434, 326, 394, 1365, 1651, 18, 6753, 506, 8950, 1245, 10478, 2353, 326, 2062, 943, 7448, 18, 225, 389, 2079, 72, 17540, 1021, 1365, 9869, 358, 506, 3723, 628, 326, 3352, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 527, 1190, 9446, 287, 2375, 12, 203, 3639, 1731, 1578, 389, 3085, 16, 203, 3639, 2254, 5034, 389, 12824, 16, 203, 3639, 1731, 1578, 8526, 745, 892, 389, 2079, 72, 17540, 203, 565, 262, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1435, 747, 1234, 18, 15330, 422, 598, 9446, 287, 15960, 16, 315, 1941, 5793, 8863, 203, 203, 3639, 2583, 24899, 3085, 480, 374, 16, 315, 1941, 1365, 8863, 203, 3639, 2583, 12, 1896, 1190, 9446, 287, 2375, 13611, 397, 404, 422, 389, 12824, 16, 315, 13611, 486, 783, 943, 8737, 1245, 8863, 203, 3639, 2583, 12, 1918, 9446, 287, 2375, 774, 13611, 63, 67, 3085, 65, 422, 374, 16, 315, 13611, 1818, 1399, 8863, 203, 203, 3639, 598, 9446, 287, 2375, 774, 13611, 63, 67, 3085, 65, 273, 389, 12824, 31, 203, 3639, 943, 1190, 9446, 287, 2375, 13611, 273, 389, 12824, 31, 203, 203, 3639, 3626, 3423, 9446, 287, 2375, 2310, 30296, 24899, 3085, 16, 389, 12824, 1769, 203, 203, 203, 5411, 1430, 1190, 9446, 287, 2375, 24899, 2079, 72, 17540, 63, 77, 19226, 203, 3639, 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 ]
./full_match/1/0x3bE28B26574F1D3d63595f07b50eB694b5FfE4CE/sources/project_/contracts/RoorHangTag.sol
@dev Returns token type
function getToken(uint256 _tokenId) public view returns (HangTagToken memory _token) { return hangTagTokens[_tokenId]; }
3,024,396
[ 1, 1356, 1147, 618, 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, 9162, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 1476, 1135, 261, 44, 539, 1805, 1345, 3778, 389, 2316, 13, 288, 203, 3639, 327, 25733, 1805, 5157, 63, 67, 2316, 548, 15533, 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 ]
./full_match/8453/0x762eb51D2e779EeEc9B239FFB0B2eC8262848f3E/sources/contracts/OptionTokenV3.sol
@notice Returns the amount in paymentTokens for a given amount of options tokens required for the LP exercise lp @param _amount The amount of options tokens to exercise @param _discount The discount amount
function getPaymentTokenAmountForExerciseLp(uint256 _amount,uint256 _discount) public view returns (uint256 paymentAmount, uint256 paymentAmountToAddLiquidity) { paymentAmount = getLpDiscountedPrice(_amount, _discount); (uint256 underlyingReserve, uint256 paymentReserve) = IRouter(router).getReserves(underlyingToken, paymentToken, false); paymentAmountToAddLiquidity = (_amount * paymentReserve) / underlyingReserve; }
11,552,879
[ 1, 1356, 326, 3844, 316, 5184, 5157, 364, 279, 864, 3844, 434, 702, 2430, 1931, 364, 326, 511, 52, 24165, 12423, 225, 389, 8949, 1021, 3844, 434, 702, 2430, 358, 24165, 225, 389, 23650, 1021, 12137, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 22104, 1345, 6275, 1290, 424, 20603, 48, 84, 12, 11890, 5034, 389, 8949, 16, 11890, 5034, 389, 23650, 13, 1071, 1476, 1135, 261, 11890, 5034, 5184, 6275, 16, 2254, 5034, 5184, 6275, 13786, 48, 18988, 24237, 13, 203, 565, 288, 203, 3639, 5184, 6275, 273, 9014, 84, 9866, 329, 5147, 24899, 8949, 16, 389, 23650, 1769, 203, 3639, 261, 11890, 5034, 6808, 607, 6527, 16, 2254, 5034, 5184, 607, 6527, 13, 273, 467, 8259, 12, 10717, 2934, 588, 607, 264, 3324, 12, 9341, 6291, 1345, 16, 5184, 1345, 16, 629, 1769, 203, 3639, 5184, 6275, 13786, 48, 18988, 24237, 273, 261, 67, 8949, 380, 5184, 607, 6527, 13, 342, 6808, 607, 6527, 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 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./Badger.sol"; contract Karmic is Badger, Pausable { uint256 public constant FEE_PRECISION = 1 ether; // 10^18 = 100% uint256 public constant TOKENS_PER_ETH = 1000; mapping(address => BoxToken) public boxTokenTiers; uint256 public boxTokenCounter; uint256 public fee; struct BoxToken { uint256 id; uint256 amount; uint256 funds; uint256 distributed; bool passedThreshold; uint256 threshold; } event FundsDistributed( address indexed receiver, uint256 indexed tokenTier, uint256 amount ); modifier isBoxToken(address token) { require(boxTokenTiers[token].id != 0, "It is not a box token"); _; } constructor(string memory _newBaseUri, string memory _metadata, uint256 _fee) Badger(_newBaseUri) { boxTokenCounter = 1; fee = _fee; createTokenTier(0, _metadata, false, address(0)); } function setFee(uint256 _fee) external onlyOwner { fee = _fee; } function bondToMint(address token, uint256 amount) public whenNotPaused isBoxToken(token) { require(IERC20(token).transferFrom(msg.sender, address(this), amount), "transfer failed"); bytes memory data; _mint(msg.sender, boxTokenTiers[token].id, amount/TOKENS_PER_ETH, data); } function addBoxTokens( address[] memory tokens, string[] calldata tierUris, uint256[] calldata threshold ) external onlyOwner { uint256 counter = boxTokenCounter; for (uint8 i; i < tokens.length; i++) { address token = tokens[i]; require(boxTokenTiers[token].id == 0, "DUPLICATE_TOKEN"); boxTokenTiers[token].id = counter; boxTokenTiers[token].threshold = threshold[i]; createTokenTier(counter, tierUris[i], false, token); counter++; } boxTokenCounter = counter; } function withdraw(address token, uint256 amount) external whenNotPaused isBoxToken(token) { uint256 totalFunding = (boxTokenTiers[token].funds*FEE_PRECISION) / (FEE_PRECISION - fee); require( !(totalFunding >= boxTokenTiers[token].threshold), "Can withdraw only funds for tokens that didn't pass threshold" ); uint256 withdrawnFunds = (amount * totalFunding) / boxTokenTiers[token].amount; boxTokenTiers[token].funds -= withdrawnFunds - withdrawnFunds*fee/FEE_PRECISION; boxTokenTiers[address(0)].funds -= withdrawnFunds*fee/FEE_PRECISION; require(IERC20(token).transferFrom(msg.sender, address(this), amount), "transfer failed"); Address.sendValue(payable(msg.sender), withdrawnFunds); } function claimGovernanceTokens(address[] memory boxTokens) external whenNotPaused { bytes memory data; address token; for (uint8 i; i < boxTokens.length; i++) { token = boxTokens[i]; uint256 amount = IERC20(token).balanceOf(msg.sender); uint256 tokenId = boxTokenTiers[token].id; require(tokenId != 0, "It is not a box token"); require(IERC20(token).transferFrom(msg.sender, address(this), amount), "transfer failed"); _mint(msg.sender, tokenId, amount/TOKENS_PER_ETH, data); } } function distribute( address payable _receiver, uint256 _tier, uint256 _amount ) external onlyOwner { BoxToken storage boxToken = boxTokenTiers[tokenTiers[_tier].boxToken]; require(_amount != 0, "nothing to distribute"); require( boxToken.funds - boxToken.distributed >= _amount, "exceeds balance" ); boxToken.distributed += _amount; Address.sendValue(_receiver, _amount); emit FundsDistributed(_receiver, _tier, _amount); } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function getBoxTokens() public view returns (address[] memory boxTokens) { boxTokens = new address[](boxTokenCounter); for (uint8 i = 1; i <= boxTokenCounter; i++) { boxTokens[i - 1] = tokenTiers[i].boxToken; } } function allBalancesOf(address holder) external view returns (uint256[] memory balances) { balances = new uint256[](boxTokenCounter); for (uint8 i; i < boxTokenCounter; i++) { balances[i] = balanceOf(holder, i); } } receive() external whenNotPaused payable { if (boxTokenTiers[msg.sender].id != 0) { boxTokenTiers[msg.sender].amount = IERC20(msg.sender).totalSupply(); boxTokenTiers[msg.sender].funds += msg.value - (msg.value*fee/FEE_PRECISION); boxTokenTiers[address(0)].funds += (msg.value*fee/FEE_PRECISION); } else { bytes memory data; boxTokenTiers[address(0)].funds += msg.value; _mint(msg.sender, 0, msg.value, data); } } } // SPDX-License-Identifier: MIT // 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) 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: GPL-3.0-or-later // Badger is a ERC1155 token used for governance. pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./libraries/Strings.sol"; contract Badger is Ownable, ERC1155 { using Strings for string; /* State variables */ mapping(uint256 => TokenTier) public tokenTiers; // tokenId => TokenTier /* Structs */ struct TokenTier { string uriId; bool transferable; address boxToken; } /* Events */ event TierChange(uint256 indexed tokenId, string uriId, bool transferables); /* Modifiers */ modifier isSameLength( address[] calldata accounts, uint256[] calldata tokenIds, uint256[] memory amounts ) { require( accounts.length == tokenIds.length && tokenIds.length == amounts.length, "Input array mismatch" ); _; } modifier isTier(uint256 tokenId) { require( !_isEmptyString(tokenTiers[tokenId].uriId), "Tier does not exist" ); _; } modifier isValidString(string memory uriId) { require(!_isEmptyString(uriId), "String cannot be empty"); _; } modifier onlyGeneralToken(uint256 id) { require( tokenTiers[id].boxToken == address(0), "only on general tokens" ); _; } /* Constructor */ constructor(string memory _newBaseUri) ERC1155(_newBaseUri) {} /* Minting & burning */ /** * @dev mints specified amount token(s) of specific id to specified account * @param account beneficiary address * @param id id of token, aka. tier * @param amount units of token to be minted to beneficiary */ function mint( address account, uint256 id, uint256 amount ) public onlyOwner onlyGeneralToken(id) { bytes memory data; _mint(account, id, amount, data); } /** * @dev burns specified amount token(s) of specific id from specified account * @param account address of token holder * @param id id of token, aka. tier * @param amount units of token to be burnt from beneficiary */ function burn( address account, uint256 id, uint256 amount ) public onlyOwner onlyGeneralToken(id) { _burn(account, id, amount); } /** * @dev mints to multiple addresses arbitrary units of tokens of ONE token id per address * @notice example: mint 3 units of tokenId 1 to alice and 4 units of tokenId 2 to bob * @param accounts list of beneficiary addresses * @param tokenIds list of token ids (aka tiers) * @param amounts list of mint amounts */ function mintToMultiple( address[] calldata accounts, uint256[] calldata tokenIds, uint256[] calldata amounts ) public onlyOwner isSameLength(accounts, tokenIds, amounts) { bytes memory data; for (uint256 i = 0; i < accounts.length; i++) { require( tokenTiers[tokenIds[i]].boxToken == address(0), "Can mint only general tokens" ); _mint(accounts[i], tokenIds[i], amounts[i], data); } } /** * @dev burns from multiple addresses arbitrary units of tokens of ONE token id per address * example: burn 3 units of tokenId 1 from alice and 4 units of tokenId 2 froms bob * @param accounts list of token holder addresses * @param tokenIds list of token ids (aka tiers) * @param amounts list of burn amounts */ function burnFromMultiple( address[] calldata accounts, uint256[] calldata tokenIds, uint256[] calldata amounts ) public onlyOwner isSameLength(accounts, tokenIds, amounts) { for (uint256 i = 0; i < accounts.length; i++) { require( tokenTiers[tokenIds[i]].boxToken == address(0), "Can burn only general tokens" ); _burn(accounts[i], tokenIds[i], amounts[i]); } } /* Transferring */ /** * @dev transfers tokens from one address to another and uses 0x0 as default data parameter * @notice this is mainly used for manual contract interactions via etherscan * @param from address from which token will be transferred * @param to recipient of address * @param id id of token to be transferred * @param amount amount of token to be transferred */ function transferFromWithoutData( address from, address to, uint256 id, uint256 amount ) public { bytes memory data; _safeTransferFrom(from, to, id, amount, data); } /** * @dev transfers tokens from one address to another allowing custom data parameter * @notice this is the standard transfer interface for ERC1155 tokens which contracts expect * @param from address from which token will be transferred * @param to recipient of address * @param id id of token to be transferred * @param amount amount of token to be transferred */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public override { require( owner() == _msgSender() || from == _msgSender() || isApprovedForAll(from, _msgSender()), "Unauthorized" ); _safeTransferFrom(from, to, id, amount, data); } /* Configuration */ /** * @dev sets a base uri, that is the first part of the url where the metadata for a tokenId is stored * @param _newBaseUri baseUrl (e.g. www.filestoring.com/) */ function changeBaseUri(string calldata _newBaseUri) public onlyOwner isValidString(_newBaseUri) { _setURI(_newBaseUri); } /** * @dev creates a new token tier * @param tokenId identifier for the new token tier * @param uriId identifier that is appended to the baseUri together forming the uri where the metadata lives * @param transferable determines if tokens from specific tier should be transferable or not */ function createTokenTier( uint256 tokenId, string memory uriId, bool transferable, address boxToken ) public onlyOwner isValidString(uriId) { require( _isEmptyString(tokenTiers[tokenId].uriId), "Tier already exists for tokenId" ); tokenTiers[tokenId] = TokenTier(uriId, transferable, boxToken); emit TierChange(tokenId, uriId, transferable); } /** * @dev updates the identifier that is appended to the baseUri for a specific tokenId (tier) * @param tokenId tokenId for which the uri should be updated * @param uriId identifier that is appended to the baseUri together forming the uri where the metadata lives */ function updateUriIdentifier(uint256 tokenId, string calldata uriId) public onlyOwner { _updateUriIdentifier(tokenId, uriId); } /** * @dev update uri identifiers for multiple token ids (tiers) * @param tokenIds tokenIds for which the uri should be updated (must be in same order as uriIds) * @param uriIds identifiers that are appended to the baseUri together forming the uri where the metadata lives (must be in same order ass tokenIds) */ function updateMultipleUriIdentifiers( uint256[] calldata tokenIds, string[] calldata uriIds ) public onlyOwner { require(tokenIds.length == uriIds.length, "Input array mismatch"); for (uint8 i = 0; i < tokenIds.length; i++) { _updateUriIdentifier(tokenIds[i], uriIds[i]); } } /** * @dev updates transferability for a given token id (tier) * @param tokenId tokenId for which transferability should be updated * @param transferable determines whether tokens from tier should be transferable or not */ function updateTransferableStatus(uint256 tokenId, bool transferable) public onlyOwner isTier(tokenId) { tokenTiers[tokenId].transferable = transferable; emit TierChange(tokenId, tokenTiers[tokenId].uriId, transferable); } /* Queries */ /** * @dev returns the uri for a given token * @notice consists of a concatenation of baseUri and uriId * @param tokenId tokenId for which the uri should be retrieved */ function uri(uint256 tokenId) public view virtual override returns (string memory) { string memory baseUri = super.uri(tokenId); return baseUri.append(tokenTiers[tokenId].uriId); } /* Internal functions */ function _updateUriIdentifier(uint256 tokenId, string calldata uriId) private isTier(tokenId) isValidString(uriId) { tokenTiers[tokenId].uriId = uriId; emit TierChange(tokenId, uriId, tokenTiers[tokenId].transferable); } function _isEmptyString(string memory uriId) internal pure returns (bool) { return bytes(uriId).length == 0; } function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal override isTier(id) { super._mint(account, id, amount, data); } function _burn( address account, uint256 id, uint256 amount ) internal override isTier(id) { super._burn(account, id, amount); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { if (to != address(0) && from != address(0)) { require( owner() == _msgSender() || from == _msgSender() || isApprovedForAll(from, _msgSender()), "Unauthorized" ); for (uint256 i; i < ids.length; i++) { require( tokenTiers[ids[i]].transferable, "Transfer disabled for this tier" ); } } } } // 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 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // 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: Unlicense pragma solidity ^0.8.0; library Strings { function append(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 returns the uri for a given token @notice consists of a concatenation of baseUri and uriId @param tokenId tokenId for which the uri should be retrieved/
function uri(uint256 tokenId) public view virtual override returns (string memory) { string memory baseUri = super.uri(tokenId); return baseUri.append(tokenTiers[tokenId].uriId); }
10,039,465
[ 1, 6154, 326, 2003, 364, 279, 864, 1147, 9079, 20915, 434, 279, 26833, 434, 23418, 471, 2003, 548, 225, 1147, 548, 4202, 1147, 548, 364, 1492, 326, 2003, 1410, 506, 10295, 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, 2003, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 533, 3778, 23418, 273, 2240, 18, 1650, 12, 2316, 548, 1769, 203, 3639, 327, 23418, 18, 6923, 12, 2316, 56, 20778, 63, 2316, 548, 8009, 1650, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x821621ffF51783ce7f14fDe29628E850A23EFaf2/sources/contracts/1_Storage.sol
* Mints 7000 Warriors/
function mintWarriors(uint256 numberOfTokens) external payable { require(IS_WARRIORS_MINT_ACTIVE, "Warriors Mint is Not Active"); require((totalSupply()+numberOfTokens) <= 10000, "Warriors Mint Finished"); require(msg.value == (numberOfTokens * WARRIORS_PRICE), "Wrong Eth value sent"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } }
780,598
[ 1, 49, 28142, 2371, 3784, 678, 297, 566, 1383, 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, 445, 312, 474, 30634, 566, 1383, 12, 11890, 5034, 7922, 5157, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 5127, 67, 16777, 2259, 14006, 67, 49, 3217, 67, 13301, 16, 315, 30634, 566, 1383, 490, 474, 353, 2288, 8857, 8863, 203, 3639, 2583, 12443, 4963, 3088, 1283, 1435, 15, 2696, 951, 5157, 13, 1648, 12619, 16, 315, 30634, 566, 1383, 490, 474, 29745, 8863, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 261, 2696, 951, 5157, 380, 678, 985, 2259, 14006, 67, 7698, 1441, 3631, 315, 13634, 512, 451, 460, 3271, 8863, 203, 540, 203, 3639, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 7922, 5157, 31, 277, 27245, 288, 203, 5411, 2254, 312, 474, 1016, 273, 2078, 3088, 1283, 5621, 203, 5411, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 312, 474, 1016, 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 ]
./full_match/80001/0xA5a200D7270EC35f926139C3CCa433bC2c090974/sources/project_/contracts/ConfirmedOwnerWithProposal.sol
* @title The ConfirmedOwner contract @notice A contract with helpers for basic contract ownership./
contract ConfirmedOwnerWithProposal is OwnableInterface { address private s_owner; address private s_pendingOwner; event OwnershipTransferRequested(address indexed from, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); pragma solidity ^0.8.0; constructor(address newOwner, address pendingOwner) { require(newOwner != address(0), "Cannot set owner to zero"); s_owner = newOwner; if (pendingOwner != address(0)) { _transferOwnership(pendingOwner); } } constructor(address newOwner, address pendingOwner) { require(newOwner != address(0), "Cannot set owner to zero"); s_owner = newOwner; if (pendingOwner != address(0)) { _transferOwnership(pendingOwner); } } function transferOwnership(address to) public override onlyOwner { _transferOwnership(to); } function acceptOwnership() external override { require(msg.sender == s_pendingOwner, "Must be proposed owner"); address oldOwner = s_owner; s_owner = msg.sender; s_pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } function owner() public view override returns (address) { return s_owner; } function _transferOwnership(address to) private { require(to != msg.sender, "Cannot transfer to self"); s_pendingOwner = to; emit OwnershipTransferRequested(s_owner, to); } function _validateOwnership() internal view { require(msg.sender == s_owner, "Only callable by owner"); } modifier onlyOwner() { _validateOwnership(); _; } }
5,629,520
[ 1, 1986, 9675, 11222, 5541, 6835, 225, 432, 6835, 598, 9246, 364, 5337, 6835, 23178, 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 ]
[ 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, 16351, 9675, 11222, 5541, 1190, 14592, 353, 14223, 6914, 1358, 288, 203, 225, 1758, 3238, 272, 67, 8443, 31, 203, 225, 1758, 3238, 272, 67, 9561, 5541, 31, 203, 203, 225, 871, 14223, 9646, 5310, 5912, 11244, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 1769, 203, 225, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 225, 3885, 12, 2867, 394, 5541, 16, 1758, 4634, 5541, 13, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 4515, 444, 3410, 358, 3634, 8863, 203, 203, 565, 272, 67, 8443, 273, 394, 5541, 31, 203, 565, 309, 261, 9561, 5541, 480, 1758, 12, 20, 3719, 288, 203, 1377, 389, 13866, 5460, 12565, 12, 9561, 5541, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 225, 3885, 12, 2867, 394, 5541, 16, 1758, 4634, 5541, 13, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 4515, 444, 3410, 358, 3634, 8863, 203, 203, 565, 272, 67, 8443, 273, 394, 5541, 31, 203, 565, 309, 261, 9561, 5541, 480, 1758, 12, 20, 3719, 288, 203, 1377, 389, 13866, 5460, 12565, 12, 9561, 5541, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 225, 445, 7412, 5460, 12565, 12, 2867, 358, 13, 1071, 3849, 1338, 5541, 288, 203, 565, 389, 13866, 5460, 12565, 12, 869, 1769, 203, 225, 289, 203, 203, 225, 445, 2791, 5460, 12565, 1435, 3903, 3849, 288, 2 ]
./full_match/1/0x88e7b8D78B2D6BC748307E02dc8dd4F784C911Dc/sources/USDTToken.sol
* @dev ERC20Token implementation/
contract USDTToken is ERC20Base, Ownable { constructor( uint256 initialSupply_, address feeReceiver_ ) payable ERC20Base("USDT", "USDT", 18, 0x312f313638373936332f4f) { require(initialSupply_ > 0, "Initial supply cannot be zero"); payable(feeReceiver_).transfer(msg.value); _mint(_msgSender(), initialSupply_); } }
3,040,522
[ 1, 654, 39, 3462, 1345, 4471, 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, 16351, 11836, 9081, 1345, 353, 4232, 39, 3462, 2171, 16, 14223, 6914, 288, 203, 565, 3885, 12, 203, 3639, 2254, 5034, 2172, 3088, 1283, 67, 16, 203, 3639, 1758, 14036, 12952, 67, 203, 203, 565, 262, 8843, 429, 4232, 39, 3462, 2171, 2932, 3378, 9081, 3113, 315, 3378, 9081, 3113, 6549, 16, 374, 92, 23, 2138, 74, 23, 3437, 4449, 28, 6418, 5520, 23, 4449, 1578, 74, 24, 74, 13, 288, 203, 3639, 2583, 12, 6769, 3088, 1283, 67, 405, 374, 16, 315, 4435, 14467, 2780, 506, 3634, 8863, 203, 3639, 8843, 429, 12, 21386, 12952, 67, 2934, 13866, 12, 3576, 18, 1132, 1769, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 2172, 3088, 1283, 67, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]