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
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; 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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() {} function _call() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgSender() internal view returns (address payable) { return payable(msg.sender); } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address call = _call(); _owner = call; owner = call; emit OwnershipTransferred(address(0), call); } modifier onlyOwner() { require(_owner == _call(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Token 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() { _name = "Samurai Inu"; _symbol = "SAMINU"; _decimals = 18; _totalSupply = 10000000000 * 10**18; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @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 override returns (uint256) { return _totalSupply; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) external view override 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: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {ERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub( amount, "ERC20: burn amount exceeds allowance" ) ); } }
* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./
contract Ownable is Context { address private _owner; address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address call = _call(); _owner = call; owner = call; emit OwnershipTransferred(address(0), call); } modifier onlyOwner() { require(_owner == _call(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
10,247,483
[ 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, 16351, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 565, 1758, 1071, 3410, 31, 203, 377, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 565, 3885, 1832, 288, 203, 3639, 1758, 745, 273, 389, 1991, 5621, 203, 3639, 389, 8443, 273, 745, 31, 203, 3639, 3410, 273, 745, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 745, 1769, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 24899, 8443, 422, 389, 1991, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 3410, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 5460, 429, 30, 394, 3410, 353, 326, 3634, 1758, 8863, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 394, 5541, 1769, 203, 3639, 389, 8443, 273, 394, 5541, 31, 203, 377, 203, 565, 289, 203, 377, 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 ]
./full_match/9001/0x913A3070694B9dba810e3068FE669e3cE8c3666E/sources/src/Helpers/Swapper.sol
@dev Executes swaps and checks that DEXs used are in the allowList @param _lifiData LiFi tracking data @param _swapData Array of data used to execute swaps
function _executeSwaps(LiFiData memory _lifiData, LibSwap.SwapData[] calldata _swapData) private noLeftovers(_swapData) { for (uint256 i = 0; i < _swapData.length; i++) { LibSwap.SwapData calldata currentSwapData = _swapData[i]; if ( !(appStorage.dexAllowlist[currentSwapData.approveTo] && appStorage.dexAllowlist[currentSwapData.callTo] && appStorage.dexFuncSignatureAllowList[bytes32(currentSwapData.callData[:8])]) ) revert ContractCallNotAllowed(); LibSwap.swap(_lifiData.transactionId, currentSwapData); } }
11,532,682
[ 1, 9763, 1352, 6679, 471, 4271, 716, 2030, 60, 87, 1399, 854, 316, 326, 1699, 682, 225, 389, 80, 704, 751, 27897, 42, 77, 11093, 501, 225, 389, 22270, 751, 1510, 434, 501, 1399, 358, 1836, 1352, 6679, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8837, 6050, 6679, 12, 28762, 42, 77, 751, 3778, 389, 80, 704, 751, 16, 10560, 12521, 18, 12521, 751, 8526, 745, 892, 389, 22270, 751, 13, 203, 3639, 3238, 203, 3639, 1158, 1682, 74, 869, 2496, 24899, 22270, 751, 13, 203, 565, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 22270, 751, 18, 2469, 31, 277, 27245, 288, 203, 5411, 10560, 12521, 18, 12521, 751, 745, 892, 783, 12521, 751, 273, 389, 22270, 751, 63, 77, 15533, 203, 5411, 309, 261, 203, 7734, 401, 12, 2910, 3245, 18, 561, 7009, 1098, 63, 2972, 12521, 751, 18, 12908, 537, 774, 65, 597, 203, 10792, 595, 3245, 18, 561, 7009, 1098, 63, 2972, 12521, 751, 18, 1991, 774, 65, 597, 203, 10792, 595, 3245, 18, 561, 2622, 5374, 7009, 682, 63, 3890, 1578, 12, 2972, 12521, 751, 18, 1991, 751, 10531, 28, 5717, 5717, 203, 5411, 262, 15226, 13456, 1477, 19354, 5621, 203, 5411, 10560, 12521, 18, 22270, 24899, 80, 704, 751, 18, 7958, 548, 16, 783, 12521, 751, 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 ]
//SPDX-License-Identifier: Unlicense pragma solidity 0.8.10; import "@interest-protocol/contracts/OracleV1.sol"; //solhint-disable-next-line no-empty-blocks contract TestOracleV1 is OracleV1 { }
solhint-disable-next-line no-empty-blocks
contract TestOracleV1 is OracleV1 { pragma solidity 0.8.10; }
12,623,145
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 5531, 17, 7996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7766, 23601, 58, 21, 353, 28544, 58, 21, 288, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 2163, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.1; contract AdminInterface { function addCandidate( address payable _candidateAddr ) public returns(bool); function deleteCandidate( address payable _candidateAddr ) public returns(bool); function setCapacity( uint _capacity ) public returns(bool); function addCoinBase( address payable _coinBase ) public returns(bool); function initHolderAddr( address payable _coinBase, address payable _holderAddr ) public returns(bool); function calVoteResult() public returns(bool); } contract VoteInterface { /** * 投票 */ function vote( address payable voterAddr, address payable candidateAddr, uint num ) public returns(bool); /** * 用于批量投票 */ function batchVote( address payable voterAddr, address payable[] memory candidateAddrs, uint[] memory nums ) public returns(bool); function updateCoinBase( address payable _coinBase, address payable _newCoinBase ) public returns(bool); function setHolderAddr( address payable _coinBase, address payable _holderAddr ) public returns(bool); function updateCandidateAddr( address payable _candidateAddr, address payable _newCandidateAddr ) public returns(bool); /** * 撤回对某个候选人的投票 */ function cancelVoteForCandidate( address payable voterAddr, address payable candidateAddr, uint num ) public returns(bool); function refreshVoteForAll() public returns(bool); function refreshVoteForVoter(address payable voterAddr) public returns(bool); } contract FetchVoteInterface { /** * 是否为竞选阶段 */ function isRunUpStage() public view returns (bool); /** * 获取所有候选人的详细信息 */ function fetchAllCandidates() public view returns ( address payable[] memory ); /** * 获取所有投票人的详细信息 */ function fetchAllVoters() public view returns ( address payable[] memory, uint[] memory ); /** * 获取所有投票人的投票情况 */ function fetchVoteInfoForVoter( address payable voterAddr ) public view returns ( address payable[] memory, uint[] memory ); /** * 获取某个候选人的总得票数 */ function fetchVoteNumForCandidate( address payable candidateAddr ) public view returns (uint); /** * 获取某个投票人已投票数 */ function fetchVoteNumForVoter( address payable voterAddr ) public view returns (uint); /** * 获取某个候选人被投票详细情况 */ function fetchVoteInfoForCandidate( address payable candidateAddr ) public view returns ( address payable[] memory, uint[] memory ); /** * 获取某个投票人对某个候选人投票数量 */ function fetchVoteNumForVoterToCandidate( address payable voterAddr, address payable candidateAddr ) public view returns (uint); /** * 获取所有候选人的得票情况 */ function fetchAllVoteResult() public view returns ( address payable[] memory, uint[] memory ); function getHolderAddr( address payable _coinBase ) public view returns ( address payable ); function getAllCoinBases( ) public view returns ( address payable[] memory ); } contract Ownable { address payable public owner; modifier onlyOwner { require(msg.sender == owner); // Do not forget the "_;"! It will be replaced by the actual function // body when the modifier is used. _; } function transferOwnership( address payable newOwner ) onlyOwner public returns(bool) { addAdmin(newOwner); deleteAdmin(owner); owner = newOwner; return true; } function getOwner() public view returns ( address payable ) { return owner; } // 合约管理员,可以添加和删除候选人 mapping (address => address payable) public adminMap; modifier onlyAdmin { require(adminMap[msg.sender] != address(0)); _; } function addAdmin(address payable addr) onlyOwner public returns(bool) { require(adminMap[addr] == address(0)); adminMap[addr] = addr; return true; } function deleteAdmin(address payable addr) onlyOwner public returns(bool) { require(adminMap[addr] != address(0)); adminMap[addr] = address(0); return true; } } contract Monitor { function doVoted( address payable voterAddr, address payable candidateAddr, uint num, uint blockNumber )public returns(bool); } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, // but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't // hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is * greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract NodeBallot is Ownable ,AdminInterface,VoteInterface,FetchVoteInterface { using SafeMath for uint256; struct Candidate{ address payable candidateAddr; bool isValid; uint voteNumber; } Candidate[] candidateArray;//候选者的数组 mapping (address => uint) candidateIndexMap;//候选者地址=>候选者数组下标 struct Voter{ address payable voterAddr; uint voteNumber; mapping (uint=> uint) candidateVoteNumberMap;//候选者数组下标=>投票数 } Voter[] voterArray;//投票者的数组 mapping (address => uint) voterIndexMap;//投票者地址=>投票者数组下标 address payable[] coinBaseArray;//高性能节点地址数组 mapping (address => uint) coinBaseIndexMap;//高性能节点地址=>高性能节点数组下标 mapping (address => address payable) holderMap;//高性能节点地址=>持币地址 uint public capacity=105;//最终获选者总数(容量,获选者数量上限)默认105个 bool isRunUps=true;//竞选准备阶段 uint _gasLeftLimit=500000;//对于过于复杂操作,无法一步完成,那么必须分步进行 bool isCalVoteResult=false;//是否真正计算竞选结果,如果正在计算过程中中断投票直到完成竞选 // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; //默认操作员,这里一般是官方发布的代理合约作为操作员,并且操作源头仍然必须是本人(这个在代理合约中编写的逻辑) address payable private _defaultOperator; Monitor monitor; address public _defaultMonitor; uint public minLimit=100 finney;//最小投票数量限额:0.1HPB,可外部设置 event ApprovalFor( bool indexed approved, address payable indexed operator, address payable indexed owner ); event CandidateAdded( address payable indexed candidateAddr ); event AddCoinBase( address payable indexed coinBase ); event UpdateCoinBase( address payable indexed coinBase, address payable indexed newCoinBase ); event SetHolderAddr( address payable indexed coinBase, address payable indexed holderAddr ); event CandidateDeleted( address payable indexed candidateAddr ); event UpdateCandidateAddr( address payable indexed _candidateAddr, address payable indexed _newCandidateAddr ); event DoVoted(// 投票 flag=1为投票,flag=0为撤票 uint indexed flag, address payable indexed candidateAddr, address payable indexed voteAddr, uint num ); //记录发送HPB的发送者地址和发送的金额 event ReceivedHpb( address payable indexed sender, uint amount ); //接受HPB转账 function () payable external { emit ReceivedHpb(msg.sender, msg.value); } //销毁合约,并把合约余额返回给合约拥有者 function kill() onlyOwner public returns(bool) { selfdestruct(owner); return true; } //合约拥有者提取合约余额的一部分 function withdraw( uint _value ) onlyOwner payable public returns(bool) { require(address(this).balance >= _value); owner.transfer(_value); return true; } modifier onlyApproved( address payable addr ) { require(!isCalVoteResult);//正在计算竞选结果中,不允许操作 require(isApproved(addr, msg.sender));//必须经过该地址允许才能操作 _; } /** *用户指定允许代理其对合约操作的权限的操作员 */ function setApproval( address payable to, bool approved ) public returns(bool) { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalFor(approved, to, msg.sender); return true; } function isApproved( address payable addr, address payable operator ) public view returns (bool) { if (addr == operator) {//如果是自己,默认允许 return true; } else if (_operatorApprovals[addr][operator]) { return true; } else {//如果是官方代理合约,并且操作源是本人也会允许 return tx.origin == addr && operator == _defaultOperator; } } /** *设置最小允许的投票数 */ function setMinLimit( uint _minLimit ) onlyAdmin public returns(bool) { minLimit = _minLimit; return true; } /** *对投票合约设置默认的代理操作合约,便于间接的操作投票合约 */ function setDefaultOperator( address payable defaultOperator ) onlyAdmin public returns(bool) { require(_defaultOperator != msg.sender); _defaultOperator = defaultOperator; adminMap[_defaultOperator] = _defaultOperator; return true; } function setDefaultMonitor( address payable defaultMonitor ) onlyAdmin public returns(bool) { _defaultMonitor = defaultMonitor; monitor=Monitor(_defaultMonitor); return true; } /** * 构造函数 初始化投票智能合约的部分依赖参数 */ constructor () payable public { owner = msg.sender; // 设置默认管理员 adminMap[owner] = owner; voterArray.push(Voter(address(0),0)); candidateArray.push(Candidate(address(0),false,0)); coinBaseArray.push(address(0)); } /** * 设置最终获选者总数 */ function setCapacity( uint _capacity ) onlyAdmin public returns(bool) { capacity = _capacity; return true; } /** * 是否还在竞选准备阶段 */ function isRunUpStage() public view returns (bool) { return isRunUps; } /** * 为了防止因为gas消耗超出而导致本次操作失败 */ function setGasLeftLimit(uint gasLeftLimit) onlyAdmin public returns (bool) { _gasLeftLimit=gasLeftLimit; return true; } /** * 增加候选者 */ function addCandidate( address payable _candidateAddr ) onlyAdmin public returns(bool) { require(isRunUps); //必须是竞选准备阶段 // 必须候选人地址还未使用 require(candidateIndexMap[_candidateAddr] == 0); candidateIndexMap[_candidateAddr]= candidateArray. push(Candidate(_candidateAddr,true,0))-1; _operatorApprovals[_candidateAddr][owner] = true; if(msg.sender!= owner){ _operatorApprovals[_candidateAddr][msg.sender] = true; } emit CandidateAdded(_candidateAddr); return true; } function addCoinBase( address payable _coinBase ) onlyAdmin public returns(bool) { require(!isRunUps); //必须是竞选结束阶段 require(coinBaseIndexMap[_coinBase] == 0); coinBaseIndexMap[_coinBase]=coinBaseArray.push(_coinBase)-1; emit AddCoinBase(_coinBase); return true; } function getAllCoinBases( ) public view returns ( address payable[] memory ) { if(coinBaseArray.length<2){ return (new address payable[](0)); } uint vcl=coinBaseArray.length - 1; address payable[] memory _coinBases=new address payable[](vcl); for (uint i = 1;i <= vcl;i++) { _coinBases[i-1] = coinBaseArray[i]; } return (_coinBases); } function updateCoinBase( address payable _coinBase, address payable _newCoinBase ) onlyApproved(_coinBase) public returns(bool) { require(!isRunUps); // 必须是竞选结束阶段 require(coinBaseIndexMap[_coinBase]!= 0); coinBaseArray[coinBaseIndexMap[_coinBase]]=_newCoinBase; coinBaseIndexMap[_newCoinBase]=coinBaseIndexMap[_coinBase]; coinBaseIndexMap[_coinBase]=0; if(candidateIndexMap[_coinBase]!= 0){ require(updateCandidateAddr(_coinBase,_newCoinBase)); } emit UpdateCoinBase(_coinBase,_newCoinBase); return true; } function setHolderAddr( address payable _coinBase, address payable _holderAddr ) onlyApproved(_coinBase) onlyApproved(_holderAddr) public returns(bool) { require(!isRunUps); //必须是竞选结束阶段 require(coinBaseIndexMap[_coinBase]!= 0); require(!isHolderAddrExist(_holderAddr));//持币地址不可以重复 holderMap[_coinBase]=_holderAddr; emit SetHolderAddr(_coinBase,_holderAddr); return true; } function initHolderAddr( address payable _coinBase, address payable _holderAddr ) onlyAdmin public returns(bool) { require(coinBaseIndexMap[_coinBase]!= 0); require(holderMap[_coinBase]==address(0));//管理员只能初始化一次,如果再次修改只能是节点自己来修改 require(!isHolderAddrExist(_holderAddr));//持币地址不可以重复 holderMap[_coinBase]=_holderAddr; emit SetHolderAddr(_coinBase,_holderAddr); return true; } function isHolderAddrExist( address payable _holderAddr ) public view returns(bool){ bool isExist=false; for(uint i=1;i<coinBaseArray.length;i++){ if(_holderAddr==getHolderAddr(coinBaseArray[i])){ isExist=true; break; } } return isExist; } function getHolderAddr( address payable _coinBase ) public view returns ( address payable ){ if(coinBaseIndexMap[_coinBase]== 0){ return address(0); } if(holderMap[_coinBase]==address(0)){ return _coinBase; } return holderMap[_coinBase]; } /** * 删除候选者 * @param _candidateAddr 候选者账户地址 */ function deleteCandidate( address payable _candidateAddr ) onlyAdmin public returns(bool){ require(isRunUps);//必须是竞选准备阶段 uint candidateIndex=candidateIndexMap[_candidateAddr]; require(candidateIndex != 0); candidateArray[candidateIndex].isValid=false; candidateArray[candidateIndex].voteNumber=0; // 撤销该候选者对应的投票者关联的投票数据 for (uint n=1;n <voterArray.length;n++) { if(voterArray[n].voteNumber>0){ if(voterArray[n].candidateVoteNumberMap[candidateIndex]>0){ voterArray[n].voteNumber=voterArray[n].voteNumber.sub( voterArray[n].candidateVoteNumberMap[candidateIndex]); voterArray[n].candidateVoteNumberMap[candidateIndex]=0; } } } emit CandidateDeleted(_candidateAddr); return true; } function updateCandidateAddr( address payable _candidateAddr, address payable _newCandidateAddr ) onlyApproved(_candidateAddr) public returns(bool) { // 判断候选人是否已经存在 Judge whether candidates exist. uint candidateIndex =candidateIndexMap[_candidateAddr]; require(candidateIndex != 0); candidateArray[candidateIndex].candidateAddr= _newCandidateAddr; candidateIndexMap[_newCandidateAddr] = candidateIndex; candidateIndexMap[_candidateAddr] = 0; emit UpdateCandidateAddr(_candidateAddr, _newCandidateAddr); return true; } /** * 投票 */ function vote( address payable voterAddr, address payable candidateAddr, uint num ) onlyApproved(voterAddr) public returns(bool){ // 刷新所有的投票结果 require(refreshVoteForAll()); uint voterIndex=voterIndexMap[voterAddr]; // 如果从没投过票,就添加投票人 if (voterIndex == 0) { voterIndex = voterArray.push(Voter(voterAddr,0))-1; voterIndexMap[voterAddr] = voterIndex; } require(voterAddr.balance>=num.add(voterArray[voterIndex].voteNumber)); return _doVote(voterIndex,candidateAddr, num); } /** * 执行投票 do vote */ function _doVote( uint voterIndex, address payable candidateAddr, uint num ) internal returns(bool){ // 不少于允许的最小投票数 require(num > minLimit); uint candidateIndex=candidateIndexMap[candidateAddr]; // 候选人必须存在 require(candidateIndex!= 0); require(candidateArray[candidateIndex].isValid); voterArray[voterIndex].candidateVoteNumberMap[candidateIndex]= num.add(voterArray[voterIndex].candidateVoteNumberMap[candidateIndex]); // 投票人已投总数累加 voterArray[voterIndex].voteNumber=num.add(voterArray[voterIndex].voteNumber); // 候选者得票数累加 candidateArray[candidateIndex].voteNumber = num.add(candidateArray[candidateIndex].voteNumber); emit DoVoted(1,candidateAddr,voterArray[voterIndex].voterAddr,num); if(_defaultMonitor!=address(0)){ monitor.doVoted( voterArray[voterIndex].voterAddr, candidateAddr, voterArray[voterIndex].candidateVoteNumberMap[candidateIndex], block.number ); } return true; } /** * 用于批量投票 */ function batchVote( address payable voterAddr, address payable[] memory candidateAddrs, uint[] memory nums ) onlyApproved(voterAddr) public returns(bool){ require(candidateAddrs.length==nums.length); // 刷新所有的投票结果 require(refreshVoteForAll()); uint voterIndex=voterIndexMap[voterAddr]; // 如果从没投过票,就添加投票人 if (voterIndex == 0) { voterIndex = voterArray.push(Voter(voterAddr,0))-1; voterIndexMap[voterAddr] = voterIndex; } for (uint i=0;i<candidateAddrs.length;i++) { require(_doVote(voterIndex,candidateAddrs[i], nums[i])); } require(voterAddr.balance>=voterArray[voterIndex].voteNumber); return true; } function refreshVoteForAll() public returns(bool) { if(voterArray.length>0){ for (uint i=1;i<voterArray.length;i++) { if(voterArray[i].voteNumber>0){ require(_innerRefreshVoter(i)); } if(gasleft()<_gasLeftLimit){ break; } } } return true; } function refreshVoteForVoter( address payable voterAddr ) public returns(bool){ uint voterIndex=voterIndexMap[voterAddr]; if (voterIndex!= 0) { if(voterArray[voterIndex].voteNumber>0){ require(_innerRefreshVoter(voterIndex)); } } return true; } function _innerRefreshVoter( uint voterIndex ) internal returns(bool){ uint balance=voterArray[voterIndex].voterAddr.balance; if (balance <=minLimit){//如果账户余额少于最小投票数量限额,全部撤销 for (uint k = 1;k <candidateArray.length;k++) { uint oldNum= voterArray[voterIndex].candidateVoteNumberMap[k]; if(oldNum>0){ require(_cancelVote(voterIndex, k, oldNum)); } } }else{ uint voteNumber=voterArray[voterIndex].voteNumber; if(balance<voteNumber){//如果账户余额少于已投票数 for (uint k=1;k<candidateArray.length;k++) { uint oldNum= voterArray[voterIndex].candidateVoteNumberMap[k]; if(oldNum>0){ uint remainNum=oldNum.mul(balance).div(voteNumber); if(remainNum <= minLimit) { require(_cancelVote(voterIndex, k, oldNum)); }else{ require(_cancelVote(voterIndex, k, oldNum.sub(remainNum))); } } } } } return true; } /** * 撤回对某个候选人的投票 */ function cancelVoteForCandidate( address payable voterAddr, address payable candidateAddr, uint num ) onlyApproved(voterAddr) public returns(bool) { uint voterIndex=voterIndexMap[voterAddr]; require(voterIndex != 0); uint candidateIndex=candidateIndexMap[candidateAddr]; require(candidateIndex != 0); require(candidateArray[candidateIndex].isValid); uint oldNum=voterArray[voterIndex].candidateVoteNumberMap[candidateIndex]; require(oldNum >= num); uint remainNum=oldNum.sub(num); if (remainNum <=minLimit) { require(_cancelVote(voterIndex,candidateIndex, oldNum)); }else{ require(_cancelVote(voterIndex, candidateIndex, num)); } return true; } function _cancelVote( uint voterIndex, uint candidateIndex, uint num ) internal returns(bool){ voterArray[voterIndex].candidateVoteNumberMap[candidateIndex] = voterArray[voterIndex].candidateVoteNumberMap[candidateIndex].sub(num); voterArray[voterIndex].voteNumber = voterArray[voterIndex].voteNumber.sub(num); candidateArray[candidateIndex].voteNumber = candidateArray[candidateIndex].voteNumber.sub(num); emit DoVoted( 0, candidateArray[candidateIndex].candidateAddr, voterArray[voterIndex].voterAddr, num ); if(_defaultMonitor!=address(0)){ monitor.doVoted( voterArray[voterIndex].voterAddr, candidateArray[candidateIndex].candidateAddr, voterArray[voterIndex].candidateVoteNumberMap[candidateIndex], block.number ); } return true; } /** * 计算选举结果 */ function calVoteResult() onlyAdmin public returns(bool) { require(isRunUps); // 必须是竞选准备阶段 refreshVoteForAll(); uint candidateLength=candidateArray.length; if (candidateLength>capacity.add(1)) { isCalVoteResult=true; address payable[] memory _inAddrs=new address payable[](capacity); uint[] memory _nums=new uint[](capacity); uint minIndex=0; uint upIndex=0; for (uint p = 1;p < candidateLength;p++) { if(gasleft()<_gasLeftLimit){ return false; } if(candidateArray[p].isValid){ if (upIndex<capacity) { //candidateIsValidMap[k] // 先初始化获选者数量池 Initialize the number of pools selected first. _inAddrs[upIndex] = candidateArray[p].candidateAddr; _nums[upIndex] = candidateArray[p].voteNumber; // 先记录获选者数量池中得票最少的记录 if (_nums[upIndex] < _nums[minIndex]) { minIndex = upIndex; } upIndex++; } else{ if (candidateArray[p].voteNumber > _nums[minIndex]) { deleteCandidate(_inAddrs[minIndex]); _inAddrs[minIndex] = candidateArray[p].candidateAddr; _nums[minIndex] = candidateArray[p].voteNumber; //重新记下最小得票者 for (uint j=0;j <capacity;j++) { if (_nums[j] < _nums[minIndex]) { minIndex = j; } } } else { deleteCandidate(candidateArray[p].candidateAddr); } } } } } isCalVoteResult=false; isRunUps=false; return true; } /** * 获取所有候选人的详细信息 */ function fetchAllCandidates() public view returns ( address payable[] memory ) { uint i=0; for (uint j = 1;j < candidateArray.length;j++) { if(candidateArray[j].isValid){ i++; } } address payable[] memory _addrs=new address payable[](i); uint p=0; for (uint k = 1;k < candidateArray.length;k++) { if(candidateArray[k].isValid){ _addrs[p]=candidateArray[k].candidateAddr; p++; } } return _addrs; } /** * 获取所有投票人的详细信息 */ function fetchAllVoters() public view returns ( address payable[] memory, uint[] memory ) { uint i=0; for (uint j = 1;j < voterArray.length;j++) { if(voterArray[j].voteNumber>0){ i++; } } address payable[] memory _addrs=new address payable[](i); uint[] memory _voteNumbers=new uint[](i); uint p=0; for (uint k = 1;k < voterArray.length;k++) { if(voterArray[k].voteNumber>0){ _addrs[p]=voterArray[k].voterAddr; _voteNumbers[p] = voterArray[k].voteNumber; p++; } } return (_addrs, _voteNumbers); } function fetchAllVoterAddrs() public view returns ( address payable[] memory ){ uint i=0; for (uint j = 1;j < voterArray.length;j++) { if(voterArray[j].voteNumber>0){ i++; } } address payable[] memory _addrs=new address payable[](i); uint p=0; for (uint k = 1;k < voterArray.length;k++) { if(voterArray[k].voteNumber>0){ _addrs[p]=voterArray[k].voterAddr; p++; } } return _addrs; } /** * 获取投票人的投票情况 */ function fetchVoteInfoForVoter( address payable voterAddr ) public view returns ( address payable[] memory, uint[] memory ) { uint voterIndex = voterIndexMap[voterAddr]; if (voterIndex == 0) { //没投过票 return (new address payable[](0), new uint[](0)); } if (voterArray[voterIndex].voteNumber == 0) { return (new address payable[](0), new uint[](0)); } uint i=0; for (uint j = 1;j < candidateArray.length;j++) { if(voterArray[voterIndex].candidateVoteNumberMap[j]>0){ i++; } } address payable[] memory _addrs=new address payable[](i); uint[] memory _nums=new uint[](i); uint p=0; for (uint k = 1;k < candidateArray.length;k++) { if(voterArray[voterIndex].candidateVoteNumberMap[k]>0){ _addrs[p]=candidateArray[k].candidateAddr; _nums[p] =voterArray[voterIndex].candidateVoteNumberMap[k]; p++; } } return (_addrs, _nums); } /** * 获取某个候选人的总得票数 Total number of votes obtained from candidates */ function fetchVoteNumForCandidate( address payable candidateAddr ) public view returns (uint) { uint candidateIndex=candidateIndexMap[candidateAddr]; require(candidateIndex != 0); require(candidateArray[candidateIndex].isValid); return candidateArray[candidateIndex].voteNumber; } /** * 获取某个投票人已投票数 Total number of votes obtained from voterAddr */ function fetchVoteNumForVoter( address payable voterAddr ) public view returns (uint) { uint voterIndex = voterIndexMap[voterAddr]; if(voterIndex == 0){//没投过票 return 0; } return voterArray[voterIndex].voteNumber; } function fetchVoteNumForVoterToCandidate( address payable voterAddr, address payable candidateAddr ) public view returns (uint) { uint voterIndex = voterIndexMap[voterAddr]; if(voterIndex == 0){//没投过票 return 0; } uint candidateIndex=candidateIndexMap[candidateAddr]; if(candidateIndex == 0){ return 0; } return voterArray[voterIndex].candidateVoteNumberMap[candidateIndex]; } /** * 获取某个候选人被投票详细情况 */ function fetchVoteInfoForCandidate( address payable candidateAddr ) public view returns ( address payable[] memory, uint[] memory ) { uint candidateIndex=candidateIndexMap[candidateAddr]; require(candidateIndex != 0); require(candidateArray[candidateIndex].isValid); if(candidateArray[candidateIndex].voteNumber==0){ return (new address payable[](0),new uint[](0)); } uint i=0; for (uint j = 1;j < voterArray.length;j++) { if(voterArray[j].candidateVoteNumberMap[candidateIndex]>0){ i++; } } address payable[] memory _addrs=new address payable[](i); uint[] memory _nums=new uint[](i); uint p=0; for (uint k = 1;k < voterArray.length;k++) { if(voterArray[k].candidateVoteNumberMap[candidateIndex]>0){ _addrs[p]=voterArray[k].voterAddr; _nums[p] =voterArray[k].candidateVoteNumberMap[candidateIndex]; p++; } } return (_addrs, _nums); } function fetchAllVoteResult() public view returns ( address payable[] memory, uint[] memory ) { uint i=0; for (uint j = 1;j < candidateArray.length;j++) { if(candidateArray[j].isValid){ i++; } } address payable[] memory _addrs=new address payable[](i); uint[] memory _nums=new uint[](i); uint p=0; for (uint k = 1;k < candidateArray.length;k++) { if(candidateArray[k].isValid){ _addrs[p]=candidateArray[k].candidateAddr; _nums[p] =candidateArray[k].voteNumber; p++; } } return (_addrs,_nums); } }
* 投票/ 刷新所有的投票结果 如果从没投过票,就添加投票人
) onlyApproved(voterAddr) public returns(bool){ require(refreshVoteForAll()); uint voterIndex=voterIndexMap[voterAddr]; function updateCandidateAddr( address payable _candidateAddr, address payable _newCandidateAddr } function vote( address payable voterAddr, address payable candidateAddr, uint num if (voterIndex == 0) { voterIndex = voterArray.push(Voter(voterAddr,0))-1; voterIndexMap[voterAddr] = voterIndex; } require(voterAddr.balance>=num.add(voterArray[voterIndex].voteNumber)); return _doVote(voterIndex,candidateAddr, num); }
12,874,604
[ 1, 167, 237, 248, 168, 103, 106, 19, 225, 166, 235, 120, 167, 249, 113, 167, 236, 227, 167, 255, 236, 168, 253, 231, 167, 237, 248, 168, 103, 106, 168, 124, 246, 167, 257, 255, 225, 166, 104, 229, 167, 257, 255, 165, 124, 241, 167, 115, 99, 167, 237, 248, 169, 128, 234, 168, 103, 106, 176, 125, 239, 166, 113, 114, 167, 120, 124, 166, 237, 259, 167, 237, 248, 168, 103, 106, 165, 123, 123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 1338, 31639, 12, 90, 20005, 3178, 13, 1071, 1135, 12, 6430, 15329, 203, 3639, 2583, 12, 9144, 19338, 1290, 1595, 10663, 203, 3639, 2254, 331, 20005, 1016, 33, 90, 20005, 1016, 863, 63, 90, 20005, 3178, 15533, 203, 565, 445, 1089, 11910, 3178, 12, 203, 3639, 1758, 8843, 429, 389, 19188, 3178, 16, 7010, 3639, 1758, 8843, 429, 389, 2704, 11910, 3178, 203, 565, 289, 203, 203, 565, 445, 12501, 12, 203, 3639, 1758, 8843, 429, 331, 20005, 3178, 16, 7010, 3639, 1758, 8843, 429, 5500, 3178, 16, 203, 3639, 2254, 818, 203, 3639, 309, 261, 90, 20005, 1016, 422, 374, 13, 288, 203, 5411, 331, 20005, 1016, 273, 331, 20005, 1076, 18, 6206, 12, 58, 20005, 12, 90, 20005, 3178, 16, 20, 3719, 17, 21, 31, 203, 5411, 331, 20005, 1016, 863, 63, 90, 20005, 3178, 65, 273, 331, 20005, 1016, 31, 203, 3639, 289, 203, 3639, 2583, 12, 90, 20005, 3178, 18, 12296, 34, 33, 2107, 18, 1289, 12, 90, 20005, 1076, 63, 90, 20005, 1016, 8009, 25911, 1854, 10019, 203, 3639, 327, 389, 2896, 19338, 12, 90, 20005, 1016, 16, 19188, 3178, 16, 818, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract RandomMachine{ address private owner; uint public randomSeed; // event for EVM logging event OwnerSet(address indexed oldOwner, address indexed newOwner); // modifier to check if caller is owner modifier isOwner() { require(msg.sender == owner, "Caller is not owner"); _; } constructor(){ owner = msg.sender; emit OwnerSet(address(0), owner); } function changeSeed(uint _randomSeed) external{ require(msg.sender == owner); randomSeed = _randomSeed; } } contract DiceGame { address private owner; uint256 nonce; RandomMachine randomMachine; // for feeding external seed outside blockchain // event for EVM logging event OwnerSet(address indexed oldOwner, address indexed newOwner); // modifier to check if caller is owner modifier isOwner() { require(msg.sender == owner, "Caller is not owner"); _; } /** * @dev Set contract deployer as owner */ constructor(address randomMachineAddress) { owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor emit OwnerSet(address(0), owner); // init external randomMachine randomMachine = RandomMachine(randomMachineAddress); nonce = 0; } /** * @dev Change owner * @param newOwner address of new owner */ function changeOwner(address newOwner) public isOwner { emit OwnerSet(owner, newOwner); owner = newOwner; } /** * @dev Return owner address * @return address of owner */ function getOwner() external view returns (address) { return owner; } function getNonce() external view isOwner returns (uint){ return nonce; } function getRandomNumber(uint max) external returns (uint){ uint randomNumber = uint( keccak256( abi.encodePacked( block.difficulty, msg.sender, nonce, randomMachine.randomSeed() ) ) ) % max + 1; nonce ++; if(nonce > 1000000){ nonce = 0; } return randomNumber; } }
* @dev Set contract deployer as owner/ init external randomMachine
constructor(address randomMachineAddress) { emit OwnerSet(address(0), owner); randomMachine = RandomMachine(randomMachineAddress); nonce = 0; }
12,781,231
[ 1, 694, 6835, 7286, 264, 487, 3410, 19, 1208, 3903, 2744, 6981, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12, 2867, 2744, 6981, 1887, 13, 288, 203, 3639, 3626, 16837, 694, 12, 2867, 12, 20, 3631, 3410, 1769, 203, 203, 3639, 2744, 6981, 273, 8072, 6981, 12, 9188, 6981, 1887, 1769, 203, 3639, 7448, 273, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {PercentageMath} from '../protocol/libraries/math/PercentageMath.sol'; import {SafeMath} from '../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IERC20WithPermit} from '../interfaces/IERC20WithPermit.sol'; import {FlashLoanReceiverBase} from '../flashloan/base/FlashLoanReceiverBase.sol'; import {IBaseUniswapAdapter} from './interfaces/IBaseUniswapAdapter.sol'; /** * @title BaseUniswapAdapter * @notice Implements the logic for performing assets swaps in Uniswap V2 * @author Aave **/ abstract contract BaseUniswapAdapter is FlashLoanReceiverBase, IBaseUniswapAdapter, Ownable { using SafeMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; // Max slippage percent allowed uint256 public constant override MAX_SLIPPAGE_PERCENT = 3000; // 30% // FLash Loan fee set in lending pool uint256 public constant override FLASHLOAN_PREMIUM_TOTAL = 9; // USD oracle asset address address public constant override USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; address public immutable override WETH_ADDRESS; IPriceOracleGetter public immutable override ORACLE; IUniswapV2Router02 public immutable override UNISWAP_ROUTER; constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public FlashLoanReceiverBase(addressesProvider) { ORACLE = IPriceOracleGetter(addressesProvider.getPriceOracle()); UNISWAP_ROUTER = uniswapRouter; WETH_ADDRESS = wethAddress; } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsOutData(reserveIn, reserveOut, amountIn); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsInData(reserveIn, reserveOut, amountOut); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Swaps an exact `amountToSwap` of an asset to another * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped * @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap * @return the amount received from the swap */ function _swapExactTokensForTokens( address assetToSwapFrom, address assetToSwapTo, uint256 amountToSwap, uint256 minAmountOut, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMinAmountOut = amountToSwap .mul(fromAssetPrice.mul(10**toAssetDecimals)) .div(toAssetPrice.mul(10**fromAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT)); require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amountToSwap, minAmountOut, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[amounts.length - 1]; } /** * @dev Receive an exact amount `amountToReceive` of `assetToSwapTo` tokens for as few `assetToSwapFrom` tokens as * possible. * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param maxAmountToSwap Max amount of `assetToSwapFrom` allowed to be swapped * @param amountToReceive Exact amount of `assetToSwapTo` to receive * @return the amount swapped */ function _swapTokensForExactTokens( address assetToSwapFrom, address assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMaxAmountToSwap = amountToReceive .mul(toAssetPrice.mul(10**fromAssetDecimals)) .div(fromAssetPrice.mul(10**toAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT)); require(maxAmountToSwap < expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), maxAmountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapTokensForExactTokens( amountToReceive, maxAmountToSwap, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[0]; } /** * @dev Get the price of the asset from the oracle denominated in eth * @param asset address * @return eth price for the asset */ function _getPrice(address asset) internal view returns (uint256) { return ORACLE.getAssetPrice(asset); } /** * @dev Get the decimals of an asset * @return number of decimals of the asset */ function _getDecimals(address asset) internal view returns (uint256) { return IERC20Detailed(asset).decimals(); } /** * @dev Get the aToken associated to the asset * @return address of the aToken */ function _getReserveData(address asset) internal view returns (DataTypes.ReserveData memory) { return LENDING_POOL.getReserveData(asset); } /** * @dev Pull the ATokens from the user * @param reserve address of the asset * @param reserveAToken address of the aToken of the reserve * @param user address * @param amount of tokens to be transferred to the contract * @param permitSignature struct containing the permit signature */ function _pullAToken( address reserve, address reserveAToken, address user, uint256 amount, PermitSignature memory permitSignature ) internal { if (_usePermit(permitSignature)) { IERC20WithPermit(reserveAToken).permit( user, address(this), permitSignature.amount, permitSignature.deadline, permitSignature.v, permitSignature.r, permitSignature.s ); } // transfer from user to adapter IERC20(reserveAToken).safeTransferFrom(user, address(this), amount); // withdraw reserve LENDING_POOL.withdraw(reserve, amount, address(this)); } /** * @dev Tells if the permit method should be called by inspecting if there is a valid signature. * If signature params are set to 0, then permit won't be called. * @param signature struct containing the permit signature * @return whether or not permit should be called */ function _usePermit(PermitSignature memory signature) internal pure returns (bool) { return !(uint256(signature.deadline) == uint256(signature.v) && uint256(signature.deadline) == 0); } /** * @dev Calculates the value denominated in USD * @param reserve Address of the reserve * @param amount Amount of the reserve * @param decimals Decimals of the reserve * @return whether or not permit should be called */ function _calcUsdValue( address reserve, uint256 amount, uint256 decimals ) internal view returns (uint256) { uint256 ethUsdPrice = _getPrice(USD_ADDRESS); uint256 reservePrice = _getPrice(reserve); return amount.mul(reservePrice).div(10**decimals).mul(ethUsdPrice).div(10**18); } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountIn Amount of reserveIn * @return Struct containing the following information: * uint256 Amount out of the reserveOut * uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsOutData( address reserveIn, address reserveOut, uint256 amountIn ) internal view returns (AmountCalc memory) { // Subtract flash loan fee uint256 finalAmountIn = amountIn.sub(amountIn.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); if (reserveIn == reserveOut) { uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( finalAmountIn, finalAmountIn.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, finalAmountIn, reserveDecimals), path ); } address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } uint256 bestAmountOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; bestAmountOut = (amountsWithWeth[2] > amountsWithoutWeth[1]) ? amountsWithWeth[2] : amountsWithoutWeth[1]; } catch { amountsWithoutWeth = new uint256[](2); bestAmountOut = amountsWithWeth[2]; } uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 outPerInPrice = finalAmountIn.mul(10**18).mul(10**reserveOutDecimals).div( bestAmountOut.mul(10**reserveInDecimals) ); return AmountCalc( bestAmountOut, outPerInPrice, _calcUsdValue(reserveIn, amountIn, reserveInDecimals), _calcUsdValue(reserveOut, bestAmountOut, reserveOutDecimals), (bestAmountOut == 0) ? new address[](2) : (bestAmountOut == amountsWithoutWeth[1]) ? simplePath : pathWithWeth ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return Struct containing the following information: * uint256 Amount in of the reserveIn * uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsInData( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (AmountCalc memory) { if (reserveIn == reserveOut) { // Add flash loan fee uint256 amountIn = amountOut.add(amountOut.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( amountIn, amountOut.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, amountOut, reserveDecimals), path ); } (uint256[] memory amounts, address[] memory path) = _getAmountsInAndPath(reserveIn, reserveOut, amountOut); // Add flash loan fee uint256 finalAmountIn = amounts[0].add(amounts[0].mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 inPerOutPrice = amountOut.mul(10**18).mul(10**reserveInDecimals).div( finalAmountIn.mul(10**reserveOutDecimals) ); return AmountCalc( finalAmountIn, inPerOutPrice, _calcUsdValue(reserveIn, finalAmountIn, reserveInDecimals), _calcUsdValue(reserveOut, amountOut, reserveOutDecimals), path ); } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsInAndPath( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (uint256[] memory, address[] memory) { address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsIn(amountOut, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } try UNISWAP_ROUTER.getAmountsIn(amountOut, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; return (amountsWithWeth[0] < amountsWithoutWeth[0] && amountsWithWeth[0] != 0) ? (amountsWithWeth, pathWithWeth) : (amountsWithoutWeth, simplePath); } catch { return (amountsWithWeth, pathWithWeth); } } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsIn( address reserveIn, address reserveOut, uint256 amountOut, bool useEthPath ) internal view returns (uint256[] memory) { address[] memory path; if (useEthPath) { path = new address[](3); path[0] = reserveIn; path[1] = WETH_ADDRESS; path[2] = reserveOut; } else { path = new address[](2); path[0] = reserveIn; path[1] = reserveOut; } return UNISWAP_ROUTER.getAmountsIn(amountOut, path); } /** * @dev Emergency rescue for token stucked on this contract, as failsafe mechanism * - Funds should never remain in this contract more time than during transactions * - Only callable by the owner **/ function rescueTokens(IERC20 token) external onlyOwner { token.transfer(owner(), token.balanceOf(address(this))); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @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: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; import {SafeMath} from './SafeMath.sol'; import {Address} from './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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './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: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IUniswapV2Router02 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IPriceOracleGetter interface * @notice Interface for the Aave price oracle. **/ interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IERC20WithPermit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IFlashLoanReceiver} from '../interfaces/IFlashLoanReceiver.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for IERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public immutable override ADDRESSES_PROVIDER; ILendingPool public immutable override LENDING_POOL; constructor(ILendingPoolAddressesProvider provider) public { ADDRESSES_PROVIDER = provider; LENDING_POOL = ILendingPool(provider.getLendingPool()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; interface IBaseUniswapAdapter { event Swapped(address fromAsset, address toAsset, uint256 fromAmount, uint256 receivedAmount); struct PermitSignature { uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct AmountCalc { uint256 calculatedAmount; uint256 relativePrice; uint256 amountInUsd; uint256 amountOutUsd; address[] path; } function WETH_ADDRESS() external returns (address); function MAX_SLIPPAGE_PERCENT() external returns (uint256); function FLASHLOAN_PREMIUM_TOTAL() external returns (uint256); function USD_ADDRESS() external returns (address); function ORACLE() external returns (IPriceOracleGetter); function UNISWAP_ROUTER() external returns (IUniswapV2Router02); /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; /** * @title IFlashLoanReceiver interface * @notice Interface for the Aave fee IFlashLoanReceiver. * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function LENDING_POOL() external view returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title UniswapRepayAdapter * @notice Uniswap V2 Adapter to perform a repay of a debt with collateral. * @author Aave **/ contract UniswapRepayAdapter is BaseUniswapAdapter { struct RepayParams { address collateralAsset; uint256 collateralAmount; uint256 rateMode; PermitSignature permitSignature; bool useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Uses the received funds from the flash loan to repay a debt on the protocol on behalf of the user. Then pulls * the collateral from the user and swaps it to the debt asset to repay the flash loan. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset, swap it * and repay the flash loan. * Supports only one asset on the flash loan. * @param assets Address of debt asset * @param amounts Amount of the debt to be repaid * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); RepayParams memory decodedParams = _decodeParams(params); _swapAndRepay( decodedParams.collateralAsset, assets[0], amounts[0], decodedParams.collateralAmount, decodedParams.rateMode, initiator, premiums[0], decodedParams.permitSignature, decodedParams.useEthPath ); return true; } /** * @dev Swaps the user collateral for the debt asset and then repay the debt on the protocol on behalf of the user * without using flash loans. This method can be used when the temporary transfer of the collateral asset to this * contract does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset * @param collateralAsset Address of asset to be swapped * @param debtAsset Address of debt asset * @param collateralAmount Amount of the collateral to be swapped * @param debtRepayAmount Amount of the debt to be repaid * @param debtRateMode Rate mode of the debt to be repaid * @param permitSignature struct containing the permit signature * @param useEthPath struct containing the permit signature */ function swapAndRepay( address collateralAsset, address debtAsset, uint256 collateralAmount, uint256 debtRepayAmount, uint256 debtRateMode, PermitSignature calldata permitSignature, bool useEthPath ) external { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); DataTypes.ReserveData memory debtReserveData = _getReserveData(debtAsset); address debtToken = DataTypes.InterestRateMode(debtRateMode) == DataTypes.InterestRateMode.STABLE ? debtReserveData.stableDebtTokenAddress : debtReserveData.variableDebtTokenAddress; uint256 currentDebt = IERC20(debtToken).balanceOf(msg.sender); uint256 amountToRepay = debtRepayAmount <= currentDebt ? debtRepayAmount : currentDebt; if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (amountToRepay < debtRepayAmount) { maxCollateralToSwap = maxCollateralToSwap.mul(amountToRepay).div(debtRepayAmount); } // Get exact collateral needed for the swap to avoid leftovers uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, amountToRepay, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amounts[0], permitSignature ); // Swap collateral for debt asset _swapTokensForExactTokens(collateralAsset, debtAsset, amounts[0], amountToRepay, useEthPath); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amountToRepay, permitSignature ); } // Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amountToRepay); LENDING_POOL.repay(debtAsset, amountToRepay, debtRateMode, msg.sender); } /** * @dev Perform the repay of the debt, pulls the initiator collateral and swaps to repay the flash loan * * @param collateralAsset Address of token to be swapped * @param debtAsset Address of debt token to be received from the swap * @param amount Amount of the debt to be repaid * @param collateralAmount Amount of the reserve to be swapped * @param rateMode Rate mode of the debt to be repaid * @param initiator Address of the user * @param premium Fee of the flash loan * @param permitSignature struct containing the permit signature */ function _swapAndRepay( address collateralAsset, address debtAsset, uint256 amount, uint256 collateralAmount, uint256 rateMode, address initiator, uint256 premium, PermitSignature memory permitSignature, bool useEthPath ) internal { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); // Repay debt. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount); uint256 repaidAmount = IERC20(debtAsset).balanceOf(address(this)); LENDING_POOL.repay(debtAsset, amount, rateMode, initiator); repaidAmount = repaidAmount.sub(IERC20(debtAsset).balanceOf(address(this))); if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (repaidAmount < amount) { maxCollateralToSwap = maxCollateralToSwap.mul(repaidAmount).div(amount); } uint256 neededForFlashLoanDebt = repaidAmount.add(premium); uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, neededForFlashLoanDebt, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, amounts[0], permitSignature ); // Swap collateral asset to the debt asset _swapTokensForExactTokens( collateralAsset, debtAsset, amounts[0], neededForFlashLoanDebt, useEthPath ); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, repaidAmount.add(premium), permitSignature ); } // Repay flashloan. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount.add(premium)); } /** * @dev Decodes debt information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature * bool useEthPath use WETH path route * @return RepayParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (RepayParams memory) { ( address collateralAsset, uint256 collateralAmount, uint256 rateMode, uint256 permitAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bool useEthPath ) = abi.decode( params, (address, uint256, uint256, uint256, uint256, uint8, bytes32, bytes32, bool) ); return RepayParams( collateralAsset, collateralAmount, rateMode, PermitSignature(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts//SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts//IERC20.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {ILendingPoolCollateralManager} from '../../interfaces/ILendingPoolCollateralManager.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPoolCollateralManager contract * @author Aave * @dev Implements actions involving management of collateral in the protocol, the main one being the liquidations * IMPORTANT This contract will run always via DELEGATECALL, through the LendingPool, so the chain of inheritance * is the same as the LendingPool, to have compatible storage layouts **/ contract LendingPoolCollateralManager is ILendingPoolCollateralManager, VersionedInitializable, LendingPoolStorage { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationCallLocalVars { uint256 userCollateralBalance; uint256 userStableDebt; uint256 userVariableDebt; uint256 maxLiquidatableDebt; uint256 actualDebtToLiquidate; uint256 liquidationRatio; uint256 maxAmountCollateralToLiquidate; uint256 userStableRate; uint256 maxCollateralToLiquidate; uint256 debtAmountNeeded; uint256 healthFactor; uint256 liquidatorPreviousATokenBalance; IAToken collateralAtoken; bool isCollateralEnabled; DataTypes.InterestRateMode borrowRateMode; uint256 errorCode; string errorMsg; } /** * @dev As thIS contract extends the VersionedInitializable contract to match the state * of the LendingPool contract, the getRevision() function is needed, but the value is not * important, as the initialize() function will never be called here */ function getRevision() internal pure override returns (uint256) { return 0; } /** * @dev Function to liquidate a position if its Health Factor drops below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override returns (uint256, string memory) { DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, userConfig, _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); (vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve); (vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.userStableDebt, vars.userVariableDebt ); if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) { return (vars.errorCode, vars.errorMsg); } vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress); vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user); vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul( LIQUIDATION_CLOSE_FACTOR_PERCENT ); vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt ? vars.maxLiquidatableDebt : debtToCover; ( vars.maxCollateralToLiquidate, vars.debtAmountNeeded ) = _calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.actualDebtToLiquidate, vars.userCollateralBalance ); // If debtAmountNeeded < actualDebtToLiquidate, there isn't enough // collateral to cover the actual amount that is being liquidated, hence we liquidate // a smaller amount if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) { vars.actualDebtToLiquidate = vars.debtAmountNeeded; } // If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the // collateral reserve if (!receiveAToken) { uint256 currentAvailableCollateral = IERC20(collateralAsset).balanceOf(address(vars.collateralAtoken)); if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY), Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } debtReserve.updateState(); if (vars.userVariableDebt >= vars.actualDebtToLiquidate) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate, debtReserve.variableBorrowIndex ); } else { // If the user doesn't have variable debt, no need to try to burn variable debt tokens if (vars.userVariableDebt > 0) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.userVariableDebt, debtReserve.variableBorrowIndex ); } IStableDebtToken(debtReserve.stableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate.sub(vars.userVariableDebt) ); } debtReserve.updateInterestRates( debtAsset, debtReserve.aTokenAddress, vars.actualDebtToLiquidate, 0 ); if (receiveAToken) { vars.liquidatorPreviousATokenBalance = IERC20(vars.collateralAtoken).balanceOf(msg.sender); vars.collateralAtoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate); if (vars.liquidatorPreviousATokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } } else { collateralReserve.updateState(); collateralReserve.updateInterestRates( collateralAsset, address(vars.collateralAtoken), 0, vars.maxCollateralToLiquidate ); // Burn the equivalent amount of aToken, sending the underlying to the liquidator vars.collateralAtoken.burn( user, msg.sender, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex ); } // If the collateral being liquidated is equal to the user balance, // we set the currency as not being used as collateral anymore if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } // Transfers the debt asset being repaid to the aToken, where the liquidity is kept IERC20(debtAsset).safeTransferFrom( msg.sender, debtReserve.aTokenAddress, vars.actualDebtToLiquidate ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.actualDebtToLiquidate, vars.maxCollateralToLiquidate, msg.sender, receiveAToken ); return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } struct AvailableCollateralToLiquidateLocalVars { uint256 userCompoundedBorrowBalance; uint256 liquidationBonus; uint256 collateralPrice; uint256 debtAssetPrice; uint256 maxAmountCollateralToLiquidate; uint256 debtAssetDecimals; uint256 collateralDecimals; } /** * @dev Calculates how much of a specific collateral can be liquidated, given * a certain amount of debt asset. * - This function needs to be called after all the checks to validate the liquidation have been performed, * otherwise it might fail. * @param collateralReserve The data of the collateral reserve * @param debtReserve The data of the debt reserve * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param userCollateralBalance The collateral balance for the specific `collateralAsset` of the user being liquidated * @return collateralAmount: The maximum amount that is possible to liquidate given all the liquidation constraints * (user balance, close factor) * debtAmountNeeded: The amount to repay with the liquidation **/ function _calculateAvailableCollateralToLiquidate( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage debtReserve, address collateralAsset, address debtAsset, uint256 debtToCover, uint256 userCollateralBalance ) internal view returns (uint256, uint256) { uint256 collateralAmount = 0; uint256 debtAmountNeeded = 0; IPriceOracleGetter oracle = IPriceOracleGetter(_addressesProvider.getPriceOracle()); AvailableCollateralToLiquidateLocalVars memory vars; vars.collateralPrice = oracle.getAssetPrice(collateralAsset); vars.debtAssetPrice = oracle.getAssetPrice(debtAsset); (, , vars.liquidationBonus, vars.collateralDecimals, ) = collateralReserve .configuration .getParams(); vars.debtAssetDecimals = debtReserve.configuration.getDecimals(); // This is the maximum possible amount of the selected collateral that can be liquidated, given the // max amount of liquidatable debt vars.maxAmountCollateralToLiquidate = vars .debtAssetPrice .mul(debtToCover) .mul(10**vars.collateralDecimals) .percentMul(vars.liquidationBonus) .div(vars.collateralPrice.mul(10**vars.debtAssetDecimals)); if (vars.maxAmountCollateralToLiquidate > userCollateralBalance) { collateralAmount = userCollateralBalance; debtAmountNeeded = vars .collateralPrice .mul(collateralAmount) .mul(10**vars.debtAssetDecimals) .div(vars.debtAssetPrice.mul(10**vars.collateralDecimals)) .percentDiv(vars.liquidationBonus); } else { collateralAmount = vars.maxAmountCollateralToLiquidate; debtAmountNeeded = debtToCover; } return (collateralAmount, debtAmountNeeded); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableAToken} from './IInitializableAToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IStableDebtToken * @notice Defines the interface for the stable debt token * @dev It does not inherit from IERC20 to save in code size * @author Aave **/ interface IStableDebtToken is IInitializableDebtToken { /** * @dev Emitted when new stable debt is minted * @param user The address of the user who triggered the minting * @param onBehalfOf The recipient of stable debt tokens * @param amount The amount minted * @param currentBalance The current balance of the user * @param balanceIncrease The increase in balance since the last action of the user * @param newRate The rate of the debt after the minting * @param avgStableRate The new average stable rate after the minting * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Mint( address indexed user, address indexed onBehalfOf, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 newRate, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Emitted when new stable debt is burned * @param user The address of the user * @param amount The amount being burned * @param currentBalance The current balance of the user * @param balanceIncrease The the increase in balance since the last action of the user * @param avgStableRate The new average stable rate after the burning * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Burn( address indexed user, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Mints debt token to the `onBehalfOf` address. * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external returns (bool); /** * @dev Burns debt of `user` * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external; /** * @dev Returns the average rate of all the stable rate loans. * @return The average stable rate **/ function getAverageStableRate() external view returns (uint256); /** * @dev Returns the stable rate of the user debt * @return The stable rate of the user **/ function getUserStableRate(address user) external view returns (uint256); /** * @dev Returns the timestamp of the last update of the user * @return The timestamp **/ function getUserLastUpdated(address user) external view returns (uint40); /** * @dev Returns the principal, the total supply and the average stable rate **/ function getSupplyData() external view returns ( uint256, uint256, uint256, uint40 ); /** * @dev Returns the timestamp of the last update of the total supply * @return The timestamp **/ function getTotalSupplyLastUpdated() external view returns (uint40); /** * @dev Returns the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() external view returns (uint256, uint256); /** * @dev Returns the principal debt balance of the user * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view returns (uint256); /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingPoolCollateralManager * @author Aave * @notice Defines the actions involving management of collateral in the protocol. **/ interface ILendingPoolCollateralManager { /** * @dev Emitted when a borrower is liquidated * @param collateral The address of the collateral being liquidated * @param principal The address of the reserve * @param user The address of the user being liquidated * @param debtToCover The total amount liquidated * @param liquidatedCollateralAmount The amount of collateral being liquidated * @param liquidator The address of the liquidator * @param receiveAToken true if the liquidator wants to receive aTokens, false otherwise **/ event LiquidationCall( address indexed collateral, address indexed principal, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when a reserve is disabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted when a reserve is enabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Users can invoke this function to liquidate an undercollateralized position. * @param collateral The address of the collateral to liquidated * @param principal The address of the principal reserve * @param user The address of the borrower * @param debtToCover The amount of principal that the liquidator wants to repay * @param receiveAToken true if the liquidators wants to receive the aTokens, false if * he wants to receive the underlying asset directly **/ function liquidationCall( address collateral, address principal, address user, uint256 debtToCover, bool receiveAToken ) external returns (uint256, string memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title VersionedInitializable * * @dev Helper contract to implement initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require( initializing || isConstructor() || revision > lastInitializedRevision, 'Contract instance has already been initialized' ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /** * @dev returns the revision number of the contract * Needs to be defined in the inherited class as a constant. **/ function getRevision() internal pure virtual returns (uint256); /** * @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. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address()) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title GenericLogic library * @author Aave * @title Implements protocol-level logic to calculate and validate the state of a user */ library GenericLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether; struct balanceDecreaseAllowedLocalVars { uint256 decimals; uint256 liquidationThreshold; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLiquidationThreshold; uint256 amountToDecreaseInETH; uint256 collateralBalanceAfterDecrease; uint256 liquidationThresholdAfterDecrease; uint256 healthFactorAfterDecrease; bool reserveUsageAsCollateralEnabled; } /** * @dev Checks if a specific balance decrease is allowed * (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD) * @param asset The address of the underlying asset of the reserve * @param user The address of the user * @param amount The amount to decrease * @param reservesData The data of all the reserves * @param userConfig The user configuration * @param reserves The list of all the active reserves * @param oracle The address of the oracle contract * @return true if the decrease of the balance is allowed **/ function balanceDecreaseAllowed( address asset, address user, uint256 amount, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap calldata userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view returns (bool) { if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) { return true; } balanceDecreaseAllowedLocalVars memory vars; (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset] .configuration .getParams(); if (vars.liquidationThreshold == 0) { return true; } ( vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle); if (vars.totalDebtInETH == 0) { return true; } vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div( 10**vars.decimals ); vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalanceAfterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .totalCollateralInETH .mul(vars.avgLiquidationThreshold) .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold)) .div(vars.collateralBalanceAfterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances( vars.collateralBalanceAfterDecrease, vars.totalDebtInETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } struct CalculateUserAccountDataVars { uint256 reserveUnitPrice; uint256 tokenUnit; uint256 compoundedLiquidityBalance; uint256 compoundedBorrowBalance; uint256 decimals; uint256 ltv; uint256 liquidationThreshold; uint256 i; uint256 healthFactor; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLtv; uint256 avgLiquidationThreshold; uint256 reservesLength; bool healthFactorBelowThreshold; address currentReserveAddress; bool usageAsCollateralEnabled; bool userUsesReserveAsCollateral; } /** * @dev Calculates the user data across the reserves. * this includes the total liquidity/collateral/borrow balances in ETH, * the average Loan To Value, the average Liquidation Ratio, and the Health factor. * @param user The address of the user * @param reservesData Data of all the reserves * @param userConfig The configuration of the user * @param reserves The list of the available reserves * @param oracle The price oracle address * @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF **/ function calculateUserAccountData( address user, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap memory userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { CalculateUserAccountDataVars memory vars; if (userConfig.isEmpty()) { return (0, 0, 0, 0, uint256(-1)); } for (vars.i = 0; vars.i < reservesCount; vars.i++) { if (!userConfig.isUsingAsCollateralOrBorrowing(vars.i)) { continue; } vars.currentReserveAddress = reserves[vars.i]; DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress]; (vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve .configuration .getParams(); vars.tokenUnit = 10**vars.decimals; vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress); if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) { vars.compoundedLiquidityBalance = IERC20(currentReserve.aTokenAddress).balanceOf(user); uint256 liquidityBalanceETH = vars.reserveUnitPrice.mul(vars.compoundedLiquidityBalance).div(vars.tokenUnit); vars.totalCollateralInETH = vars.totalCollateralInETH.add(liquidityBalanceETH); vars.avgLtv = vars.avgLtv.add(liquidityBalanceETH.mul(vars.ltv)); vars.avgLiquidationThreshold = vars.avgLiquidationThreshold.add( liquidityBalanceETH.mul(vars.liquidationThreshold) ); } if (userConfig.isBorrowing(vars.i)) { vars.compoundedBorrowBalance = IERC20(currentReserve.stableDebtTokenAddress).balanceOf( user ); vars.compoundedBorrowBalance = vars.compoundedBorrowBalance.add( IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user) ); vars.totalDebtInETH = vars.totalDebtInETH.add( vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit) ); } } vars.avgLtv = vars.totalCollateralInETH > 0 ? vars.avgLtv.div(vars.totalCollateralInETH) : 0; vars.avgLiquidationThreshold = vars.totalCollateralInETH > 0 ? vars.avgLiquidationThreshold.div(vars.totalCollateralInETH) : 0; vars.healthFactor = calculateHealthFactorFromBalances( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLiquidationThreshold ); return ( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLtv, vars.avgLiquidationThreshold, vars.healthFactor ); } /** * @dev Calculates the health factor from the corresponding balances * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total debt in ETH * @param liquidationThreshold The avg liquidation threshold * @return The health factor calculated from the balances provided **/ function calculateHealthFactorFromBalances( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 liquidationThreshold ) internal pure returns (uint256) { if (totalDebtInETH == 0) return uint256(-1); return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH); } /** * @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the * average Loan To Value * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total borrow balance * @param ltv The average loan to value * @return the amount available to borrow in ETH for the user **/ function calculateAvailableBorrowsETH( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 ltv ) internal pure returns (uint256) { uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv); if (availableBorrowsETH < totalDebtInETH) { return 0; } availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH); return availableBorrowsETH; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title Helpers library * @author Aave */ library Helpers { /** * @dev Fetches the user current stable and variable debt balances * @param user The user address * @param reserve The reserve data object * @return The stable and variable debt balance **/ function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {Helpers} from '../helpers/Helpers.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000; uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95% /** * @dev Validates a deposit action * @param reserve The reserve object on which the user is depositing * @param amount The amount to be deposited */ function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view { (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags(); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); } /** * @dev Validates a withdraw action * @param reserveAddress The address of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user * @param reservesData The reserves state * @param userConfig The user configuration * @param reserves The addresses of the reserves * @param reservesCount The number of reserves * @param oracle The price oracle */ function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { require(amount != 0, Errors.VL_INVALID_AMOUNT); require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE); (bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require( GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, amount, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_TRANSFER_NOT_ALLOWED ); } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 currentLiquidationThreshold; uint256 amountOfCollateralNeededETH; uint256 userCollateralBalanceETH; uint256 userBorrowBalanceETH; uint256 availableLiquidity; uint256 healthFactor; bool isActive; bool isFrozen; bool borrowingEnabled; bool stableRateBorrowingEnabled; } /** * @dev Validates a borrow action * @param asset The address of the asset to borrow * @param reserve The reserve state from which the user is borrowing * @param userAddress The address of the user * @param amount The amount to be borrowed * @param amountInETH The amount to be borrowed, in ETH * @param interestRateMode The interest rate mode at which the user is borrowing * @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateBorrow( address asset, DataTypes.ReserveData storage reserve, address userAddress, uint256 amount, uint256 amountInETH, uint256 interestRateMode, uint256 maxStableLoanPercent, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { ValidateBorrowLocalVars memory vars; (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve .configuration .getFlags(); require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED); //validate interest rate mode require( uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode || uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode, Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED ); ( vars.userCollateralBalanceETH, vars.userBorrowBalanceETH, vars.currentLtv, vars.currentLiquidationThreshold, vars.healthFactor ) = GenericLogic.calculateUserAccountData( userAddress, reservesData, userConfig, reserves, reservesCount, oracle ); require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0); require( vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv( vars.currentLtv ); //LTV is calculated in percentage require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity **/ if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent); require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } } /** * @dev Validates a repay action * @param reserve The reserve state from which the user is repaying * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveData storage reserve, uint256 amountSent, DataTypes.InterestRateMode rateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) external view { bool isActive = reserve.configuration.getActive(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(amountSent > 0, Errors.VL_INVALID_AMOUNT); require( (stableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE) || (variableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE), Errors.VL_NO_DEBT_OF_SELECTED_TYPE ); require( amountSent != uint256(-1) || msg.sender == onBehalfOf, Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); } /** * @dev Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the borrow */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) external view { (bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); if (currentRateMode == DataTypes.InterestRateMode.STABLE) { require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE); } else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) { require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE); /** * user wants to swap to stable, before swapping we need to ensure that * 1. stable borrow rate is enabled on the reserve * 2. user is not trying to abuse the reserve by depositing * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || stableDebt.add(variableDebt) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); } else { revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED); } } /** * @dev Validates a stable borrow rate rebalance action * @param reserve The reserve state on which the user is getting rebalanced * @param reserveAddress The address of the reserve * @param stableDebtToken The stable debt token instance * @param variableDebtToken The variable debt token instance * @param aTokenAddress The address of the aToken contract */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, address reserveAddress, IERC20 stableDebtToken, IERC20 variableDebtToken, address aTokenAddress ) external view { (bool isActive, , , ) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); //if the usage ratio is below 95%, no rebalances are needed uint256 totalDebt = stableDebtToken.totalSupply().add(variableDebtToken.totalSupply()).wadToRay(); uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress).wadToRay(); uint256 usageRatio = totalDebt == 0 ? 0 : totalDebt.rayDiv(availableLiquidity.add(totalDebt)); //if the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage, //then we allow rebalancing of the stable rate positions. uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 maxVariableBorrowRate = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).getMaxVariableBorrowRate(); require( usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD && currentLiquidityRate <= maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD), Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET ); } /** * @dev Validates the action of setting an asset as collateral * @param reserve The state of the reserve that the user is enabling or disabling as collateral * @param reserveAddress The address of the reserve * @param reservesData The data of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateSetUseReserveAsCollateral( DataTypes.ReserveData storage reserve, address reserveAddress, bool useAsCollateral, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender); require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0); require( useAsCollateral || GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, underlyingBalance, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_DEPOSIT_ALREADY_IN_USE ); } /** * @dev Validates a flashloan action * @param assets The assets being flashborrowed * @param amounts The amounts for each asset being borrowed **/ function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure { require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS); } /** * @dev Validates the liquidation action * @param collateralReserve The reserve data of the collateral * @param principalReserve The reserve data of the principal * @param userConfig The user configuration * @param userHealthFactor The user's health factor * @param userStableDebt Total stable debt balance of the user * @param userVariableDebt Total variable debt balance of the user **/ function validateLiquidationCall( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage principalReserve, DataTypes.UserConfigurationMap storage userConfig, uint256 userHealthFactor, uint256 userStableDebt, uint256 userVariableDebt ) internal view returns (uint256, string memory) { if ( !collateralReserve.configuration.getActive() || !principalReserve.configuration.getActive() ) { return ( uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE), Errors.VL_NO_ACTIVE_RESERVE ); } if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) { return ( uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); } bool isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() > 0 && userConfig.isUsingAsCollateral(collateralReserve.id); //if collateral isn't enabled as collateral by user, it cannot be liquidated if (!isCollateralEnabled) { return ( uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED ); } if (userStableDebt == 0 && userVariableDebt == 0) { return ( uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED), Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER ); } return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } /** * @dev Validates an aToken transfer * @param from The user from which the aTokens are being transferred * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateTransfer( address from, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view { (, , , , uint256 healthFactor) = GenericLogic.calculateUserAccountData( from, reservesData, userConfig, reserves, reservesCount, oracle ); require( healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_TRANSFER_NOT_ALLOWED ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; contract LendingPoolStorage { using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; ILendingPoolAddressesProvider internal _addressesProvider; mapping(address => DataTypes.ReserveData) internal _reserves; mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig; // the list of the available reserves, structured as a mapping for gas savings reasons mapping(uint256 => address) internal _reservesList; uint256 internal _reservesCount; bool internal _paused; uint256 internal _maxStableRateBorrowSizePercent; uint256 internal _flashLoanPremiumTotal; uint256 internal _maxNumberOfReserves; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableAToken * @notice Interface for the initialize function on AToken * @author Aave **/ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals the decimals of the underlying * @param aTokenName the name of the aToken * @param aTokenSymbol the symbol of the aToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAaveIncentivesController { function handleAction( address user, uint256 userBalance, uint256 totalSupply ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableDebtToken * @notice Interface for the initialize function common between debt tokens * @author Aave **/ interface IInitializableDebtToken { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param incentivesController The address of the incentives controller for this aToken * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {MathUtils} from '../math/MathUtils.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements the logic to update the reserves state */ library ReserveLogic { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; /** * @dev Emitted when the state of a reserve is updated * @param asset The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed asset, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; /** * @dev Returns the ongoing normalized income for the reserve * A value of 1e27 means there is no income. As time passes, the income is accrued * A value of 2*1e27 means for each unit of asset one unit of income has been accrued * @param reserve The reserve object * @return the normalized income. expressed in ray **/ function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.liquidityIndex; } uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul( reserve.liquidityIndex ); return cumulated; } /** * @dev Returns the ongoing normalized variable debt for the reserve * A value of 1e27 means there is no debt. As time passes, the income is accrued * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated * @param reserve The reserve object * @return The normalized variable debt. expressed in ray **/ function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.variableBorrowIndex; } uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul( reserve.variableBorrowIndex ); return cumulated; } /** * @dev Updates the liquidity cumulative index and the variable borrow index. * @param reserve the reserve object **/ function updateState(DataTypes.ReserveData storage reserve) internal { uint256 scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply(); uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; uint256 previousLiquidityIndex = reserve.liquidityIndex; uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp; (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes( reserve, scaledVariableDebt, previousLiquidityIndex, previousVariableBorrowIndex, lastUpdatedTimestamp ); _mintToTreasury( reserve, scaledVariableDebt, previousVariableBorrowIndex, newLiquidityIndex, newVariableBorrowIndex, lastUpdatedTimestamp ); } /** * @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate * the flashloan fee to the reserve, and spread it between all the depositors * @param reserve The reserve object * @param totalLiquidity The total liquidity available in the reserve * @param amount The amount to accomulate **/ function cumulateToLiquidityIndex( DataTypes.ReserveData storage reserve, uint256 totalLiquidity, uint256 amount ) internal { uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay()); uint256 result = amountToLiquidityRatio.add(WadRayMath.ray()); result = result.rayMul(reserve.liquidityIndex); require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(result); } /** * @dev Initializes a reserve * @param reserve The reserve object * @param aTokenAddress The address of the overlying atoken contract * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function init( DataTypes.ReserveData storage reserve, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress ) external { require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED); reserve.liquidityIndex = uint128(WadRayMath.ray()); reserve.variableBorrowIndex = uint128(WadRayMath.ray()); reserve.aTokenAddress = aTokenAddress; reserve.stableDebtTokenAddress = stableDebtTokenAddress; reserve.variableDebtTokenAddress = variableDebtTokenAddress; reserve.interestRateStrategyAddress = interestRateStrategyAddress; } struct UpdateInterestRatesLocalVars { address stableDebtTokenAddress; uint256 availableLiquidity; uint256 totalStableDebt; uint256 newLiquidityRate; uint256 newStableRate; uint256 newVariableRate; uint256 avgStableRate; uint256 totalVariableDebt; } /** * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate * @param reserve The address of the reserve to be updated * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow) **/ function updateInterestRates( DataTypes.ReserveData storage reserve, address reserveAddress, address aTokenAddress, uint256 liquidityAdded, uint256 liquidityTaken ) internal { UpdateInterestRatesLocalVars memory vars; vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress; (vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress) .getTotalSupplyAndAvgRate(); //calculates the total variable debt locally using the scaled total supply instead //of totalSupply(), as it's noticeably cheaper. Also, the index has been //updated by the previous updateState() call vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress) .scaledTotalSupply() .rayMul(reserve.variableBorrowIndex); ( vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( reserveAddress, aTokenAddress, liquidityAdded, liquidityTaken, vars.totalStableDebt, vars.totalVariableDebt, vars.avgStableRate, reserve.configuration.getReserveFactor() ); require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW); require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW); require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW); reserve.currentLiquidityRate = uint128(vars.newLiquidityRate); reserve.currentStableBorrowRate = uint128(vars.newStableRate); reserve.currentVariableBorrowRate = uint128(vars.newVariableRate); emit ReserveDataUpdated( reserveAddress, vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate, reserve.liquidityIndex, reserve.variableBorrowIndex ); } struct MintToTreasuryLocalVars { uint256 currentStableDebt; uint256 principalStableDebt; uint256 previousStableDebt; uint256 currentVariableDebt; uint256 previousVariableDebt; uint256 avgStableRate; uint256 cumulatedStableInterest; uint256 totalDebtAccrued; uint256 amountToMint; uint256 reserveFactor; uint40 stableSupplyUpdatedTimestamp; } /** * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the * specific asset. * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The current scaled total variable debt * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest * @param newLiquidityIndex The new liquidity index * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest **/ function _mintToTreasury( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 previousVariableBorrowIndex, uint256 newLiquidityIndex, uint256 newVariableBorrowIndex, uint40 timestamp ) internal { MintToTreasuryLocalVars memory vars; vars.reserveFactor = reserve.configuration.getReserveFactor(); if (vars.reserveFactor == 0) { return; } //fetching the principal, total stable debt and the avg stable rate ( vars.principalStableDebt, vars.currentStableDebt, vars.avgStableRate, vars.stableSupplyUpdatedTimestamp ) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData(); //calculate the last principal variable debt vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex); //calculate the new total supply after accumulation of the index vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex); //calculate the stable debt until the last timestamp update vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest( vars.avgStableRate, vars.stableSupplyUpdatedTimestamp, timestamp ); vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest); //debt accrued is the sum of the current debt minus the sum of the debt at the last update vars.totalDebtAccrued = vars .currentVariableDebt .add(vars.currentStableDebt) .sub(vars.previousVariableDebt) .sub(vars.previousStableDebt); vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor); if (vars.amountToMint != 0) { IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } } /** * @dev Updates the reserve indexes and the timestamp of the update * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The scaled variable debt * @param liquidityIndex The last stored liquidity index * @param variableBorrowIndex The last stored variable borrow index **/ function _updateIndexes( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 timestamp ) internal returns (uint256, uint256) { uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 newLiquidityIndex = liquidityIndex; uint256 newVariableBorrowIndex = variableBorrowIndex; //only cumulating if there is any income being produced if (currentLiquidityRate > 0) { uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(newLiquidityIndex); //as the liquidity rate might come only from stable rate loans, we need to ensure //that there is actual variable debt before accumulating if (scaledVariableDebt != 0) { uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp); newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); require( newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW ); reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); return (newLiquidityIndex, newVariableBorrowIndex); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the reserve configuration */ library ReserveConfiguration { uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 constant IS_FROZEN_START_BIT_POSITION = 57; uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58; uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59; uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 constant MAX_VALID_LTV = 65535; uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 constant MAX_VALID_DECIMALS = 255; uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; /** * @dev Sets the Loan to Value of the reserve * @param self The reserve configuration * @param ltv the new ltv **/ function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } /** * @dev Gets the Loan to Value of the reserve * @param self The reserve configuration * @return The loan to value **/ function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } /** * @dev Sets the liquidation threshold of the reserve * @param self The reserve configuration * @param threshold The new liquidation threshold **/ function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } /** * @dev Gets the liquidation threshold of the reserve * @param self The reserve configuration * @return The liquidation threshold **/ function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } /** * @dev Sets the liquidation bonus of the reserve * @param self The reserve configuration * @param bonus The new liquidation bonus **/ function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } /** * @dev Gets the liquidation bonus of the reserve * @param self The reserve configuration * @return The liquidation bonus **/ function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } /** * @dev Sets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @param decimals The decimals **/ function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } /** * @dev Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset **/ function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } /** * @dev Sets the active state of the reserve * @param self The reserve configuration * @param active The active state **/ function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION); } /** * @dev Gets the active state of the reserve * @param self The reserve configuration * @return The active state **/ function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } /** * @dev Sets the frozen state of the reserve * @param self The reserve configuration * @param frozen The frozen state **/ function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); } /** * @dev Gets the frozen state of the reserve * @param self The reserve configuration * @return The frozen state **/ function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } /** * @dev Enables or disables borrowing on the reserve * @param self The reserve configuration * @param enabled True if the borrowing needs to be enabled, false otherwise **/ function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the borrowing state of the reserve * @param self The reserve configuration * @return The borrowing state **/ function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } /** * @dev Enables or disables stable rate borrowing on the reserve * @param self The reserve configuration * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise **/ function setStableRateBorrowingEnabled( DataTypes.ReserveConfigurationMap memory self, bool enabled ) internal pure { self.data = (self.data & STABLE_BORROWING_MASK) | (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the stable rate borrowing state of the reserve * @param self The reserve configuration * @return The stable rate borrowing state **/ function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } /** * @dev Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor **/ function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } /** * @dev Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor **/ function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } /** * @dev Gets the configuration flags of the reserve * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns ( bool, bool, bool, bool ) { uint256 dataLocal = self.data; return ( (dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0, (dataLocal & ~BORROWING_MASK) != 0, (dataLocal & ~STABLE_BORROWING_MASK) != 0 ); } /** * @dev Gets the configuration paramters of the reserve * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParams(DataTypes.ReserveConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 dataLocal = self.data; return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration paramters of the reserve from a memory object * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration flags of the reserve from a memory object * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( bool, bool, bool, bool ) { return ( (self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0, (self.data & ~BORROWING_MASK) != 0, (self.data & ~STABLE_BORROWING_MASK) != 0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title UserConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the user configuration */ library UserConfiguration { uint256 internal constant BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555; /** * @dev Sets if the user is borrowing the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param borrowing True if the user is borrowing the reserve, false otherwise **/ function setBorrowing( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool borrowing ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2))) | (uint256(borrowing ? 1 : 0) << (reserveIndex * 2)); } /** * @dev Sets if the user is using as collateral the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise **/ function setUsingAsCollateral( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool usingAsCollateral ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2 + 1))) | (uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1)); } /** * @dev Used to validate if a user has been using the reserve for borrowing or as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise **/ function isUsingAsCollateralOrBorrowing( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 3 != 0; } /** * @dev Used to validate if a user has been using the reserve for borrowing * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing, false otherwise **/ function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 1 != 0; } /** * @dev Used to validate if a user has been using the reserve as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve as collateral, false otherwise **/ function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0; } /** * @dev Used to validate if a user has been borrowing from any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data & BORROWING_MASK != 0; } /** * @dev Used to validate if a user has not been using any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data == 0; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IReserveInterestRateStrategyInterface interface * @dev Interface for the calculation of the interest rates * @author Aave */ interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256, uint256, uint256 ); function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {WadRayMath} from './WadRayMath.sol'; library MathUtils { using SafeMath for uint256; using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {FlashLoanReceiverBase} from '../../flashloan/base/FlashLoanReceiverBase.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; contract MockFlashLoanReceiver is FlashLoanReceiverBase { using SafeERC20 for IERC20; ILendingPoolAddressesProvider internal _provider; event ExecutedWithFail(address[] _assets, uint256[] _amounts, uint256[] _premiums); event ExecutedWithSuccess(address[] _assets, uint256[] _amounts, uint256[] _premiums); bool _failExecution; uint256 _amountToApprove; bool _simulateEOA; constructor(ILendingPoolAddressesProvider provider) public FlashLoanReceiverBase(provider) {} function setFailExecutionTransfer(bool fail) public { _failExecution = fail; } function setAmountToApprove(uint256 amountToApprove) public { _amountToApprove = amountToApprove; } function setSimulateEOA(bool flag) public { _simulateEOA = flag; } function amountToApprove() public view returns (uint256) { return _amountToApprove; } function simulateEOA() public view returns (bool) { return _simulateEOA; } function executeOperation( address[] memory assets, uint256[] memory amounts, uint256[] memory premiums, address initiator, bytes memory params ) public override returns (bool) { params; initiator; if (_failExecution) { emit ExecutedWithFail(assets, amounts, premiums); return !_simulateEOA; } for (uint256 i = 0; i < assets.length; i++) { //mint to this contract the specific amount MintableERC20 token = MintableERC20(assets[i]); //check the contract has the specified balance require( amounts[i] <= IERC20(assets[i]).balanceOf(address(this)), 'Invalid balance for the contract' ); uint256 amountToReturn = (_amountToApprove != 0) ? _amountToApprove : amounts[i].add(premiums[i]); //execution does not fail - mint tokens and return them to the _destination token.mint(premiums[i]); IERC20(assets[i]).approve(address(LENDING_POOL), amountToReturn); } emit ExecutedWithSuccess(assets, amounts, premiums); return true; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableERC20 is ERC20 { constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokens * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(_msgSender(), value); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; import './IERC20.sol'; import './SafeMath.sol'; import './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: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Address} from '../dependencies/openzeppelin/contracts/Address.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title WalletBalanceProvider contract * @author Aave, influenced by https://github.com/wbobeirne/eth-balance-checker/blob/master/contracts/BalanceChecker.sol * @notice Implements a logic of getting multiple tokens balance for one user address * @dev NOTE: THIS CONTRACT IS NOT USED WITHIN THE AAVE PROTOCOL. It's an accessory contract used to reduce the number of calls * towards the blockchain from the Aave backend. **/ contract WalletBalanceProvider { using Address for address payable; using Address for address; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; address constant MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** @dev Fallback function, don't accept any ETH **/ receive() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), '22'); } /** @dev Check the token balance of a wallet in a token contract Returns the balance of the token for user. Avoids possible errors: - return 0 on non-contract address **/ function balanceOf(address user, address token) public view returns (uint256) { if (token == MOCK_ETH_ADDRESS) { return user.balance; // ETH balance // check if token is actually a contract } else if (token.isContract()) { return IERC20(token).balanceOf(user); } revert('INVALID_TOKEN'); } /** * @notice Fetches, for a list of _users and _tokens (ETH included with mock address), the balances * @param users The list of users * @param tokens The list of tokens * @return And array with the concatenation of, for each user, his/her balances **/ function batchBalanceOf(address[] calldata users, address[] calldata tokens) external view returns (uint256[] memory) { uint256[] memory balances = new uint256[](users.length * tokens.length); for (uint256 i = 0; i < users.length; i++) { for (uint256 j = 0; j < tokens.length; j++) { balances[i * tokens.length + j] = balanceOf(users[i], tokens[j]); } } return balances; } /** @dev provides balances of user wallet for all reserves available on the pool */ function getUserWalletBalances(address provider, address user) external view returns (address[] memory, uint256[] memory) { ILendingPool pool = ILendingPool(ILendingPoolAddressesProvider(provider).getLendingPool()); address[] memory reserves = pool.getReservesList(); address[] memory reservesWithEth = new address[](reserves.length + 1); for (uint256 i = 0; i < reserves.length; i++) { reservesWithEth[i] = reserves[i]; } reservesWithEth[reserves.length] = MOCK_ETH_ADDRESS; uint256[] memory balances = new uint256[](reservesWithEth.length); for (uint256 j = 0; j < reserves.length; j++) { DataTypes.ReserveConfigurationMap memory configuration = pool.getConfiguration(reservesWithEth[j]); (bool isActive, , , ) = configuration.getFlagsMemory(); if (!isActive) { balances[j] = 0; continue; } balances[j] = balanceOf(user, reservesWithEth[j]); } balances[reserves.length] = balanceOf(user, MOCK_ETH_ADDRESS); return (reservesWithEth, balances); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IWETH} from './interfaces/IWETH.sol'; import {IWETHGateway} from './interfaces/IWETHGateway.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract WETHGateway is IWETHGateway, Ownable { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; IWETH internal immutable WETH; /** * @dev Sets the WETH address and the LendingPoolAddressesProvider address. Infinite approves lending pool. * @param weth Address of the Wrapped Ether contract **/ constructor(address weth) public { WETH = IWETH(weth); } function authorizeLendingPool(address lendingPool) external onlyOwner { WETH.approve(lendingPool, uint256(-1)); } /** * @dev deposits WETH into the reserve, using native ETH. A corresponding amount of the overlying asset (aTokens) * is minted. * @param lendingPool address of the targeted underlying lending pool * @param onBehalfOf address of the user who will receive the aTokens representing the deposit * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable override { WETH.deposit{value: msg.value}(); ILendingPool(lendingPool).deposit(address(WETH), msg.value, onBehalfOf, referralCode); } /** * @dev withdraws the WETH _reserves of msg.sender. * @param lendingPool address of the targeted underlying lending pool * @param amount amount of aWETH to withdraw and receive native ETH * @param to address of the user who will receive native ETH */ function withdrawETH( address lendingPool, uint256 amount, address to ) external override { IAToken aWETH = IAToken(ILendingPool(lendingPool).getReserveData(address(WETH)).aTokenAddress); uint256 userBalance = aWETH.balanceOf(msg.sender); uint256 amountToWithdraw = amount; // if amount is equal to uint(-1), the user wants to redeem everything if (amount == type(uint256).max) { amountToWithdraw = userBalance; } aWETH.transferFrom(msg.sender, address(this), amountToWithdraw); ILendingPool(lendingPool).withdraw(address(WETH), amountToWithdraw, address(this)); WETH.withdraw(amountToWithdraw); _safeTransferETH(to, amountToWithdraw); } /** * @dev repays a borrow on the WETH reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). * @param lendingPool address of the targeted underlying lending pool * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything * @param rateMode the rate mode to repay * @param onBehalfOf the address for which msg.sender is repaying */ function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable override { (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebtMemory( onBehalfOf, ILendingPool(lendingPool).getReserveData(address(WETH)) ); uint256 paybackAmount = DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } require(msg.value >= paybackAmount, 'msg.value is less than repayment amount'); WETH.deposit{value: paybackAmount}(); ILendingPool(lendingPool).repay(address(WETH), msg.value, rateMode, onBehalfOf); // refund remaining dust eth if (msg.value > paybackAmount) _safeTransferETH(msg.sender, msg.value - paybackAmount); } /** * @dev borrow WETH, unwraps to ETH and send both the ETH and DebtTokens to msg.sender, via `approveDelegation` and onBehalf argument in `LendingPool.borrow`. * @param lendingPool address of the targeted underlying lending pool * @param amount the amount of ETH to borrow * @param interesRateMode the interest rate mode * @param referralCode integrators are assigned a referral code and can potentially receive rewards */ function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external override { ILendingPool(lendingPool).borrow( address(WETH), amount, interesRateMode, referralCode, msg.sender ); WETH.withdraw(amount); _safeTransferETH(msg.sender, amount); } /** * @dev transfer ETH to an address, revert if it fails. * @param to recipient of the transfer * @param value the amount to send */ function _safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'ETH_TRANSFER_FAILED'); } /** * @dev transfer ERC20 from the utility contract, for ERC20 recovery in case of stuck tokens due * direct transfers to the contract address. * @param token token to transfer * @param to recipient of the transfer * @param amount amount to send */ function emergencyTokenTransfer( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } /** * @dev transfer native Ether from the utility contract, for native Ether recovery in case of stuck Ether * due selfdestructs or transfer ether to pre-computated contract address before deployment. * @param to recipient of the transfer * @param amount amount to send */ function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner { _safeTransferETH(to, amount); } /** * @dev Get WETH address used by WETHGateway */ function getWETHAddress() external view returns (address) { return address(WETH); } /** * @dev Only WETH contract is allowed to transfer ETH here. Prevent other addresses to send Ether to this contract. */ receive() external payable { require(msg.sender == address(WETH), 'Receive not allowed'); } /** * @dev Revert fallback calls */ fallback() external payable { revert('Fallback not allowed'); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function approve(address guy, uint256 wad) external returns (bool); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETHGateway { function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable; function withdrawETH( address lendingPool, uint256 amount, address onBehalfOf ) external; function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable; function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import 'hardhat/console.sol'; /** * @title DefaultReserveInterestRateStrategy contract * @notice Implements the calculation of the interest rates depending on the reserve state * @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE` * point of utilization and another from that one to 100% * - An instance of this same contract, can't be used across different Aave markets, due to the caching * of the LendingPoolAddressesProvider * @author Aave **/ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; using PercentageMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates. * Expressed in ray **/ uint256 public immutable OPTIMAL_UTILIZATION_RATE; /** * @dev This constant represents the excess utilization rate above the optimal. It's always equal to * 1-optimal utilization rate. Added as a constant here for gas optimizations. * Expressed in ray **/ uint256 public immutable EXCESS_UTILIZATION_RATE; ILendingPoolAddressesProvider public immutable addressesProvider; // Base variable borrow rate when Utilization rate = 0. Expressed in ray uint256 internal immutable _baseVariableBorrowRate; // Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope1; // Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope2; // Slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope1; // Slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope2; constructor( ILendingPoolAddressesProvider provider, uint256 optimalUtilizationRate, uint256 baseVariableBorrowRate, uint256 variableRateSlope1, uint256 variableRateSlope2, uint256 stableRateSlope1, uint256 stableRateSlope2 ) public { OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate; EXCESS_UTILIZATION_RATE = WadRayMath.ray().sub(optimalUtilizationRate); addressesProvider = provider; _baseVariableBorrowRate = baseVariableBorrowRate; _variableRateSlope1 = variableRateSlope1; _variableRateSlope2 = variableRateSlope2; _stableRateSlope1 = stableRateSlope1; _stableRateSlope2 = stableRateSlope2; } function variableRateSlope1() external view returns (uint256) { return _variableRateSlope1; } function variableRateSlope2() external view returns (uint256) { return _variableRateSlope2; } function stableRateSlope1() external view returns (uint256) { return _stableRateSlope1; } function stableRateSlope2() external view returns (uint256) { return _stableRateSlope2; } function baseVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate; } function getMaxVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate.add(_variableRateSlope1).add(_variableRateSlope2); } /** * @dev Calculates the interest rates depending on the reserve's state and configurations * @param reserve The address of the reserve * @param liquidityAdded The liquidity added during the operation * @param liquidityTaken The liquidity taken during the operation * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view override returns ( uint256, uint256, uint256 ) { uint256 availableLiquidity = IERC20(reserve).balanceOf(aToken); //avoid stack too deep availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken); return calculateInterestRates( reserve, availableLiquidity, totalStableDebt, totalVariableDebt, averageStableBorrowRate, reserveFactor ); } struct CalcInterestRatesLocalVars { uint256 totalDebt; uint256 currentVariableBorrowRate; uint256 currentStableBorrowRate; uint256 currentLiquidityRate; uint256 utilizationRate; } /** * @dev Calculates the interest rates depending on the reserve's state and configurations. * NOTE This function is kept for compatibility with the previous DefaultInterestRateStrategy interface. * New protocol implementation uses the new calculateInterestRates() interface * @param reserve The address of the reserve * @param availableLiquidity The liquidity available in the corresponding aToken * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) public view override returns ( uint256, uint256, uint256 ) { CalcInterestRatesLocalVars memory vars; vars.totalDebt = totalStableDebt.add(totalVariableDebt); vars.currentVariableBorrowRate = 0; vars.currentStableBorrowRate = 0; vars.currentLiquidityRate = 0; vars.utilizationRate = vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt)); vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(reserve); if (vars.utilizationRate > OPTIMAL_UTILIZATION_RATE) { uint256 excessUtilizationRateRatio = vars.utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE); vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add( _stableRateSlope2.rayMul(excessUtilizationRateRatio) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add( _variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { vars.currentStableBorrowRate = vars.currentStableBorrowRate.add( _stableRateSlope1.rayMul(vars.utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE)) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add( vars.utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE) ); } vars.currentLiquidityRate = _getOverallBorrowRate( totalStableDebt, totalVariableDebt, vars .currentVariableBorrowRate, averageStableBorrowRate ) .rayMul(vars.utilizationRate) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor)); return ( vars.currentLiquidityRate, vars.currentStableBorrowRate, vars.currentVariableBorrowRate ); } /** * @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param currentVariableBorrowRate The current variable borrow rate of the reserve * @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans * @return The weighted averaged borrow rate **/ function _getOverallBorrowRate( uint256 totalStableDebt, uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalDebt = totalStableDebt.add(totalVariableDebt); if (totalDebt == 0) return 0; uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay()); return overallBorrowRate; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address asset, uint256 rate) external; } // 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: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUiPoolDataProvider} from './interfaces/IUiPoolDataProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; contract UiPoolDataProvider is IUiPoolDataProvider { using WadRayMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address public constant MOCK_USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; function getInterestRateStrategySlopes(DefaultReserveInterestRateStrategy interestRateStrategy) internal view returns ( uint256, uint256, uint256, uint256 ) { return ( interestRateStrategy.variableRateSlope1(), interestRateStrategy.variableRateSlope2(), interestRateStrategy.stableRateSlope1(), interestRateStrategy.stableRateSlope2() ); } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view override returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); IPriceOracleGetter oracle = IPriceOracleGetter(provider.getPriceOracle()); address[] memory reserves = lendingPool.getReservesList(); DataTypes.UserConfigurationMap memory userConfig = lendingPool.getUserConfiguration(user); AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length); UserReserveData[] memory userReservesData = new UserReserveData[](user != address(0) ? reserves.length : 0); for (uint256 i = 0; i < reserves.length; i++) { AggregatedReserveData memory reserveData = reservesData[i]; reserveData.underlyingAsset = reserves[i]; // reserve current state DataTypes.ReserveData memory baseData = lendingPool.getReserveData(reserveData.underlyingAsset); reserveData.liquidityIndex = baseData.liquidityIndex; reserveData.variableBorrowIndex = baseData.variableBorrowIndex; reserveData.liquidityRate = baseData.currentLiquidityRate; reserveData.variableBorrowRate = baseData.currentVariableBorrowRate; reserveData.stableBorrowRate = baseData.currentStableBorrowRate; reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp; reserveData.aTokenAddress = baseData.aTokenAddress; reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress; reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress; reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress; reserveData.priceInEth = oracle.getAssetPrice(reserveData.underlyingAsset); reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf( reserveData.aTokenAddress ); ( reserveData.totalPrincipalStableDebt, , reserveData.averageStableRate, reserveData.stableDebtLastUpdateTimestamp ) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData(); reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress) .scaledTotalSupply(); // reserve configuration // we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol(); reserveData.name = ''; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = baseData.configuration.getParamsMemory(); ( reserveData.isActive, reserveData.isFrozen, reserveData.borrowingEnabled, reserveData.stableBorrowRateEnabled ) = baseData.configuration.getFlagsMemory(); reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0; ( reserveData.variableRateSlope1, reserveData.variableRateSlope2, reserveData.stableRateSlope1, reserveData.stableRateSlope2 ) = getInterestRateStrategySlopes( DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress) ); if (user != address(0)) { // user reserve data userReservesData[i].underlyingAsset = reserveData.underlyingAsset; userReservesData[i].scaledATokenBalance = IAToken(reserveData.aTokenAddress) .scaledBalanceOf(user); userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i); if (userConfig.isBorrowing(i)) { userReservesData[i].scaledVariableDebt = IVariableDebtToken( reserveData .variableDebtTokenAddress ) .scaledBalanceOf(user); userReservesData[i].principalStableDebt = IStableDebtToken( reserveData .stableDebtTokenAddress ) .principalBalanceOf(user); if (userReservesData[i].principalStableDebt != 0) { userReservesData[i].stableBorrowRate = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserStableRate(user); userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserLastUpdated(user); } } } } return (reservesData, userReservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; interface IUiPoolDataProvider { struct AggregatedReserveData { address underlyingAsset; string name; string symbol; uint256 decimals; uint256 baseLTVasCollateral; uint256 reserveLiquidationThreshold; uint256 reserveLiquidationBonus; uint256 reserveFactor; bool usageAsCollateralEnabled; bool borrowingEnabled; bool stableBorrowRateEnabled; bool isActive; bool isFrozen; // base data uint128 liquidityIndex; uint128 variableBorrowIndex; uint128 liquidityRate; uint128 variableBorrowRate; uint128 stableBorrowRate; uint40 lastUpdateTimestamp; address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; address interestRateStrategyAddress; // uint256 availableLiquidity; uint256 totalPrincipalStableDebt; uint256 averageStableRate; uint256 stableDebtLastUpdateTimestamp; uint256 totalScaledVariableDebt; uint256 priceInEth; uint256 variableRateSlope1; uint256 variableRateSlope2; uint256 stableRateSlope1; uint256 stableRateSlope2; } // // struct ReserveData { // uint256 averageStableBorrowRate; // uint256 totalLiquidity; // } struct UserReserveData { address underlyingAsset; uint256 scaledATokenBalance; bool usageAsCollateralEnabledOnUser; uint256 stableBorrowRate; uint256 scaledVariableDebt; uint256 principalStableDebt; uint256 stableBorrowLastUpdateTimestamp; } // // struct ATokenSupplyData { // string name; // string symbol; // uint8 decimals; // uint256 totalSupply; // address aTokenAddress; // } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ); // function getUserReservesData(ILendingPoolAddressesProvider provider, address user) // external // view // returns (UserReserveData[] memory); // // function getAllATokenSupply(ILendingPoolAddressesProvider provider) // external // view // returns (ATokenSupplyData[] memory); // // function getATokenSupply(address[] calldata aTokens) // external // view // returns (ATokenSupplyData[] memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract AaveProtocolDataProvider { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2; address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct TokenData { string symbol; address tokenAddress; } ILendingPoolAddressesProvider public immutable ADDRESSES_PROVIDER; constructor(ILendingPoolAddressesProvider addressesProvider) public { ADDRESSES_PROVIDER = addressesProvider; } function getAllReservesTokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory reservesTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { if (reserves[i] == MKR) { reservesTokens[i] = TokenData({symbol: 'MKR', tokenAddress: reserves[i]}); continue; } if (reserves[i] == ETH) { reservesTokens[i] = TokenData({symbol: 'ETH', tokenAddress: reserves[i]}); continue; } reservesTokens[i] = TokenData({ symbol: IERC20Detailed(reserves[i]).symbol(), tokenAddress: reserves[i] }); } return reservesTokens; } function getAllATokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory aTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { DataTypes.ReserveData memory reserveData = pool.getReserveData(reserves[i]); aTokens[i] = TokenData({ symbol: IERC20Detailed(reserveData.aTokenAddress).symbol(), tokenAddress: reserveData.aTokenAddress }); } return aTokens; } function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ) { DataTypes.ReserveConfigurationMap memory configuration = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getConfiguration(asset); (ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor) = configuration .getParamsMemory(); (isActive, isFrozen, borrowingEnabled, stableBorrowRateEnabled) = configuration .getFlagsMemory(); usageAsCollateralEnabled = liquidationThreshold > 0; } function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( IERC20Detailed(asset).balanceOf(reserve.aTokenAddress), IERC20Detailed(reserve.stableDebtTokenAddress).totalSupply(), IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply(), reserve.currentLiquidityRate, reserve.currentVariableBorrowRate, reserve.currentStableBorrowRate, IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(), reserve.liquidityIndex, reserve.variableBorrowIndex, reserve.lastUpdateTimestamp ); } function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); DataTypes.UserConfigurationMap memory userConfig = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getUserConfiguration(user); currentATokenBalance = IERC20Detailed(reserve.aTokenAddress).balanceOf(user); currentVariableDebt = IERC20Detailed(reserve.variableDebtTokenAddress).balanceOf(user); currentStableDebt = IERC20Detailed(reserve.stableDebtTokenAddress).balanceOf(user); principalStableDebt = IStableDebtToken(reserve.stableDebtTokenAddress).principalBalanceOf(user); scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user); liquidityRate = reserve.currentLiquidityRate; stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( user ); usageAsCollateralEnabled = userConfig.isUsingAsCollateral(reserve.id); } function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( reserve.aTokenAddress, reserve.stableDebtTokenAddress, reserve.variableDebtTokenAddress ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title VariableDebtToken * @notice Implements a variable debt token to track the borrowing positions of users * at variable rate mode * @author Aave **/ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Calculates the accumulated debt balance of the user * @return The debt balance of the user **/ function balanceOf(address user) public view virtual override returns (uint256) { uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; } return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Mints debt token to the `onBehalfOf` address * - Only callable by the LendingPool * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } uint256 previousBalance = super.balanceOf(onBehalfOf); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(onBehalfOf, amountScaled); emit Transfer(address(0), onBehalfOf, amount); emit Mint(user, onBehalfOf, amount, index); return previousBalance == 0; } /** * @dev Burns user variable debt * - Only callable by the LendingPool * @param user The user whose debt is getting burned * @param amount The amount getting burned * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); } /** * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action **/ function scaledBalanceOf(address user) public view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users * @return The total supply **/ function totalSupply() public view virtual override returns (uint256) { return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the principal balance of the user and principal total supply. * @param user The address of the user * @return The principal balance of the user * @return The principal total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../../interfaces/ILendingPool.sol'; import {ICreditDelegationToken} from '../../../interfaces/ICreditDelegationToken.sol'; import { VersionedInitializable } from '../../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from '../IncentivizedERC20.sol'; import {Errors} from '../../libraries/helpers/Errors.sol'; /** * @title DebtTokenBase * @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken * @author Aave */ abstract contract DebtTokenBase is IncentivizedERC20('DEBTTOKEN_IMPL', 'DEBTTOKEN_IMPL', 0), VersionedInitializable, ICreditDelegationToken { mapping(address => mapping(address => uint256)) internal _borrowAllowances; /** * @dev Only lending pool can call functions marked by this modifier **/ modifier onlyLendingPool { require(_msgSender() == address(_getLendingPool()), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external override { _borrowAllowances[_msgSender()][delegatee] = amount; emit BorrowAllowanceDelegated(_msgSender(), delegatee, _getUnderlyingAssetAddress(), amount); } /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view override returns (uint256) { return _borrowAllowances[fromUser][toUser]; } /** * @dev Being non transferrable, the debt token does not implement any of the * standard ERC20 functions for transfer and allowance. **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function allowance(address owner, address spender) public view virtual override returns (uint256) { owner; spender; revert('ALLOWANCE_NOT_SUPPORTED'); } function approve(address spender, uint256 amount) public virtual override returns (bool) { spender; amount; revert('APPROVAL_NOT_SUPPORTED'); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { sender; recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { spender; addedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { spender; subtractedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function _decreaseBorrowAllowance( address delegator, address delegatee, uint256 amount ) internal { uint256 newAllowance = _borrowAllowances[delegator][delegatee].sub(amount, Errors.BORROW_ALLOWANCE_NOT_ENOUGH); _borrowAllowances[delegator][delegatee] = newAllowance; emit BorrowAllowanceDelegated(delegator, delegatee, _getUnderlyingAssetAddress(), newAllowance); } function _getUnderlyingAssetAddress() internal view virtual returns (address); function _getLendingPool() internal view virtual returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface ICreditDelegationToken { event BorrowAllowanceDelegated( address indexed fromUser, address indexed toUser, address asset, uint256 amount ); /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external; /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title ERC20 * @notice Basic ERC20 implementation * @author Aave, inspired by the Openzeppelin ERC20 implementation **/ abstract contract IncentivizedERC20 is Context, IERC20, IERC20Detailed { using SafeMath for uint256; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor( string memory name, string memory symbol, uint8 decimals ) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return The name of the token **/ function name() public view override returns (string memory) { return _name; } /** * @return The symbol of the token **/ function symbol() public view override returns (string memory) { return _symbol; } /** * @return The decimals of the token **/ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total supply of the token **/ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @return The balance of the token **/ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @return Abstract function implemented by the child aToken/debtToken. * Done this way in order to not break compatibility with previous versions of aTokens/debtTokens **/ function _getIncentivesController() internal view virtual returns(IAaveIncentivesController); /** * @dev Executes a transfer of tokens from _msgSender() to recipient * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev Returns the allowance of spender on the tokens owned by owner * @param owner The owner of the tokens * @param spender The user allowed to spend the owner's tokens * @return The amount of owner's tokens spender is allowed to spend **/ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Allows `spender` to spend the tokens owned by _msgSender() * @param spender The user allowed to spend _msgSender() tokens * @return `true` **/ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so * @param sender The owner of the tokens * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ 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') ); emit Transfer(sender, recipient, amount); return true; } /** * @dev Increases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param addedValue The amount being added to the allowance * @return `true` **/ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Decreases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param subtractedValue The amount being subtracted to the allowance * @return `true` **/ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } function _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 oldSenderBalance = _balances[sender]; _balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance'); uint256 oldRecipientBalance = _balances[recipient]; _balances[recipient] = _balances[recipient].add(amount); if (address(_getIncentivesController()) != address(0)) { uint256 currentTotalSupply = _totalSupply; _getIncentivesController().handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { _getIncentivesController().handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.add(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.sub(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } 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); } function _setName(string memory newName) internal { _name = newName; } function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {VariableDebtToken} from '../../protocol/tokenization/VariableDebtToken.sol'; contract MockVariableDebtToken is VariableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {AToken} from '../../protocol/tokenization/AToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; contract MockAToken is AToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from './IncentivizedERC20.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title Aave ERC20 AToken * @dev Implementation of the interest bearing token for the Aave protocol * @author Aave */ contract AToken is VersionedInitializable, IncentivizedERC20('ATOKEN_IMPL', 'ATOKEN_IMPL', 0), IAToken { using WadRayMath for uint256; using SafeERC20 for IERC20; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); uint256 public constant ATOKEN_REVISION = 0x1; /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; bytes32 public DOMAIN_SEPARATOR; ILendingPool internal _pool; address internal _treasury; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; modifier onlyLendingPool { require(_msgSender() == address(_pool), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } function getRevision() internal pure virtual override returns (uint256) { return ATOKEN_REVISION; } /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external override initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(aTokenName)), keccak256(EIP712_REVISION), chainId, address(this) ) ); _setName(aTokenName); _setSymbol(aTokenSymbol); _setDecimals(aTokenDecimals); _pool = pool; _treasury = treasury; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), treasury, address(incentivesController), aTokenDecimals, aTokenName, aTokenSymbol, params ); } /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); IERC20(_underlyingAsset).safeTransfer(receiverOfUnderlying, amount); emit Transfer(user, address(0), amount); emit Burn(user, receiverOfUnderlying, amount, index); } /** * @dev Mints `amount` aTokens to `user` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { uint256 previousBalance = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(user, amountScaled); emit Transfer(address(0), user, amount); emit Mint(user, amount, index); return previousBalance == 0; } /** * @dev Mints aTokens to the reserve treasury * - Only callable by the LendingPool * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { if (amount == 0) { return; } address treasury = _treasury; // Compared to the normal mint, we don't check for rounding errors. // The amount to mint can easily be very small since it is a fraction of the interest ccrued. // In that case, the treasury will experience a (very small) loss, but it // wont cause potentially valid transactions to fail. _mint(treasury, amount.rayDiv(index)); emit Transfer(address(0), treasury, amount); emit Mint(treasury, amount, index); } /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * - Only callable by the LendingPool * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to, value); } /** * @dev Calculates the balance of the user: principal balance + interest generated by the principal * @param user The user whose balance is calculated * @return The balance of the user **/ function balanceOf(address user) public view override(IncentivizedERC20, IERC20) returns (uint256) { return super.balanceOf(user).rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) { uint256 currentSupplyScaled = super.totalSupply(); if (currentSupplyScaled == 0) { return 0; } return currentSupplyScaled.rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the address of the Aave treasury, receiving the fees on this aToken **/ function RESERVE_TREASURY_ADDRESS() public view returns (address) { return _treasury; } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev For internal usage in the logic of the parent contract IncentivizedERC20 **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param target The recipient of the aTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address target, uint256 amount) external override onlyLendingPool returns (uint256) { IERC20(_underlyingAsset).safeTransfer(target, amount); return amount; } /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external override onlyLendingPool {} /** * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadline * @param v Signature param * @param s Signature param * @param r Signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev Transfers the aTokens between two users. Validates the transfer * (ie checks for valid HF after the transfer) if required * @param from The source address * @param to The destination address * @param amount The amount getting transferred * @param validate `true` if the transfer needs to be validated **/ function _transfer( address from, address to, uint256 amount, bool validate ) internal { address underlyingAsset = _underlyingAsset; ILendingPool pool = _pool; uint256 index = pool.getReserveNormalizedIncome(underlyingAsset); uint256 fromBalanceBefore = super.balanceOf(from).rayMul(index); uint256 toBalanceBefore = super.balanceOf(to).rayMul(index); super._transfer(from, to, amount.rayDiv(index)); if (validate) { pool.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore); } emit BalanceTransfer(from, to, amount, index); } /** * @dev Overrides the parent _transfer to force validated transfer() and transferFrom() * @param from The source address * @param to The destination address * @param amount The amount getting transferred **/ function _transfer( address from, address to, uint256 amount ) internal override { _transfer(from, to, amount, true); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IDelegationToken} from '../../interfaces/IDelegationToken.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {AToken} from './AToken.sol'; /** * @title Aave AToken enabled to delegate voting power of the underlying asset to a different address * @dev The underlying asset needs to be compatible with the COMP delegation interface * @author Aave */ contract DelegationAwareAToken is AToken { modifier onlyPoolAdmin { require( _msgSender() == ILendingPool(_pool).getAddressesProvider().getPoolAdmin(), Errors.CALLER_NOT_POOL_ADMIN ); _; } /** * @dev Delegates voting power of the underlying asset to a `delegatee` address * @param delegatee The address that will receive the delegation **/ function delegateUnderlyingTo(address delegatee) external onlyPoolAdmin { IDelegationToken(_underlyingAsset).delegate(delegatee); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IDelegationToken * @dev Implements an interface for tokens with delegation COMP/UNI compatible * @author Aave **/ interface IDelegationToken { function delegate(address delegatee) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; import { ILendingPoolAddressesProviderRegistry } from '../../interfaces/ILendingPoolAddressesProviderRegistry.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesProviderRegistry { mapping(address => uint256) private _addressesProviders; address[] private _addressesProvidersList; /** * @dev Returns the list of registered addresses provider * @return The list of addresses provider, potentially containing address(0) elements **/ function getAddressesProvidersList() external view override returns (address[] memory) { address[] memory addressesProvidersList = _addressesProvidersList; uint256 maxLength = addressesProvidersList.length; address[] memory activeProviders = new address[](maxLength); for (uint256 i = 0; i < maxLength; i++) { if (_addressesProviders[addressesProvidersList[i]] > 0) { activeProviders[i] = addressesProvidersList[i]; } } return activeProviders; } /** * @dev Registers an addresses provider * @param provider The address of the new LendingPoolAddressesProvider * @param id The id for the new LendingPoolAddressesProvider, referring to the market it belongs to **/ function registerAddressesProvider(address provider, uint256 id) external override onlyOwner { require(id != 0, Errors.LPAPR_INVALID_ADDRESSES_PROVIDER_ID); _addressesProviders[provider] = id; _addToAddressesProvidersList(provider); emit AddressesProviderRegistered(provider); } /** * @dev Removes a LendingPoolAddressesProvider from the list of registered addresses provider * @param provider The LendingPoolAddressesProvider address **/ function unregisterAddressesProvider(address provider) external override onlyOwner { require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); } /** * @dev Returns the id on a registered LendingPoolAddressesProvider * @return The id or 0 if the LendingPoolAddressesProvider is not registered */ function getAddressesProviderIdByAddress(address addressesProvider) external view override returns (uint256) { return _addressesProviders[addressesProvider]; } function _addToAddressesProvidersList(address provider) internal { uint256 providersCount = _addressesProvidersList.length; for (uint256 i = 0; i < providersCount; i++) { if (_addressesProvidersList[i] == provider) { return; } } _addressesProvidersList.push(provider); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ interface ILendingPoolAddressesProviderRegistry { event AddressesProviderRegistered(address indexed newAddress); event AddressesProviderUnregistered(address indexed newAddress); function getAddressesProvidersList() external view returns (address[] memory); function getAddressesProviderIdByAddress(address addressesProvider) external view returns (uint256); function registerAddressesProvider(address provider, uint256 id) external; function unregisterAddressesProvider(address provider) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IChainlinkAggregator} from '../interfaces/IChainlinkAggregator.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; /// @title AaveOracle /// @author Aave /// @notice Proxy smart contract to get the price of an asset from a price source, with Chainlink Aggregator /// smart contracts as primary option /// - If the returned price by a Chainlink aggregator is <= 0, the call is forwarded to a fallbackOracle /// - Owned by the Aave governance system, allowed to add sources for assets, replace them /// and change the fallbackOracle contract AaveOracle is IPriceOracleGetter, Ownable { using SafeERC20 for IERC20; event WethSet(address indexed weth); event AssetSourceUpdated(address indexed asset, address indexed source); event FallbackOracleUpdated(address indexed fallbackOracle); mapping(address => IChainlinkAggregator) private assetsSources; IPriceOracleGetter private _fallbackOracle; address public immutable WETH; /// @notice Constructor /// @param assets The addresses of the assets /// @param sources The address of the source of each asset /// @param fallbackOracle The address of the fallback oracle to use if the data of an /// aggregator is not consistent constructor( address[] memory assets, address[] memory sources, address fallbackOracle, address weth ) public { _setFallbackOracle(fallbackOracle); _setAssetsSources(assets, sources); WETH = weth; emit WethSet(weth); } /// @notice External function called by the Aave governance to set or replace sources of assets /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function setAssetSources(address[] calldata assets, address[] calldata sources) external onlyOwner { _setAssetsSources(assets, sources); } /// @notice Sets the fallbackOracle /// - Callable only by the Aave governance /// @param fallbackOracle The address of the fallbackOracle function setFallbackOracle(address fallbackOracle) external onlyOwner { _setFallbackOracle(fallbackOracle); } /// @notice Internal function to set the sources for each asset /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function _setAssetsSources(address[] memory assets, address[] memory sources) internal { require(assets.length == sources.length, 'INCONSISTENT_PARAMS_LENGTH'); for (uint256 i = 0; i < assets.length; i++) { assetsSources[assets[i]] = IChainlinkAggregator(sources[i]); emit AssetSourceUpdated(assets[i], sources[i]); } } /// @notice Internal function to set the fallbackOracle /// @param fallbackOracle The address of the fallbackOracle function _setFallbackOracle(address fallbackOracle) internal { _fallbackOracle = IPriceOracleGetter(fallbackOracle); emit FallbackOracleUpdated(fallbackOracle); } /// @notice Gets an asset price by address /// @param asset The asset address function getAssetPrice(address asset) public view override returns (uint256) { IChainlinkAggregator source = assetsSources[asset]; if (asset == WETH) { return 1 ether; } else if (address(source) == address(0)) { return _fallbackOracle.getAssetPrice(asset); } else { int256 price = IChainlinkAggregator(source).latestAnswer(); if (price > 0) { return uint256(price); } else { return _fallbackOracle.getAssetPrice(asset); } } } /// @notice Gets a list of prices from a list of assets addresses /// @param assets The list of assets addresses function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory) { uint256[] memory prices = new uint256[](assets.length); for (uint256 i = 0; i < assets.length; i++) { prices[i] = getAssetPrice(assets[i]); } return prices; } /// @notice Gets the address of the source for an asset address /// @param asset The address of the asset /// @return address The address of the source function getSourceOfAsset(address asset) external view returns (address) { return address(assetsSources[asset]); } /// @notice Gets the address of the fallback oracle /// @return address The addres of the fallback oracle function getFallbackOracle() external view returns (address) { return address(_fallbackOracle); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import { InitializableImmutableAdminUpgradeabilityProxy } from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {IInitializableDebtToken} from '../../interfaces/IInitializableDebtToken.sol'; import {IInitializableAToken} from '../../interfaces/IInitializableAToken.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {ILendingPoolConfigurator} from '../../interfaces/ILendingPoolConfigurator.sol'; /** * @title LendingPoolConfigurator contract * @author Aave * @dev Implements the configuration methods for the Aave protocol **/ contract LendingPoolConfigurator is VersionedInitializable, ILendingPoolConfigurator { using SafeMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; ILendingPoolAddressesProvider internal addressesProvider; ILendingPool internal pool; modifier onlyPoolAdmin { require(addressesProvider.getPoolAdmin() == msg.sender, Errors.CALLER_NOT_POOL_ADMIN); _; } modifier onlyEmergencyAdmin { require( addressesProvider.getEmergencyAdmin() == msg.sender, Errors.LPC_CALLER_NOT_EMERGENCY_ADMIN ); _; } uint256 internal constant CONFIGURATOR_REVISION = 0x1; function getRevision() internal pure override returns (uint256) { return CONFIGURATOR_REVISION; } function initialize(ILendingPoolAddressesProvider provider) public initializer { addressesProvider = provider; pool = ILendingPool(addressesProvider.getLendingPool()); } /** * @dev Initializes reserves in batch **/ function batchInitReserve(InitReserveInput[] calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; for (uint256 i = 0; i < input.length; i++) { _initReserve(cachedPool, input[i]); } } function _initReserve(ILendingPool pool, InitReserveInput calldata input) internal { address aTokenProxyAddress = _initTokenWithProxy( input.aTokenImpl, abi.encodeWithSelector( IInitializableAToken.initialize.selector, pool, input.treasury, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.aTokenName, input.aTokenSymbol, input.params ) ); address stableDebtTokenProxyAddress = _initTokenWithProxy( input.stableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.stableDebtTokenName, input.stableDebtTokenSymbol, input.params ) ); address variableDebtTokenProxyAddress = _initTokenWithProxy( input.variableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.variableDebtTokenName, input.variableDebtTokenSymbol, input.params ) ); pool.initReserve( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(input.underlyingAsset); currentConfig.setDecimals(input.underlyingAssetDecimals); currentConfig.setActive(true); currentConfig.setFrozen(false); pool.setConfiguration(input.underlyingAsset, currentConfig.data); emit ReserveInitialized( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); } /** * @dev Updates the aToken implementation for the reserve **/ function updateAToken(UpdateATokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableAToken.initialize.selector, cachedPool, input.treasury, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.aTokenAddress, input.implementation, encodedCall ); emit ATokenUpgraded(input.asset, reserveData.aTokenAddress, input.implementation); } /** * @dev Updates the stable debt token implementation for the reserve **/ function updateStableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.stableDebtTokenAddress, input.implementation, encodedCall ); emit StableDebtTokenUpgraded( input.asset, reserveData.stableDebtTokenAddress, input.implementation ); } /** * @dev Updates the variable debt token implementation for the asset **/ function updateVariableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.variableDebtTokenAddress, input.implementation, encodedCall ); emit VariableDebtTokenUpgraded( input.asset, reserveData.variableDebtTokenAddress, input.implementation ); } /** * @dev Enables borrowing on a reserve * @param asset The address of the underlying asset of the reserve * @param stableBorrowRateEnabled True if stable borrow rate needs to be enabled by default on this reserve **/ function enableBorrowingOnReserve(address asset, bool stableBorrowRateEnabled) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(true); currentConfig.setStableRateBorrowingEnabled(stableBorrowRateEnabled); pool.setConfiguration(asset, currentConfig.data); emit BorrowingEnabledOnReserve(asset, stableBorrowRateEnabled); } /** * @dev Disables borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableBorrowingOnReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit BorrowingDisabledOnReserve(asset); } /** * @dev Configures the reserve collateralization parameters * all the values are expressed in percentages with two decimals of precision. A valid value is 10000, which means 100.00% * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset. The values is always above 100%. A value of 105% * means the liquidator will receive a 5% bonus **/ function configureReserveAsCollateral( address asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); //validation of the parameters: the LTV can //only be lower or equal than the liquidation threshold //(otherwise a loan against the asset would cause instantaneous liquidation) require(ltv <= liquidationThreshold, Errors.LPC_INVALID_CONFIGURATION); if (liquidationThreshold != 0) { //liquidation bonus must be bigger than 100.00%, otherwise the liquidator would receive less //collateral than needed to cover the debt require( liquidationBonus > PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); //if threshold * bonus is less than PERCENTAGE_FACTOR, it's guaranteed that at the moment //a loan is taken there is enough collateral available to cover the liquidation bonus require( liquidationThreshold.percentMul(liquidationBonus) <= PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); } else { require(liquidationBonus == 0, Errors.LPC_INVALID_CONFIGURATION); //if the liquidation threshold is being set to 0, // the reserve is being disabled as collateral. To do so, //we need to ensure no liquidity is deposited _checkNoLiquidity(asset); } currentConfig.setLtv(ltv); currentConfig.setLiquidationThreshold(liquidationThreshold); currentConfig.setLiquidationBonus(liquidationBonus); pool.setConfiguration(asset, currentConfig.data); emit CollateralConfigurationChanged(asset, ltv, liquidationThreshold, liquidationBonus); } /** * @dev Enable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function enableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(true); pool.setConfiguration(asset, currentConfig.data); emit StableRateEnabledOnReserve(asset); } /** * @dev Disable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit StableRateDisabledOnReserve(asset); } /** * @dev Activates a reserve * @param asset The address of the underlying asset of the reserve **/ function activateReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveActivated(asset); } /** * @dev Deactivates a reserve * @param asset The address of the underlying asset of the reserve **/ function deactivateReserve(address asset) external onlyPoolAdmin { _checkNoLiquidity(asset); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveDeactivated(asset); } /** * @dev Freezes a reserve. A frozen reserve doesn't allow any new deposit, borrow or rate swap * but allows repayments, liquidations, rate rebalances and withdrawals * @param asset The address of the underlying asset of the reserve **/ function freezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveFrozen(asset); } /** * @dev Unfreezes a reserve * @param asset The address of the underlying asset of the reserve **/ function unfreezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveUnfrozen(asset); } /** * @dev Updates the reserve factor of a reserve * @param asset The address of the underlying asset of the reserve * @param reserveFactor The new reserve factor of the reserve **/ function setReserveFactor(address asset, uint256 reserveFactor) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setReserveFactor(reserveFactor); pool.setConfiguration(asset, currentConfig.data); emit ReserveFactorChanged(asset, reserveFactor); } /** * @dev Sets the interest rate strategy of a reserve * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The new address of the interest strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external onlyPoolAdmin { pool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress); emit ReserveInterestRateStrategyChanged(asset, rateStrategyAddress); } /** * @dev pauses or unpauses all the actions of the protocol, including aToken transfers * @param val true if protocol needs to be paused, false otherwise **/ function setPoolPause(bool val) external onlyEmergencyAdmin { pool.setPause(val); } function _initTokenWithProxy(address implementation, bytes memory initParams) internal returns (address) { InitializableImmutableAdminUpgradeabilityProxy proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(implementation, initParams); return address(proxy); } function _upgradeTokenImplementation( address proxyAddress, address implementation, bytes memory initParams ) internal { InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(payable(proxyAddress)); proxy.upgradeToAndCall(implementation, initParams); } function _checkNoLiquidity(address asset) internal view { DataTypes.ReserveData memory reserveData = pool.getReserveData(asset); uint256 availableLiquidity = IERC20Detailed(asset).balanceOf(reserveData.aTokenAddress); require( availableLiquidity == 0 && reserveData.currentLiquidityRate == 0, Errors.LPC_RESERVE_LIQUIDITY_NOT_0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseImmutableAdminUpgradeabilityProxy.sol'; import '../../../dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends BaseAdminUpgradeabilityProxy with an initializer function */ contract InitializableImmutableAdminUpgradeabilityProxy is BaseImmutableAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { constructor(address admin) public BaseImmutableAdminUpgradeabilityProxy(admin) {} /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) { BaseImmutableAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ILendingPoolConfigurator { struct InitReserveInput { address aTokenImpl; address stableDebtTokenImpl; address variableDebtTokenImpl; uint8 underlyingAssetDecimals; address interestRateStrategyAddress; address underlyingAsset; address treasury; address incentivesController; string underlyingAssetName; string aTokenName; string aTokenSymbol; string variableDebtTokenName; string variableDebtTokenSymbol; string stableDebtTokenName; string stableDebtTokenSymbol; bytes params; } struct UpdateATokenInput { address asset; address treasury; address incentivesController; string name; string symbol; address implementation; bytes params; } struct UpdateDebtTokenInput { address asset; address incentivesController; string name; string symbol; address implementation; bytes params; } /** * @dev Emitted when a reserve is initialized. * @param asset The address of the underlying asset of the reserve * @param aToken The address of the associated aToken contract * @param stableDebtToken The address of the associated stable rate debt token * @param variableDebtToken The address of the associated variable rate debt token * @param interestRateStrategyAddress The address of the interest rate strategy for the reserve **/ event ReserveInitialized( address indexed asset, address indexed aToken, address stableDebtToken, address variableDebtToken, address interestRateStrategyAddress ); /** * @dev Emitted when borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve * @param stableRateEnabled True if stable rate borrowing is enabled, false otherwise **/ event BorrowingEnabledOnReserve(address indexed asset, bool stableRateEnabled); /** * @dev Emitted when borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event BorrowingDisabledOnReserve(address indexed asset); /** * @dev Emitted when the collateralization risk parameters for the specified asset are updated. * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset **/ event CollateralConfigurationChanged( address indexed asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Emitted when stable rate borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateEnabledOnReserve(address indexed asset); /** * @dev Emitted when stable rate borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateDisabledOnReserve(address indexed asset); /** * @dev Emitted when a reserve is activated * @param asset The address of the underlying asset of the reserve **/ event ReserveActivated(address indexed asset); /** * @dev Emitted when a reserve is deactivated * @param asset The address of the underlying asset of the reserve **/ event ReserveDeactivated(address indexed asset); /** * @dev Emitted when a reserve is frozen * @param asset The address of the underlying asset of the reserve **/ event ReserveFrozen(address indexed asset); /** * @dev Emitted when a reserve is unfrozen * @param asset The address of the underlying asset of the reserve **/ event ReserveUnfrozen(address indexed asset); /** * @dev Emitted when a reserve factor is updated * @param asset The address of the underlying asset of the reserve * @param factor The new reserve factor **/ event ReserveFactorChanged(address indexed asset, uint256 factor); /** * @dev Emitted when the reserve decimals are updated * @param asset The address of the underlying asset of the reserve * @param decimals The new decimals **/ event ReserveDecimalsChanged(address indexed asset, uint256 decimals); /** * @dev Emitted when a reserve interest strategy contract is updated * @param asset The address of the underlying asset of the reserve * @param strategy The new address of the interest strategy contract **/ event ReserveInterestRateStrategyChanged(address indexed asset, address strategy); /** * @dev Emitted when an aToken implementation is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The aToken proxy address * @param implementation The new aToken implementation **/ event ATokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a stable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The stable debt token proxy address * @param implementation The new aToken implementation **/ event StableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a variable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The variable debt token proxy address * @param implementation The new aToken implementation **/ event VariableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import '../../../dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol'; /** * @title BaseImmutableAdminUpgradeabilityProxy * @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. The admin role is stored in an immutable, which * helps saving transactions costs * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { address immutable ADMIN; constructor(address admin) public { ADMIN = admin; } modifier ifAdmin() { if (msg.sender == ADMIN) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return ADMIN; } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != ADMIN, 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './Proxy.sol'; import '../contracts/Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view override returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), 'Cannot set a proxy implementation to a non-contract address' ); bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { //solium-disable-next-line assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {MathUtils} from '../libraries/math/MathUtils.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title StableDebtToken * @notice Implements a stable debt token to track the borrowing positions of users * at stable rate mode * @author Aave **/ contract StableDebtToken is IStableDebtToken, DebtTokenBase { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; uint256 internal _avgStableRate; mapping(address => uint40) internal _timestamps; mapping(address => uint256) internal _usersStableRate; uint40 internal _totalSupplyTimestamp; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Returns the average stable rate across all the stable rate debt * @return the average stable rate **/ function getAverageStableRate() external view virtual override returns (uint256) { return _avgStableRate; } /** * @dev Returns the timestamp of the last user action * @return The last update timestamp **/ function getUserLastUpdated(address user) external view virtual override returns (uint40) { return _timestamps[user]; } /** * @dev Returns the stable rate of the user * @param user The address of the user * @return The stable rate of user **/ function getUserStableRate(address user) external view virtual override returns (uint256) { return _usersStableRate[user]; } /** * @dev Calculates the current user debt balance * @return The accumulated debt of the user **/ function balanceOf(address account) public view virtual override returns (uint256) { uint256 accountBalance = super.balanceOf(account); uint256 stableRate = _usersStableRate[account]; if (accountBalance == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(stableRate, _timestamps[account]); return accountBalance.rayMul(cumulatedInterest); } struct MintLocalVars { uint256 previousSupply; uint256 nextSupply; uint256 amountInRay; uint256 newStableRate; uint256 currentAvgStableRate; } /** * @dev Mints debt token to the `onBehalfOf` address. * - Only callable by the LendingPool * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external override onlyLendingPool returns (bool) { MintLocalVars memory vars; if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(onBehalfOf); vars.previousSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; vars.nextSupply = _totalSupply = vars.previousSupply.add(amount); vars.amountInRay = amount.wadToRay(); vars.newStableRate = _usersStableRate[onBehalfOf] .rayMul(currentBalance.wadToRay()) .add(vars.amountInRay.rayMul(rate)) .rayDiv(currentBalance.add(amount).wadToRay()); require(vars.newStableRate <= type(uint128).max, Errors.SDT_STABLE_DEBT_OVERFLOW); _usersStableRate[onBehalfOf] = vars.newStableRate; //solium-disable-next-line _totalSupplyTimestamp = _timestamps[onBehalfOf] = uint40(block.timestamp); // Calculates the updated average stable rate vars.currentAvgStableRate = _avgStableRate = vars .currentAvgStableRate .rayMul(vars.previousSupply.wadToRay()) .add(rate.rayMul(vars.amountInRay)) .rayDiv(vars.nextSupply.wadToRay()); _mint(onBehalfOf, amount.add(balanceIncrease), vars.previousSupply); emit Transfer(address(0), onBehalfOf, amount); emit Mint( user, onBehalfOf, amount, currentBalance, balanceIncrease, vars.newStableRate, vars.currentAvgStableRate, vars.nextSupply ); return currentBalance == 0; } /** * @dev Burns debt of `user` * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external override onlyLendingPool { (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(user); uint256 previousSupply = totalSupply(); uint256 newAvgStableRate = 0; uint256 nextSupply = 0; uint256 userStableRate = _usersStableRate[user]; // Since the total supply and each single user debt accrue separately, // there might be accumulation errors so that the last borrower repaying // mght actually try to repay more than the available debt supply. // In this case we simply set the total supply and the avg stable rate to 0 if (previousSupply <= amount) { _avgStableRate = 0; _totalSupply = 0; } else { nextSupply = _totalSupply = previousSupply.sub(amount); uint256 firstTerm = _avgStableRate.rayMul(previousSupply.wadToRay()); uint256 secondTerm = userStableRate.rayMul(amount.wadToRay()); // For the same reason described above, when the last user is repaying it might // happen that user rate * user balance > avg rate * total supply. In that case, // we simply set the avg rate to 0 if (secondTerm >= firstTerm) { newAvgStableRate = _avgStableRate = _totalSupply = 0; } else { newAvgStableRate = _avgStableRate = firstTerm.sub(secondTerm).rayDiv(nextSupply.wadToRay()); } } if (amount == currentBalance) { _usersStableRate[user] = 0; _timestamps[user] = 0; } else { //solium-disable-next-line _timestamps[user] = uint40(block.timestamp); } //solium-disable-next-line _totalSupplyTimestamp = uint40(block.timestamp); if (balanceIncrease > amount) { uint256 amountToMint = balanceIncrease.sub(amount); _mint(user, amountToMint, previousSupply); emit Mint( user, user, amountToMint, currentBalance, balanceIncrease, userStableRate, newAvgStableRate, nextSupply ); } else { uint256 amountToBurn = amount.sub(balanceIncrease); _burn(user, amountToBurn, previousSupply); emit Burn(user, amountToBurn, currentBalance, balanceIncrease, newAvgStableRate, nextSupply); } emit Transfer(user, address(0), amount); } /** * @dev Calculates the increase in balance since the last user interaction * @param user The address of the user for which the interest is being accumulated * @return The previous principal balance, the new principal balance and the balance increase **/ function _calculateBalanceIncrease(address user) internal view returns ( uint256, uint256, uint256 ) { uint256 previousPrincipalBalance = super.balanceOf(user); if (previousPrincipalBalance == 0) { return (0, 0, 0); } // Calculation of the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease ); } /** * @dev Returns the principal and total supply, the average borrow rate and the last supply update timestamp **/ function getSupplyData() public view override returns ( uint256, uint256, uint256, uint40 ) { uint256 avgRate = _avgStableRate; return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate, _totalSupplyTimestamp); } /** * @dev Returns the the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() public view override returns (uint256, uint256) { uint256 avgRate = _avgStableRate; return (_calcTotalSupply(avgRate), avgRate); } /** * @dev Returns the total supply **/ function totalSupply() public view override returns (uint256) { return _calcTotalSupply(_avgStableRate); } /** * @dev Returns the timestamp at which the total supply was updated **/ function getTotalSupplyLastUpdated() public view override returns (uint40) { return _totalSupplyTimestamp; } /** * @dev Returns the principal debt balance of the user from * @param user The user's address * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev For internal usage in the logic of the parent contracts **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } /** * @dev Calculates the total supply * @param avgRate The average rate at which the total supply increases * @return The debt balance of the user since the last burn/mint action **/ function _calcTotalSupply(uint256 avgRate) internal view virtual returns (uint256) { uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(avgRate, _totalSupplyTimestamp); return principalSupply.rayMul(cumulatedInterest); } /** * @dev Mints stable debt tokens to an user * @param account The account receiving the debt tokens * @param amount The amount being minted * @param oldTotalSupply the total supply before the minting event **/ function _mint( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } /** * @dev Burns stable debt tokens of an user * @param account The user getting his debt burned * @param amount The amount being burned * @param oldTotalSupply The total supply before the burning event **/ function _burn( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, Errors.SDT_BURN_EXCEEDS_BALANCE); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {StableDebtToken} from '../../protocol/tokenization/StableDebtToken.sol'; contract MockStableDebtToken is StableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Address} from '../../dependencies/openzeppelin/contracts/Address.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IFlashLoanReceiver} from '../../flashloan/interfaces/IFlashLoanReceiver.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPool contract * @dev Main point of interaction with an Aave protocol's market * - Users can: * # Deposit * # Withdraw * # Borrow * # Repay * # Swap their loans between variable and stable rate * # Enable/disable their deposits as collateral rebalance stable rate borrow positions * # Liquidate positions * # Execute Flash Loans * - To be covered by a proxy contract, owned by the LendingPoolAddressesProvider of the specific market * - All admin functions are callable by the LendingPoolConfigurator contract defined also in the * LendingPoolAddressesProvider * @author Aave **/ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; uint256 public constant LENDINGPOOL_REVISION = 0x2; modifier whenNotPaused() { _whenNotPaused(); _; } modifier onlyLendingPoolConfigurator() { _onlyLendingPoolConfigurator(); _; } function _whenNotPaused() internal view { require(!_paused, Errors.LP_IS_PAUSED); } function _onlyLendingPoolConfigurator() internal view { require( _addressesProvider.getLendingPoolConfigurator() == msg.sender, Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR ); } function getRevision() internal pure override returns (uint256) { return LENDINGPOOL_REVISION; } /** * @dev Function is invoked by the proxy contract when the LendingPool contract is added to the * LendingPoolAddressesProvider of the market. * - Caching the address of the LendingPoolAddressesProvider in order to reduce gas consumption * on subsequent operations * @param provider The address of the LendingPoolAddressesProvider **/ function initialize(ILendingPoolAddressesProvider provider) public initializer { _addressesProvider = provider; _maxStableRateBorrowSizePercent = 2500; _flashLoanPremiumTotal = 9; _maxNumberOfReserves = 128; } /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address aToken = reserve.aTokenAddress; reserve.updateState(); reserve.updateInterestRates(asset, aToken, amount, 0); IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); bool isFirstDeposit = IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode); } /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address aToken = reserve.aTokenAddress; uint256 userBalance = IAToken(aToken).balanceOf(msg.sender); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); reserve.updateState(); reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; _executeBorrow( ExecuteBorrowParams( asset, msg.sender, onBehalfOf, amount, interestRateMode, reserve.aTokenAddress, referralCode, true ) ); } /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateRepay( reserve, amount, interestRateMode, onBehalfOf, stableDebt, variableDebt ); uint256 paybackAmount = interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); } address aToken = reserve.aTokenAddress; reserve.updateInterestRates(asset, aToken, paybackAmount, 0); if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); IAToken(aToken).handleRepayment(msg.sender, paybackAmount); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateSwapRateMode( reserve, _usersConfig[msg.sender], stableDebt, variableDebt, interestRateMode ); reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); IVariableDebtToken(reserve.variableDebtTokenAddress).mint( msg.sender, msg.sender, stableDebt, reserve.variableBorrowIndex ); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( msg.sender, variableDebt, reserve.variableBorrowIndex ); IStableDebtToken(reserve.stableDebtTokenAddress).mint( msg.sender, msg.sender, variableDebt, reserve.currentStableBorrowRate ); } reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); emit Swap(asset, msg.sender, rateMode); } /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress); IERC20 variableDebtToken = IERC20(reserve.variableDebtTokenAddress); address aTokenAddress = reserve.aTokenAddress; uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user); ValidationLogic.validateRebalanceStableBorrowRate( reserve, asset, stableDebtToken, variableDebtToken, aTokenAddress ); reserve.updateState(); IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt); IStableDebtToken(address(stableDebtToken)).mint( user, user, stableDebt, reserve.currentStableBorrowRate ); reserve.updateInterestRates(asset, aTokenAddress, 0, 0); emit RebalanceStableBorrowRate(asset, user); } /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( reserve, asset, useAsCollateral, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, useAsCollateral); if (useAsCollateral) { emit ReserveUsedAsCollateralEnabled(asset, msg.sender); } else { emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } } /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override whenNotPaused { address collateralManager = _addressesProvider.getLendingPoolCollateralManager(); //solium-disable-next-line (bool success, bytes memory result) = collateralManager.delegatecall( abi.encodeWithSignature( 'liquidationCall(address,address,address,uint256,bool)', collateralAsset, debtAsset, user, debtToCover, receiveAToken ) ); require(success, Errors.LP_LIQUIDATION_CALL_FAILED); (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); require(returnCode == 0, string(abi.encodePacked(returnMessage))); } struct FlashLoanLocalVars { IFlashLoanReceiver receiver; address oracle; uint256 i; address currentAsset; address currentATokenAddress; uint256 currentAmount; uint256 currentPremium; uint256 currentAmountPlusPremium; address debtToken; } /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external override whenNotPaused { FlashLoanLocalVars memory vars; ValidationLogic.validateFlashloan(assets, amounts); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); vars.receiver = IFlashLoanReceiver(receiverAddress); for (vars.i = 0; vars.i < assets.length; vars.i++) { aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress; premiums[vars.i] = amounts[vars.i].mul(_flashLoanPremiumTotal).div(10000); IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]); } require( vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params), Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN ); for (vars.i = 0; vars.i < assets.length; vars.i++) { vars.currentAsset = assets[vars.i]; vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) { _reserves[vars.currentAsset].updateState(); _reserves[vars.currentAsset].cumulateToLiquidityIndex( IERC20(vars.currentATokenAddress).totalSupply(), vars.currentPremium ); _reserves[vars.currentAsset].updateInterestRates( vars.currentAsset, vars.currentATokenAddress, vars.currentAmountPlusPremium, 0 ); IERC20(vars.currentAsset).safeTransferFrom( receiverAddress, vars.currentATokenAddress, vars.currentAmountPlusPremium ); } else { // If the user chose to not return the funds, the system checks if there is enough collateral and // eventually opens a debt position _executeBorrow( ExecuteBorrowParams( vars.currentAsset, msg.sender, onBehalfOf, vars.currentAmount, modes[vars.i], vars.currentATokenAddress, referralCode, false ) ); } emit FlashLoan( receiverAddress, msg.sender, vars.currentAsset, vars.currentAmount, vars.currentPremium, referralCode ); } } /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view override returns (DataTypes.ReserveData memory) { return _reserves[asset]; } /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view override returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { ( totalCollateralETH, totalDebtETH, ltv, currentLiquidationThreshold, healthFactor ) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( totalCollateralETH, totalDebtETH, ltv ); } /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view override returns (DataTypes.ReserveConfigurationMap memory) { return _reserves[asset].configuration; } /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view override returns (DataTypes.UserConfigurationMap memory) { return _usersConfig[user]; } /** * @dev Returns the normalized income per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view virtual override returns (uint256) { return _reserves[asset].getNormalizedIncome(); } /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view override returns (uint256) { return _reserves[asset].getNormalizedDebt(); } /** * @dev Returns if the LendingPool is paused */ function paused() external view override returns (bool) { return _paused; } /** * @dev Returns the list of the initialized reserves **/ function getReservesList() external view override returns (address[] memory) { address[] memory _activeReserves = new address[](_reservesCount); for (uint256 i = 0; i < _reservesCount; i++) { _activeReserves[i] = _reservesList[i]; } return _activeReserves; } /** * @dev Returns the cached LendingPoolAddressesProvider connected to this contract **/ function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) { return _addressesProvider; } /** * @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate */ function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) { return _maxStableRateBorrowSizePercent; } /** * @dev Returns the fee on flash loans */ function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) { return _flashLoanPremiumTotal; } /** * @dev Returns the maximum number of reserves supported to be listed in this LendingPool */ function MAX_NUMBER_RESERVES() public view returns (uint256) { return _maxNumberOfReserves; } /** * @dev Validates and finalizes an aToken transfer * - Only callable by the overlying aToken of the `asset` * @param asset The address of the underlying asset of the aToken * @param from The user from which the aTokens are transferred * @param to The user receiving the aTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The aToken balance of the `from` user before the transfer * @param balanceToBefore The aToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external override whenNotPaused { require(msg.sender == _reserves[asset].aTokenAddress, Errors.LP_CALLER_MUST_BE_AN_ATOKEN); ValidationLogic.validateTransfer( from, _reserves, _usersConfig[from], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); uint256 reserveId = _reserves[asset].id; if (from != to) { if (balanceFromBefore.sub(amount) == 0) { DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; fromConfig.setUsingAsCollateral(reserveId, false); emit ReserveUsedAsCollateralDisabled(asset, from); } if (balanceToBefore == 0 && amount != 0) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserveId, true); emit ReserveUsedAsCollateralEnabled(asset, to); } } } /** * @dev Initializes a reserve, activating it, assigning an aToken and debt tokens and an * interest rate strategy * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param aTokenAddress The address of the aToken that will be assigned to the reserve * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve * @param aTokenAddress The address of the VariableDebtToken that will be assigned to the reserve * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function initReserve( address asset, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external override onlyLendingPoolConfigurator { require(Address.isContract(asset), Errors.LP_NOT_CONTRACT); _reserves[asset].init( aTokenAddress, stableDebtAddress, variableDebtAddress, interestRateStrategyAddress ); _addReserveToList(asset); } /** * @dev Updates the address of the interest rate strategy contract * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The address of the interest rate strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external override onlyLendingPoolConfigurator { _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; } /** * @dev Sets the configuration bitmap of the reserve as a whole * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param configuration The new configuration bitmap **/ function setConfiguration(address asset, uint256 configuration) external override onlyLendingPoolConfigurator { _reserves[asset].configuration.data = configuration; } /** * @dev Set the _pause state of a reserve * - Only callable by the LendingPoolConfigurator contract * @param val `true` to pause the reserve, `false` to un-pause it */ function setPause(bool val) external override onlyLendingPoolConfigurator { _paused = val; if (_paused) { emit Paused(); } else { emit Unpaused(); } } struct ExecuteBorrowParams { address asset; address user; address onBehalfOf; uint256 amount; uint256 interestRateMode; address aTokenAddress; uint16 referralCode; bool releaseUnderlying; } function _executeBorrow(ExecuteBorrowParams memory vars) internal { DataTypes.ReserveData storage reserve = _reserves[vars.asset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf]; address oracle = _addressesProvider.getPriceOracle(); uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( 10**reserve.configuration.getDecimals() ); ValidationLogic.validateBorrow( vars.asset, reserve, vars.onBehalfOf, vars.amount, amountInETH, vars.interestRateMode, _maxStableRateBorrowSizePercent, _reserves, userConfig, _reservesList, _reservesCount, oracle ); reserve.updateState(); uint256 currentStableRate = 0; bool isFirstBorrowing = false; if (DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE) { currentStableRate = reserve.currentStableBorrowRate; isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, currentStableRate ); } else { isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); } if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( vars.asset, vars.aTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0 ); if (vars.releaseUnderlying) { IAToken(vars.aTokenAddress).transferUnderlyingTo(vars.user, vars.amount); } emit Borrow( vars.asset, vars.user, vars.onBehalfOf, vars.amount, vars.interestRateMode, DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE ? currentStableRate : reserve.currentVariableBorrowRate, vars.referralCode ); } function _addReserveToList(address asset) internal { uint256 reservesCount = _reservesCount; require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED); bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset; if (!reserveAlreadyAdded) { _reserves[asset].id = uint8(reservesCount); _reservesList[reservesCount] = asset; _reservesCount = reservesCount + 1; } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IExchangeAdapter { event Exchange( address indexed from, address indexed to, address indexed platform, uint256 fromAmount, uint256 toAmount ); function approveExchange(IERC20[] calldata tokens) external; function exchange( address from, address to, uint256 amount, uint256 maxSlippage ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableDelegationERC20 is ERC20 { address public delegatee; constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokensp * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(msg.sender, value); return true; } function delegate(address delegateeAddress) external { delegatee = delegateeAddress; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; contract MockUniswapV2Router02 is IUniswapV2Router02 { mapping(address => uint256) internal _amountToReturn; mapping(address => uint256) internal _amountToSwap; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsIn; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsOut; uint256 internal defaultMockValue; function setAmountToReturn(address reserve, uint256 amount) public { _amountToReturn[reserve] = amount; } function setAmountToSwap(address reserve, uint256 amount) public { _amountToSwap[reserve] = amount; } function swapExactTokensForTokens( uint256 amountIn, uint256, /* amountOutMin */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn); MintableERC20(path[1]).mint(_amountToReturn[path[0]]); IERC20(path[1]).transfer(to, _amountToReturn[path[0]]); amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountToReturn[path[0]]; } function swapTokensForExactTokens( uint256 amountOut, uint256, /* amountInMax */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), _amountToSwap[path[0]]); MintableERC20(path[1]).mint(amountOut); IERC20(path[1]).transfer(to, amountOut); amounts = new uint256[](path.length); amounts[0] = _amountToSwap[path[0]]; amounts[1] = amountOut; } function setAmountOut( uint256 amountIn, address reserveIn, address reserveOut, uint256 amountOut ) public { _amountsOut[reserveIn][reserveOut][amountIn] = amountOut; } function setAmountIn( uint256 amountOut, address reserveIn, address reserveOut, uint256 amountIn ) public { _amountsIn[reserveIn][reserveOut][amountOut] = amountIn; } function setDefaultMockValue(uint256 value) public { defaultMockValue = value; } function getAmountsOut(uint256 amountIn, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountsOut[path[0]][path[1]][amountIn] > 0 ? _amountsOut[path[0]][path[1]][amountIn] : defaultMockValue; return amounts; } function getAmountsIn(uint256 amountOut, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = _amountsIn[path[0]][path[1]][amountOut] > 0 ? _amountsIn[path[0]][path[1]][amountOut] : defaultMockValue; amounts[1] = amountOut; return amounts; } } // 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: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract UniswapLiquiditySwapAdapter is BaseUniswapAdapter { struct PermitParams { uint256[] amount; uint256[] deadline; uint8[] v; bytes32[] r; bytes32[] s; } struct SwapParams { address[] assetToSwapToList; uint256[] minAmountsToReceive; bool[] swapAllBalance; PermitParams permitParams; bool[] useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Swaps the received reserve amount from the flash loan into the asset specified in the params. * The received funds from the swap are then deposited into the protocol on behalf of the user. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * repay the flash loan. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); SwapParams memory decodedParams = _decodeParams(params); require( assets.length == decodedParams.assetToSwapToList.length && assets.length == decodedParams.minAmountsToReceive.length && assets.length == decodedParams.swapAllBalance.length && assets.length == decodedParams.permitParams.amount.length && assets.length == decodedParams.permitParams.deadline.length && assets.length == decodedParams.permitParams.v.length && assets.length == decodedParams.permitParams.r.length && assets.length == decodedParams.permitParams.s.length && assets.length == decodedParams.useEthPath.length, 'INCONSISTENT_PARAMS' ); for (uint256 i = 0; i < assets.length; i++) { _swapLiquidity( assets[i], decodedParams.assetToSwapToList[i], amounts[i], premiums[i], initiator, decodedParams.minAmountsToReceive[i], decodedParams.swapAllBalance[i], PermitSignature( decodedParams.permitParams.amount[i], decodedParams.permitParams.deadline[i], decodedParams.permitParams.v[i], decodedParams.permitParams.r[i], decodedParams.permitParams.s[i] ), decodedParams.useEthPath[i] ); } return true; } struct SwapAndDepositLocalVars { uint256 i; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; address aToken; } /** * @dev Swaps an amount of an asset to another and deposits the new asset amount on behalf of the user without using * a flash loan. This method can be used when the temporary transfer of the collateral asset to this contract * does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * perform the swap. * @param assetToSwapFromList List of addresses of the underlying asset to be swap from * @param assetToSwapToList List of addresses of the underlying asset to be swap to and deposited * @param amountToSwapList List of amounts to be swapped. If the amount exceeds the balance, the total balance is used for the swap * @param minAmountsToReceive List of min amounts to be received from the swap * @param permitParams List of struct containing the permit signatures * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v param for the permit signature * bytes32 r param for the permit signature * bytes32 s param for the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ function swapAndDeposit( address[] calldata assetToSwapFromList, address[] calldata assetToSwapToList, uint256[] calldata amountToSwapList, uint256[] calldata minAmountsToReceive, PermitSignature[] calldata permitParams, bool[] calldata useEthPath ) external { require( assetToSwapFromList.length == assetToSwapToList.length && assetToSwapFromList.length == amountToSwapList.length && assetToSwapFromList.length == minAmountsToReceive.length && assetToSwapFromList.length == permitParams.length, 'INCONSISTENT_PARAMS' ); SwapAndDepositLocalVars memory vars; for (vars.i = 0; vars.i < assetToSwapFromList.length; vars.i++) { vars.aToken = _getReserveData(assetToSwapFromList[vars.i]).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(msg.sender); vars.amountToSwap = amountToSwapList[vars.i] > vars.aTokenInitiatorBalance ? vars.aTokenInitiatorBalance : amountToSwapList[vars.i]; _pullAToken( assetToSwapFromList[vars.i], vars.aToken, msg.sender, vars.amountToSwap, permitParams[vars.i] ); vars.receivedAmount = _swapExactTokensForTokens( assetToSwapFromList[vars.i], assetToSwapToList[vars.i], vars.amountToSwap, minAmountsToReceive[vars.i], useEthPath[vars.i] ); // Deposit new reserve IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), 0); IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetToSwapToList[vars.i], vars.receivedAmount, msg.sender, 0); } } /** * @dev Swaps an `amountToSwap` of an asset to another and deposits the funds on behalf of the initiator. * @param assetFrom Address of the underlying asset to be swap from * @param assetTo Address of the underlying asset to be swap to and deposited * @param amount Amount from flash loan * @param premium Premium of the flash loan * @param minAmountToReceive Min amount to be received from the swap * @param swapAllBalance Flag indicating if all the user balance should be swapped * @param permitSignature List of struct containing the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ struct SwapLiquidityLocalVars { address aToken; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; uint256 flashLoanDebt; uint256 amountToPull; } function _swapLiquidity( address assetFrom, address assetTo, uint256 amount, uint256 premium, address initiator, uint256 minAmountToReceive, bool swapAllBalance, PermitSignature memory permitSignature, bool useEthPath ) internal { SwapLiquidityLocalVars memory vars; vars.aToken = _getReserveData(assetFrom).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(initiator); vars.amountToSwap = swapAllBalance && vars.aTokenInitiatorBalance.sub(premium) <= amount ? vars.aTokenInitiatorBalance.sub(premium) : amount; vars.receivedAmount = _swapExactTokensForTokens( assetFrom, assetTo, vars.amountToSwap, minAmountToReceive, useEthPath ); // Deposit new reserve IERC20(assetTo).safeApprove(address(LENDING_POOL), 0); IERC20(assetTo).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetTo, vars.receivedAmount, initiator, 0); vars.flashLoanDebt = amount.add(premium); vars.amountToPull = vars.amountToSwap.add(premium); _pullAToken(assetFrom, vars.aToken, initiator, vars.amountToPull, permitSignature); // Repay flash loan IERC20(assetFrom).safeApprove(address(LENDING_POOL), 0); IERC20(assetFrom).safeApprove(address(LENDING_POOL), vars.flashLoanDebt); } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature * bool[] useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @return SwapParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (SwapParams memory) { ( address[] memory assetToSwapToList, uint256[] memory minAmountsToReceive, bool[] memory swapAllBalance, uint256[] memory permitAmount, uint256[] memory deadline, uint8[] memory v, bytes32[] memory r, bytes32[] memory s, bool[] memory useEthPath ) = abi.decode( params, (address[], uint256[], bool[], uint256[], uint256[], uint8[], bytes32[], bytes32[], bool[]) ); return SwapParams( assetToSwapToList, minAmountsToReceive, swapAllBalance, PermitParams(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract FlashLiquidationAdapter is BaseUniswapAdapter { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationParams { address collateralAsset; address borrowedAsset; address user; uint256 debtToCover; bool useEthPath; } struct LiquidationCallLocalVars { uint256 initFlashBorrowedBalance; uint256 diffFlashBorrowedBalance; uint256 initCollateralBalance; uint256 diffCollateralBalance; uint256 flashLoanDebt; uint256 soldAmount; uint256 remainingTokens; uint256 borrowedAssetLeftovers; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Liquidate a non-healthy position collateral-wise, with a Health Factor below 1, using Flash Loan and Uniswap to repay flash loan premium. * - The caller (liquidator) with a flash loan covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk minus the flash loan premium. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the caller * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * address borrowedAsset The asset that must be covered * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); LiquidationParams memory decodedParams = _decodeParams(params); require(assets.length == 1 && assets[0] == decodedParams.borrowedAsset, 'INCONSISTENT_PARAMS'); _liquidateAndSwap( decodedParams.collateralAsset, decodedParams.borrowedAsset, decodedParams.user, decodedParams.debtToCover, decodedParams.useEthPath, amounts[0], premiums[0], initiator ); return true; } /** * @dev * @param collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * @param borrowedAsset The asset that must be covered * @param user The user address with a Health Factor below 1 * @param debtToCover The amount of debt to coverage, can be max(-1) to liquidate all possible debt * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @param flashBorrowedAmount Amount of asset requested at the flash loan to liquidate the user position * @param premium Fee of the requested flash loan * @param initiator Address of the caller */ function _liquidateAndSwap( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath, uint256 flashBorrowedAmount, uint256 premium, address initiator ) internal { LiquidationCallLocalVars memory vars; vars.initCollateralBalance = IERC20(collateralAsset).balanceOf(address(this)); if (collateralAsset != borrowedAsset) { vars.initFlashBorrowedBalance = IERC20(borrowedAsset).balanceOf(address(this)); // Track leftover balance to rescue funds in case of external transfers into this contract vars.borrowedAssetLeftovers = vars.initFlashBorrowedBalance.sub(flashBorrowedAmount); } vars.flashLoanDebt = flashBorrowedAmount.add(premium); // Approve LendingPool to use debt token for liquidation IERC20(borrowedAsset).approve(address(LENDING_POOL), debtToCover); // Liquidate the user position and release the underlying collateral LENDING_POOL.liquidationCall(collateralAsset, borrowedAsset, user, debtToCover, false); // Discover the liquidated tokens uint256 collateralBalanceAfter = IERC20(collateralAsset).balanceOf(address(this)); // Track only collateral released, not current asset balance of the contract vars.diffCollateralBalance = collateralBalanceAfter.sub(vars.initCollateralBalance); if (collateralAsset != borrowedAsset) { // Discover flash loan balance after the liquidation uint256 flashBorrowedAssetAfter = IERC20(borrowedAsset).balanceOf(address(this)); // Use only flash loan borrowed assets, not current asset balance of the contract vars.diffFlashBorrowedBalance = flashBorrowedAssetAfter.sub(vars.borrowedAssetLeftovers); // Swap released collateral into the debt asset, to repay the flash loan vars.soldAmount = _swapTokensForExactTokens( collateralAsset, borrowedAsset, vars.diffCollateralBalance, vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance), useEthPath ); vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount); } else { vars.remainingTokens = vars.diffCollateralBalance.sub(premium); } // Allow repay of flash loan IERC20(borrowedAsset).approve(address(LENDING_POOL), vars.flashLoanDebt); // Transfer remaining tokens to initiator if (vars.remainingTokens > 0) { IERC20(collateralAsset).transfer(initiator, vars.remainingTokens); } } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to claim * address borrowedAsset The asset that must be covered and will be exchanged to pay the flash loan premium * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap * @return LiquidationParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (LiquidationParams memory) { ( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath ) = abi.decode(params, (address, address, address, uint256, bool)); return LiquidationParams(collateralAsset, borrowedAsset, user, debtToCover, useEthPath); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param logic address of the initial implementation. * @param admin Address of the proxy administrator. * @param data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize( address logic, address admin, bytes memory data ) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(logic, data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), 'Cannot change the admin of a proxy to the zero address'); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor( address _logic, address _admin, bytes memory _data ) public payable UpgradeabilityProxy(_logic, _data) { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; // Prettier ignore to prevent buidler flatter bug // prettier-ignore import {InitializableImmutableAdminUpgradeabilityProxy} from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider { string private _marketId; mapping(bytes32 => address) private _addresses; bytes32 private constant LENDING_POOL = 'LENDING_POOL'; bytes32 private constant LENDING_POOL_CONFIGURATOR = 'LENDING_POOL_CONFIGURATOR'; bytes32 private constant POOL_ADMIN = 'POOL_ADMIN'; bytes32 private constant EMERGENCY_ADMIN = 'EMERGENCY_ADMIN'; bytes32 private constant LENDING_POOL_COLLATERAL_MANAGER = 'COLLATERAL_MANAGER'; bytes32 private constant PRICE_ORACLE = 'PRICE_ORACLE'; bytes32 private constant LENDING_RATE_ORACLE = 'LENDING_RATE_ORACLE'; constructor(string memory marketId) public { _setMarketId(marketId); } /** * @dev Returns the id of the Aave market to which this contracts points to * @return The market id **/ function getMarketId() external view override returns (string memory) { return _marketId; } /** * @dev Allows to set the market which this LendingPoolAddressesProvider represents * @param marketId The market id */ function setMarketId(string memory marketId) external override onlyOwner { _setMarketId(marketId); } /** * @dev General function to update the implementation of a proxy registered with * certain `id`. If there is no proxy registered, it will instantiate one and * set as implementation the `implementationAddress` * IMPORTANT Use this function carefully, only for ids that don't have an explicit * setter function, in order to avoid unexpected consequences * @param id The id * @param implementationAddress The address of the new implementation */ function setAddressAsProxy(bytes32 id, address implementationAddress) external override onlyOwner { _updateImpl(id, implementationAddress); emit AddressSet(id, implementationAddress, true); } /** * @dev Sets an address for an id replacing the address saved in the addresses map * IMPORTANT Use this function carefully, as it will do a hard replacement * @param id The id * @param newAddress The address to set */ function setAddress(bytes32 id, address newAddress) external override onlyOwner { _addresses[id] = newAddress; emit AddressSet(id, newAddress, false); } /** * @dev Returns an address by id * @return The address */ function getAddress(bytes32 id) public view override returns (address) { return _addresses[id]; } /** * @dev Returns the address of the LendingPool proxy * @return The LendingPool proxy address **/ function getLendingPool() external view override returns (address) { return getAddress(LENDING_POOL); } /** * @dev Updates the implementation of the LendingPool, or creates the proxy * setting the new `pool` implementation on the first time calling it * @param pool The new LendingPool implementation **/ function setLendingPoolImpl(address pool) external override onlyOwner { _updateImpl(LENDING_POOL, pool); emit LendingPoolUpdated(pool); } /** * @dev Returns the address of the LendingPoolConfigurator proxy * @return The LendingPoolConfigurator proxy address **/ function getLendingPoolConfigurator() external view override returns (address) { return getAddress(LENDING_POOL_CONFIGURATOR); } /** * @dev Updates the implementation of the LendingPoolConfigurator, or creates the proxy * setting the new `configurator` implementation on the first time calling it * @param configurator The new LendingPoolConfigurator implementation **/ function setLendingPoolConfiguratorImpl(address configurator) external override onlyOwner { _updateImpl(LENDING_POOL_CONFIGURATOR, configurator); emit LendingPoolConfiguratorUpdated(configurator); } /** * @dev Returns the address of the LendingPoolCollateralManager. Since the manager is used * through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence * the addresses are changed directly * @return The address of the LendingPoolCollateralManager **/ function getLendingPoolCollateralManager() external view override returns (address) { return getAddress(LENDING_POOL_COLLATERAL_MANAGER); } /** * @dev Updates the address of the LendingPoolCollateralManager * @param manager The new LendingPoolCollateralManager address **/ function setLendingPoolCollateralManager(address manager) external override onlyOwner { _addresses[LENDING_POOL_COLLATERAL_MANAGER] = manager; emit LendingPoolCollateralManagerUpdated(manager); } /** * @dev The functions below are getters/setters of addresses that are outside the context * of the protocol hence the upgradable proxy pattern is not used **/ function getPoolAdmin() external view override returns (address) { return getAddress(POOL_ADMIN); } function setPoolAdmin(address admin) external override onlyOwner { _addresses[POOL_ADMIN] = admin; emit ConfigurationAdminUpdated(admin); } function getEmergencyAdmin() external view override returns (address) { return getAddress(EMERGENCY_ADMIN); } function setEmergencyAdmin(address emergencyAdmin) external override onlyOwner { _addresses[EMERGENCY_ADMIN] = emergencyAdmin; emit EmergencyAdminUpdated(emergencyAdmin); } function getPriceOracle() external view override returns (address) { return getAddress(PRICE_ORACLE); } function setPriceOracle(address priceOracle) external override onlyOwner { _addresses[PRICE_ORACLE] = priceOracle; emit PriceOracleUpdated(priceOracle); } function getLendingRateOracle() external view override returns (address) { return getAddress(LENDING_RATE_ORACLE); } function setLendingRateOracle(address lendingRateOracle) external override onlyOwner { _addresses[LENDING_RATE_ORACLE] = lendingRateOracle; emit LendingRateOracleUpdated(lendingRateOracle); } /** * @dev Internal function to update the implementation of a specific proxied component of the protocol * - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress` * as implementation and calls the initialize() function on the proxy * - If there is already a proxy registered, it just updates the implementation to `newAddress` and * calls the initialize() function via upgradeToAndCall() in the proxy * @param id The id of the proxy to be updated * @param newAddress The address of the new implementation **/ function _updateImpl(bytes32 id, address newAddress) internal { address payable proxyAddress = payable(_addresses[id]); InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature('initialize(address)', address(this)); if (proxyAddress == address(0)) { proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(newAddress, params); _addresses[id] = address(proxy); emit ProxyCreated(id, address(proxy)); } else { proxy.upgradeToAndCall(newAddress, params); } } function _setMarketId(string memory marketId) internal { _marketId = marketId; emit MarketIdSet(marketId); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {LendingPool} from '../protocol/lendingpool/LendingPool.sol'; import { LendingPoolAddressesProvider } from '../protocol/configuration/LendingPoolAddressesProvider.sol'; import {LendingPoolConfigurator} from '../protocol/lendingpool/LendingPoolConfigurator.sol'; import {AToken} from '../protocol/tokenization/AToken.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract ATokensAndRatesHelper is Ownable { address payable private pool; address private addressesProvider; address private poolConfigurator; event deployedContracts(address aToken, address strategy); struct InitDeploymentInput { address asset; uint256[6] rates; } struct ConfigureReserveInput { address asset; uint256 baseLTV; uint256 liquidationThreshold; uint256 liquidationBonus; uint256 reserveFactor; bool stableBorrowingEnabled; } constructor( address payable _pool, address _addressesProvider, address _poolConfigurator ) public { pool = _pool; addressesProvider = _addressesProvider; poolConfigurator = _poolConfigurator; } function initDeployment(InitDeploymentInput[] calldata inputParams) external onlyOwner { for (uint256 i = 0; i < inputParams.length; i++) { emit deployedContracts( address(new AToken()), address( new DefaultReserveInterestRateStrategy( LendingPoolAddressesProvider(addressesProvider), inputParams[i].rates[0], inputParams[i].rates[1], inputParams[i].rates[2], inputParams[i].rates[3], inputParams[i].rates[4], inputParams[i].rates[5] ) ) ); } } function configureReserves(ConfigureReserveInput[] calldata inputParams) external onlyOwner { LendingPoolConfigurator configurator = LendingPoolConfigurator(poolConfigurator); for (uint256 i = 0; i < inputParams.length; i++) { configurator.configureReserveAsCollateral( inputParams[i].asset, inputParams[i].baseLTV, inputParams[i].liquidationThreshold, inputParams[i].liquidationBonus ); configurator.enableBorrowingOnReserve( inputParams[i].asset, inputParams[i].stableBorrowingEnabled ); configurator.setReserveFactor(inputParams[i].asset, inputParams[i].reserveFactor); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library StringLib { function concat(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {StableDebtToken} from '../protocol/tokenization/StableDebtToken.sol'; import {VariableDebtToken} from '../protocol/tokenization/VariableDebtToken.sol'; import {LendingRateOracle} from '../mocks/oracle/LendingRateOracle.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract StableAndVariableTokensHelper is Ownable { address payable private pool; address private addressesProvider; event deployedContracts(address stableToken, address variableToken); constructor(address payable _pool, address _addressesProvider) public { pool = _pool; addressesProvider = _addressesProvider; } function initDeployment(address[] calldata tokens, string[] calldata symbols) external onlyOwner { require(tokens.length == symbols.length, 'Arrays not same length'); require(pool != address(0), 'Pool can not be zero address'); for (uint256 i = 0; i < tokens.length; i++) { emit deployedContracts(address(new StableDebtToken()), address(new VariableDebtToken())); } } function setOracleBorrowRates( address[] calldata assets, uint256[] calldata rates, address oracle ) external onlyOwner { require(assets.length == rates.length, 'Arrays not same length'); for (uint256 i = 0; i < assets.length; i++) { // LendingRateOracle owner must be this contract LendingRateOracle(oracle).setMarketBorrowRate(assets[i], rates[i]); } } function setOracleOwnership(address oracle, address admin) external onlyOwner { require(admin != address(0), 'owner can not be zero'); require(LendingRateOracle(oracle).owner() == address(this), 'helper is not owner'); LendingRateOracle(oracle).transferOwnership(admin); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; contract LendingRateOracle is ILendingRateOracle, Ownable { mapping(address => uint256) borrowRates; mapping(address => uint256) liquidityRates; function getMarketBorrowRate(address _asset) external view override returns (uint256) { return borrowRates[_asset]; } function setMarketBorrowRate(address _asset, uint256 _rate) external override onlyOwner { borrowRates[_asset] = _rate; } function getMarketLiquidityRate(address _asset) external view returns (uint256) { return liquidityRates[_asset]; } function setMarketLiquidityRate(address _asset, uint256 _rate) external onlyOwner { liquidityRates[_asset] = _rate; } }
* @dev Validates the action of setting an asset as collateral @param reserve The state of the reserve that the user is enabling or disabling as collateral @param reserveAddress The address of the reserve @param reservesData The data of all the reserves @param userConfig The state of the user for the specific reserve @param reserves The addresses of all the active reserves @param oracle The price oracle/
function validateSetUseReserveAsCollateral( DataTypes.ReserveData storage reserve, address reserveAddress, bool useAsCollateral, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender); require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0); require( useAsCollateral || GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, underlyingBalance, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_DEPOSIT_ALREADY_IN_USE ); }
68,333
[ 1, 9594, 326, 1301, 434, 3637, 392, 3310, 487, 4508, 2045, 287, 225, 20501, 1021, 919, 434, 326, 20501, 716, 326, 729, 353, 570, 17912, 578, 1015, 17912, 487, 4508, 2045, 287, 225, 20501, 1887, 1021, 1758, 434, 326, 20501, 225, 400, 264, 3324, 751, 1021, 501, 434, 777, 326, 400, 264, 3324, 225, 729, 809, 1021, 919, 434, 326, 729, 364, 326, 2923, 20501, 225, 400, 264, 3324, 1021, 6138, 434, 777, 326, 2695, 400, 264, 3324, 225, 20865, 1021, 6205, 20865, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 1954, 694, 3727, 607, 6527, 1463, 13535, 2045, 287, 12, 203, 565, 1910, 2016, 18, 607, 6527, 751, 2502, 20501, 16, 203, 565, 1758, 20501, 1887, 16, 203, 565, 1426, 999, 1463, 13535, 2045, 287, 16, 203, 565, 2874, 12, 2867, 516, 1910, 2016, 18, 607, 6527, 751, 13, 2502, 400, 264, 3324, 751, 16, 203, 565, 1910, 2016, 18, 1299, 1750, 863, 2502, 729, 809, 16, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 2502, 400, 264, 3324, 16, 203, 565, 2254, 5034, 400, 264, 3324, 1380, 16, 203, 565, 1758, 20865, 203, 225, 262, 3903, 1476, 288, 203, 565, 2254, 5034, 6808, 13937, 273, 467, 654, 39, 3462, 12, 455, 6527, 18, 69, 1345, 1887, 2934, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 203, 565, 2583, 12, 9341, 6291, 13937, 405, 374, 16, 9372, 18, 58, 48, 67, 31625, 7076, 1360, 67, 38, 1013, 4722, 67, 4400, 67, 43, 18857, 67, 22408, 67, 20, 1769, 203, 203, 565, 2583, 12, 203, 1377, 999, 1463, 13535, 2045, 287, 747, 203, 3639, 7928, 20556, 18, 12296, 23326, 448, 5042, 12, 203, 1850, 20501, 1887, 16, 203, 1850, 1234, 18, 15330, 16, 203, 1850, 6808, 13937, 16, 203, 1850, 400, 264, 3324, 751, 16, 203, 1850, 729, 809, 16, 203, 1850, 400, 264, 3324, 16, 203, 1850, 400, 264, 3324, 1380, 16, 203, 1850, 20865, 203, 3639, 262, 16, 203, 1377, 9372, 18, 58, 48, 67, 1639, 28284, 67, 1013, 20305, 67, 706, 67, 8001, 203, 565, 11272, 203, 225, 289, 2 ]
pragma solidity 0.5.17; import "./UpgradeableProxy.sol"; /** * @author Quant Network * @title TreasuryAbstract * @dev Sets the main variables of a Treasury contract and allows other contracts to easily interface with a Treasury contract without knowing the whole code. */ contract TreasuryBase is UpgradeableProxy { // the connected factory of this treasury bytes constant private treasurysFactory1 = '1.treasurysFactory'; // the connected rulelist of this treasury bytes constant private treasurysRuleList1 = '1.treasurysRuleList'; // the treasury's escrowed deposit bytes constant private treasurysDeposit1 = '1.treasuryDeposit'; // the QNT address of this treasury (possible cold wallet) bytes constant private QNTAddress1 = '1.QNTAddress'; // the operator address of this treasury, which can call other smart contract functions on behalf of the treasury bytes constant private operatorAddress1 = '1.operatorAddress'; // whether this treasury is currently paused (true) or active (false) bytes constant private circuitBreakerOn1 = '1.circuitBreakerOn'; // the fee the MAPP has to pay for any dispute raised per gateway bytes constant private mappDisputeFeeMultipler1 = '1.mappDisputeFeeMultipler'; // the commission divider charged for every mapp to gateway transaction. // The divider is used with the original fee of the function. // I.e a commission divider of 2 is equal to 50% commission bytes constant private commissionDivider1 = '1.commissionDivider'; // the penalty multiplier the treasury has to pay if it has been found in breach of // one of its verification rules. The mulitipication is used with the original fee of the function. // I.e. a treasuryPenalty of 10 is equal to a 10x penalty bytes constant private treasuryPenaltyMultipler1 = '1.treasuryPenaltyMultipler'; // the penalty multiplier a gateway has to pay if it has be found in breach of // one of its verification rules. The mulitipication is used with the original fee of the function // I.e. a gatewayPenalty of 5 is equal to a 5x penalty. bytes constant private gatewayPenaltyMultipler1 = '1.gatewayPenaltyMultipler'; /** * set a new factory for this treasury */ function treasurysFactory(address newTreasurysFactory) internal { addressStorage[keccak256(treasurysFactory1)] = newTreasurysFactory; } /** * set a new rulelist for this treasury */ function treasurysRuleList(address newTreasurysRuleList) internal { addressStorage[keccak256(treasurysRuleList1)] = newTreasurysRuleList; } /** * set a new treasury deposit */ function treasurysDeposit(address newTreasuryDeposit) internal { addressStorage[keccak256(treasurysDeposit1)] = newTreasuryDeposit; } /** * set a new QNTAddress for this treasury */ function QNTAddress(address newQNTAddress) internal { addressStorage[keccak256(QNTAddress1)] = newQNTAddress; } /** * set a new operator for this treasury */ function operatorAddress(address newOperator) internal { addressStorage[keccak256(operatorAddress1)] = newOperator; } /** * set the circuitbreaker of this treasury */ function circuitBreakerOn(bool newCircuitBreakerOn) internal { boolStorage[keccak256(circuitBreakerOn1)] = newCircuitBreakerOn; } /** * set the mapp dispute fee multiplier */ function mappDisputeFeeMultipler(uint16 newMappDisputeFeeMultipler) internal { uint16Storage[keccak256(mappDisputeFeeMultipler1)] = newMappDisputeFeeMultipler; } /** * set the commission divider */ function commissionDivider(uint16 neCommissionDivider) internal { uint16Storage[keccak256(commissionDivider1)] = neCommissionDivider; } /** * set the treasury dispute multiplier */ function treasuryPenaltyMultipler(uint16 newTreasuryPenaltyMultipler) internal { uint16Storage[keccak256(treasuryPenaltyMultipler1)] = newTreasuryPenaltyMultipler; } /** * set the gateway dispute multiplier */ function gatewayPenaltyMultipler(uint16 newGatewayPenaltyMultipler) internal { uint16Storage[keccak256(gatewayPenaltyMultipler1)] = newGatewayPenaltyMultipler; } /** * @return - the admin of the proxy. Only the admin address can upgrade the smart contract logic */ function admin() public view returns (address) { return addressStorage[keccak256('proxy.admin')]; } /** * @return - the number of hours wait time for any critical update */ function speedBumpHours() public view returns (uint16){ return uint16Storage[keccak256('proxy.speedBumpHours')]; } /** * @return - the connected factory of this treasury */ function treasurysFactory() public view returns (address){ return addressStorage[keccak256(treasurysFactory1)]; } /** * @return - the connected rulelist of this treasury */ function treasurysRuleList() public view returns (address){ return addressStorage[keccak256(treasurysRuleList1)]; } /** * @return - the treasury's escrowed deposit */ function treasurysDeposit() public view returns (address){ return addressStorage[keccak256(treasurysDeposit1)]; } /** * @return - the withdrawal address of this treasury */ function QNTAddress() public view returns (address){ return addressStorage[keccak256(QNTAddress1)]; } /** * @return - the operator of this treasury */ function operatorAddress() public view returns (address){ return addressStorage[keccak256(operatorAddress1)]; } /** * @return - whether this treasury is currently active or not */ function circuitBreakerOn() public view returns (bool){ return boolStorage[keccak256(circuitBreakerOn1)]; } /** * @return - the fee the mapp has to pay for any dispute raised per gateway */ function mappDisputeFeeMultipler() public view returns (uint16){ return uint16Storage[keccak256(mappDisputeFeeMultipler1)]; } /** * @return the commission divider charged for every mapp to gateway transaction. * The divider is used with the original fee of the function. * I.e a commission divider of 2 is equal to 50% commission */ function commissionDivider() public view returns (uint16){ return uint16Storage[keccak256(commissionDivider1)]; } /** * @return - the penalty multiplier for the treasury has to pay if it has been found in breach of * one of its verification rules. The mulitipication is used with the original fee of the function. * I.e. a treasuryPenalty of 10 is equal to a 10x penalty */ function treasuryPenaltyMultipler() public view returns (uint16){ return uint16Storage[keccak256(treasuryPenaltyMultipler1)]; } /** * @return - the penalty multiplier a gateway has to pay if it has be found in breach of * one of its verification rules. The mulitipication is used with the original fee of the function * I.e. a gatewayPenalty of 5 is equal to a 5x penalty. */ function gatewayPenaltyMultipler() public view returns (uint16){ return uint16Storage[keccak256(gatewayPenaltyMultipler1)]; } }
* @return - the penalty multiplier a gateway has to pay if it has be found in breach of one of its verification rules. The mulitipication is used with the original fee of the function I.e. a gatewayPenalty of 5 is equal to a 5x penalty./
function gatewayPenaltyMultipler() public view returns (uint16){ return uint16Storage[keccak256(gatewayPenaltyMultipler1)]; }
6,477,594
[ 1, 2463, 300, 326, 23862, 15027, 279, 6878, 711, 358, 8843, 309, 518, 711, 506, 1392, 316, 324, 12974, 434, 1245, 434, 2097, 11805, 2931, 18, 1021, 14064, 305, 625, 829, 353, 1399, 598, 326, 2282, 14036, 434, 326, 445, 467, 18, 73, 18, 279, 6878, 24251, 15006, 434, 1381, 353, 3959, 358, 279, 1381, 92, 23862, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 6878, 24251, 15006, 5002, 20728, 1435, 1071, 1476, 1135, 261, 11890, 2313, 15329, 203, 5411, 327, 2254, 2313, 3245, 63, 79, 24410, 581, 5034, 12, 11127, 24251, 15006, 5002, 20728, 21, 13, 15533, 203, 3639, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x21517abae577dDC59Ac6945C501F36AF085d97A7/sources/contracts/CrowdFunding.sol
global variable which at the start would be set to 0, as we want to keep the track of the campaigns so it would be kept 0
uint256 public numberOfCampaigns = 0;
1,856,058
[ 1, 6347, 2190, 1492, 622, 326, 787, 4102, 506, 444, 358, 374, 16, 487, 732, 2545, 358, 3455, 326, 3298, 434, 326, 8965, 87, 1427, 518, 4102, 506, 16555, 374, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 11890, 5034, 1071, 7922, 13432, 87, 273, 374, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xA9f3bCD35380d5eA4431D25adC8Fd8A85B5ABA52/sources/contracts/GetVotedToEarn.sol
for testing purpose
function getOneContestCreatorAddressNoRule(uint256 _contestId) public view returns (address,address,address) {
5,616,911
[ 1, 1884, 7769, 13115, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 20863, 660, 395, 10636, 1887, 2279, 2175, 12, 11890, 5034, 389, 1213, 395, 548, 13, 1071, 1476, 1135, 261, 2867, 16, 2867, 16, 2867, 13, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; contract MineAuction { event Bid(address bidder, uint amount, uint charType, uint tokenId); IERC20 public acceptableToken; IERC721 public mms2; IERC721 public mms1; IERC721 public hero; uint public phrase; // 1 - started/free bid, 2 - bid then extend uint public phraseOneEndAt; // when will the free bid end uint public endedAt; // when will the limited time bid end bool public ended; // note: flag to indicate if auction is ended, might not be valid if no one trigger its change via bidding address public highestBidder; // bid winner address public owner; address public target; // final address where bidding fund will be transferred to uint public highestBid; uint public bidInc; // bidding amount increment uint public tokenId; // which char will get entry fee, used with charType, 1: hero, 2: mms1, 3: mms2 uint public charType; uint public phraseOneDelay; uint public phraseTwoDelay; uint public round; constructor(address _a, address _h, address _m1, address _m2, uint _startingBid, uint _bidInc) { owner = msg.sender; acceptableToken = IERC20(_a); hero = IERC721(_h); mms1 = IERC721(_m1); mms2 = IERC721(_m2); highestBid = _startingBid * 10 ** 18; bidInc = _bidInc * 10 ** 18; // note: for testnet only phraseOneDelay = 48 hours; phraseTwoDelay = 30 minutes; } modifier onlyOwner() { require(msg.sender == owner, "Not owner"); // Underscore is a special character only used inside // a function modifier and it tells Solidity to // execute the rest of the code. _; } modifier validAddress(address _addr) { require(_addr != address(0), "Not valid address"); _; } function bid(uint _charType, uint _tokenId, uint _amount) external { // note: tokenId could be changed between biddings _amount = _amount * 10 ** 18; require(ended == false, "auc ended - ended"); require(_amount >= highestBid + bidInc, "value < highest"); if (_charType == 3) { if (msg.sender != mms2.ownerOf(_tokenId)) { revert("wrong NFT owner"); } } else if (_charType == 2) { if (msg.sender != mms1.ownerOf(_tokenId)) { revert("wrong NFT owner"); } } else if (_charType == 1) { if (msg.sender != hero.ownerOf(_tokenId)) { revert("wrong NFT owner"); } } else { revert("wrong char type"); } if (phrase == 0) { // start and go into phrase 1 phrase = 1; phraseOneEndAt = block.timestamp + phraseOneDelay; } else if (phrase == 1) { if (block.timestamp > phraseOneEndAt) { if (block.timestamp <= phraseOneEndAt + phraseTwoDelay) { // if new bid time in oneendat and first twodelay, then enter 2 phrase phrase = 2; endedAt = block.timestamp + phraseTwoDelay; } else { // time beyond oneendat and first twodelay, then auction ends at phrase 1 ended = true; revert("auc ended - expired 1"); } } } else if (phrase == 2) { if (block.timestamp > endedAt) { ended = true; revert("auc ended - expired 2"); } endedAt = block.timestamp + phraseTwoDelay; } else { revert("illegal phrase"); } acceptableToken.transferFrom(msg.sender, address(this), _amount); // get this bid first if (highestBidder != address(0)) { acceptableToken.transfer(highestBidder, highestBid); // send back to last bidder if we have one } highestBidder = msg.sender; highestBid = _amount; tokenId = _tokenId; charType = _charType; round = round + 1; emit Bid(highestBidder, highestBid, charType, tokenId); } function isAuctionEnd() public view returns (bool) { // observer which can tell actual status of this auction if (phrase == 1) { if (block.timestamp > phraseOneEndAt + phraseTwoDelay) { return true; } } else if (phrase == 2) { if (block.timestamp > endedAt) { return true; } } return false; } function setTarget(address _t) external onlyOwner validAddress(_t) { target = _t; } function changeTokenId(uint _charType, uint _tokenId) external onlyOwner { charType = _charType; tokenId = _tokenId; } function withdraw() external onlyOwner { require(target != address(0), "invalid target"); require(isAuctionEnd(), "auc not ended"); acceptableToken.transfer(target, highestBid); } } interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom( address sender, address recipient, uint amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface IERC721 is IERC165 { function balanceOf(address owner) external view returns (uint balance); function ownerOf(uint tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint tokenId ) external; function safeTransferFrom( address from, address to, uint tokenId, bytes calldata data ) external; function transferFrom( address from, address to, uint tokenId ) external; function approve(address to, uint tokenId) external; function getApproved(uint tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); }
time beyond oneendat and first twodelay, then auction ends at phrase 1
} else {
15,882,880
[ 1, 957, 17940, 1245, 409, 270, 471, 1122, 2339, 1009, 528, 16, 1508, 279, 4062, 3930, 622, 13045, 404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 289, 469, 288, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; import "wafr/Test.sol"; import "utils/MiniMeToken.sol"; contract TokenUser { MiniMeToken token; function () public payable {} function TokenUser(address _token) public { token = MiniMeToken(_token); } function transfer(address _to, uint256 _value) public returns (bool) { return token.transfer(_to, _value); } } contract MiniMeTokenTest is Test { MiniMeToken token; uint256 initGeneration = 5000; TokenUser user1; TokenUser user2; TokenUser user3; TokenUser user4; function setup() { token = new MiniMeToken( address(0), address(0), 0, "MiniMeToken", 8, "MMT", true); user1 = new TokenUser(address(token)); user2 = new TokenUser(address(token)); user3 = new TokenUser(address(token)); user4 = new TokenUser(address(token)); require(user1.send(100000000)); require(user2.send(100000000)); require(user3.send(100000000)); require(user4.send(100000000)); } function test_0_testGenerateTokens() { // test for balance assertEq(token.balanceOf(address(this)), 0); assertEq(token.balanceOfAt(address(this), block.number), 0); assertEq(token.balanceOfAtTime(address(this), block.timestamp), 0); assertEq(token.totalSupply(), 0); assertEq(token.totalSupplyAt(block.number), 0); assertEq(token.totalSupplyAt(block.timestamp), 0); // generate tokens assertEq(token.generateTokens(address(this), 5000), true); // test for balance assertEq(token.balanceOf(address(this)), initGeneration); assertEq(token.balanceOfAt(address(this), block.number), initGeneration); assertEq(token.balanceOfAtTime(address(this), block.timestamp), initGeneration); assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); // generate tokens assertEq(token.generateTokens(address(this), 5000), true); initGeneration += 5000; // test for balance assertEq(token.balanceOf(address(this)), initGeneration); assertEq(token.balanceOfAt(address(this), block.number), initGeneration); assertEq(token.balanceOfAtTime(address(this), block.timestamp), initGeneration); assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); // generate tokens assertEq(token.generateTokens(address(this), 5000), true); initGeneration += 5000; // test for balance assertEq(token.balanceOf(address(this)), initGeneration); assertEq(token.balanceOfAt(address(this), block.number), initGeneration); assertEq(token.balanceOfAtTime(address(this), block.timestamp), initGeneration); assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); } function test_1_generationAcrossBlocks_increaseBlocksBy100() { // generate tokens assertEq(token.generateTokens(address(this), 5000), true); initGeneration += 5000; // test for balance assertEq(token.balanceOf(address(this)), initGeneration); assertEq(token.balanceOfAt(address(this), block.number), initGeneration); assertEq(token.balanceOfAtTime(address(this), block.timestamp), initGeneration); assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); } function test_2_destroyTokens() { // generate tokens assertEq(token.destroyTokens(address(this), 5000), true); initGeneration -= 5000; // test for balance assertEq(token.balanceOf(address(this)), initGeneration); assertEq(token.balanceOfAt(address(this), block.number), initGeneration); assertEq(token.balanceOfAtTime(address(this), block.timestamp), initGeneration); assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); // generate tokens assertEq(token.destroyTokens(address(this), 5000), true); initGeneration -= 5000; // test for balance assertEq(token.balanceOf(address(this)), initGeneration); assertEq(token.balanceOfAt(address(this), block.number), initGeneration); assertEq(token.balanceOfAtTime(address(this), block.timestamp), initGeneration); assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); } function test_3_destoryTokensAccrossBlocks_increaseBlocksBy1000() { // generate tokens assertEq(token.destroyTokens(address(this), 300), true); initGeneration -= 300; // test for balance assertEq(token.balanceOf(address(this)), initGeneration); assertEq(token.balanceOfAt(address(this), block.number), initGeneration); assertEq(token.balanceOfAtTime(address(this), block.timestamp), initGeneration); assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); } function test_4_generateTokensAccrossBlocksAfterDestroy_increaseBlocksBy1000() { // generate tokens assertEq(token.generateTokens(address(this), 2340), true); initGeneration += 2340; // test for balance assertEq(token.balanceOf(address(this)), initGeneration); assertEq(token.balanceOfAt(address(this), block.number), initGeneration); assertEq(token.balanceOfAtTime(address(this), block.timestamp), initGeneration); assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); } function test_5_generateSecondAccountBalance_increaseBlocksBy1000() { address secondAccount = address(sha3("something")); uint secondAccountGen = 1000; // generate tokens assertEq(token.generateTokens(secondAccount, secondAccountGen), true); // test for balance assertEq(token.balanceOf(address(this)), initGeneration); assertEq(token.balanceOfAt(address(this), block.number), initGeneration); assertEq(token.balanceOfAtTime(address(this), block.timestamp), initGeneration); // up generation then do total supply initGeneration += secondAccountGen; // test total supply assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); // test for balance assertEq(token.balanceOf(secondAccount), secondAccountGen); assertEq(token.balanceOfAt(secondAccount, block.number), secondAccountGen); assertEq(token.balanceOfAtTime(secondAccount, block.timestamp), secondAccountGen); } function test_6_basicTransfer_increaseBlocksBy1000() { address thirdAccount = address(sha3("anotherAccount")); uint256 initThirdAccount = 0; // test for balance assertEq(token.balanceOf(thirdAccount), initThirdAccount); assertEq(token.balanceOfAt(thirdAccount, block.number), initThirdAccount); assertEq(token.balanceOfAtTime(thirdAccount, block.timestamp), initThirdAccount); // transfer from address(this) to third account assertEq(token.transfer(thirdAccount, 500), true); initThirdAccount += 500; // test for balance assertEq(token.balanceOf(thirdAccount), initThirdAccount); assertEq(token.balanceOfAt(thirdAccount, block.number), initThirdAccount); assertEq(token.balanceOfAtTime(thirdAccount, block.timestamp), initThirdAccount); // test total supply assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); } function test_8_basicTransfersBetweenAccounts_increaseBlocksBy300() { address user1Address = address(user1); address user2Address = address(user2); // test for balance assertEq(token.balanceOf(user1Address), 0); assertEq(token.balanceOfAt(user1Address, block.number), 0); assertEq(token.balanceOfAtTime(user1Address, block.timestamp), 0); // transfer from address(this) to third account assertEq(token.transfer(user1Address, 500), true); // test for balance assertEq(token.balanceOf(user1Address), 500); assertEq(token.balanceOfAt(user1Address, block.number), 500); assertEq(token.balanceOfAtTime(user1Address, block.timestamp), 500); // transfer from address(this) to third account assertEq(user1.transfer(user2Address, 500), true); // test for balance assertEq(token.balanceOf(user1Address), 0); assertEq(token.balanceOfAt(user1Address, block.number), 0); assertEq(token.balanceOfAtTime(user1Address, block.timestamp), 0); // test for balance assertEq(token.balanceOf(user2Address), 500); assertEq(token.balanceOfAt(user2Address, block.number), 500); assertEq(token.balanceOfAtTime(user2Address, block.timestamp), 500); // transfer from address(this) to third account assertEq(user2.transfer(user1Address, 500), true); // test for balance assertEq(token.balanceOf(user1Address), 500); assertEq(token.balanceOfAt(user1Address, block.number), 500); assertEq(token.balanceOfAtTime(user1Address, block.timestamp), 500); // test for balance assertEq(token.balanceOf(user2Address), 0); assertEq(token.balanceOfAt(user2Address, block.number), 0); assertEq(token.balanceOfAtTime(user2Address, block.timestamp), 0); // test total supply assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); } function test_9_checkDestructionOverflow_shouldThrow() { address user4Address = address(user4); assertEq(token.destroyTokens(user4Address, 500), true); } function test_9a_transferShouldBeFalse() { assertEq(user4.transfer(address(user1), 3290390390), false); // test total supply assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); } function test_9b_testGoodTransfer_thenInvalid() { assertEq(user1.transfer(address(user1), 2), true); assertEq(user1.transfer(address(user1), 23498243892349), false); // test total supply assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); } }
generate tokens test for balance
function test_4_generateTokensAccrossBlocksAfterDestroy_increaseBlocksBy1000() { assertEq(token.generateTokens(address(this), 2340), true); initGeneration += 2340; assertEq(token.balanceOf(address(this)), initGeneration); assertEq(token.balanceOfAt(address(this), block.number), initGeneration); assertEq(token.balanceOfAtTime(address(this), block.timestamp), initGeneration); assertEq(token.totalSupply(), initGeneration); assertEq(token.totalSupplyAt(block.number), initGeneration); assertEq(token.totalSupplyAt(block.timestamp), initGeneration); }
13,031,681
[ 1, 7163, 2430, 1842, 364, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 1842, 67, 24, 67, 7163, 5157, 8973, 3984, 6450, 4436, 10740, 67, 267, 11908, 6450, 858, 18088, 1435, 288, 203, 565, 1815, 19508, 12, 2316, 18, 7163, 5157, 12, 2867, 12, 2211, 3631, 576, 5026, 20, 3631, 638, 1769, 203, 203, 565, 1208, 13842, 1011, 576, 5026, 20, 31, 203, 203, 565, 1815, 19508, 12, 2316, 18, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 1208, 13842, 1769, 203, 565, 1815, 19508, 12, 2316, 18, 12296, 951, 861, 12, 2867, 12, 2211, 3631, 1203, 18, 2696, 3631, 1208, 13842, 1769, 203, 565, 1815, 19508, 12, 2316, 18, 12296, 951, 861, 950, 12, 2867, 12, 2211, 3631, 1203, 18, 5508, 3631, 1208, 13842, 1769, 203, 565, 1815, 19508, 12, 2316, 18, 4963, 3088, 1283, 9334, 1208, 13842, 1769, 203, 565, 1815, 19508, 12, 2316, 18, 4963, 3088, 1283, 861, 12, 2629, 18, 2696, 3631, 1208, 13842, 1769, 203, 565, 1815, 19508, 12, 2316, 18, 4963, 3088, 1283, 861, 12, 2629, 18, 5508, 3631, 1208, 13842, 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 ]
./full_match/1/0xcb6Ea7fddFdf2AFc2Bc6Bf715185A33F8E27B96b/sources/@pendle/core-v2/contracts/router/base/MarketApproxLib.sol
every iteration, the diff between guessMin and guessMax will be divided by 2
uint256 maxIteration;
3,061,510
[ 1, 20434, 6532, 16, 326, 3122, 3086, 7274, 2930, 471, 7274, 2747, 903, 506, 26057, 635, 576, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 943, 10795, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x88c2EF4520a6173E492aDeFa175Ba2497588Fe1f/sources/Slot_Machine.sol
@dev circuit breaker to disable the deposit function.
function depositsCircuitBreaker() public onlyOwner(){ bool _on; bool _off; enableDeposits = !enableDeposits; if(enableWithdrawals){ _on = true; _off = false; _on = false; _off = true; } emit DepositBreaker(_on, _off); }
720,534
[ 1, 24987, 898, 264, 358, 4056, 326, 443, 1724, 445, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 443, 917, 1282, 21719, 22660, 1435, 1071, 1338, 5541, 1435, 95, 203, 565, 1426, 389, 265, 31, 203, 565, 1426, 389, 3674, 31, 203, 565, 4237, 758, 917, 1282, 273, 401, 7589, 758, 917, 1282, 31, 203, 565, 309, 12, 7589, 1190, 9446, 1031, 15329, 203, 1377, 389, 265, 273, 638, 31, 203, 1377, 389, 3674, 273, 629, 31, 203, 1377, 389, 265, 273, 629, 31, 203, 1377, 389, 3674, 273, 638, 31, 203, 565, 289, 203, 565, 3626, 4019, 538, 305, 22660, 24899, 265, 16, 389, 3674, 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 ]
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "./GovernorMikeInterfaces.sol"; contract GovernorMikeDelegate is GovernorMikeDelegateStorageV2, GovernorMikeEvents { /// @notice The name of this contract string public constant name = "Compound Governor Mike"; /// @notice The minimum setable proposal threshold uint public constant MIN_PROPOSAL_THRESHOLD = 50000e18; // 50,000 Comp /// @notice The maximum setable proposal threshold uint public constant MAX_PROPOSAL_THRESHOLD = 100000e18; //100,000 Comp /// @notice The minimum setable voting period uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours /// @notice The max setable voting period uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks /// @notice The min setable voting delay uint public constant MIN_VOTING_DELAY = 1; /// @notice The max setable voting delay uint public constant MAX_VOTING_DELAY = 40320; // About 1 week /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed uint public constant quorumVotes = 400000e18; // 400,000 = 4% of Comp /// @notice The maximum number of actions that can be included in a proposal uint public constant proposalMaxOperations = 10; // 10 actions /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); /** * @notice Used to initialize the contract during delegator contructor * @param timelock_ The address of the Timelock * @param comp_ The address of the COMP token * @param votingPeriod_ The initial voting period * @param votingDelay_ The initial voting delay * @param proposalThreshold_ The initial proposal threshold */ function initialize(address timelock_, address comp_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public { require(address(timelock) == address(0), "GovernorMike::initialize: can only initialize once"); require(msg.sender == admin, "GovernorMike::initialize: admin only"); require(timelock_ != address(0), "GovernorMike::initialize: invalid timelock address"); require(comp_ != address(0), "GovernorMike::initialize: invalid comp address"); require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorMike::initialize: invalid voting period"); require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorMike::initialize: invalid voting delay"); require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorMike::initialize: invalid proposal threshold"); timelock = TimelockInterface(timelock_); comp = CompInterface(comp_); votingPeriod = votingPeriod_; votingDelay = votingDelay_; proposalThreshold = proposalThreshold_; } /** * @notice Function used to propose a new proposal with multiple issues. * Sender must have delegates above the proposal threshold * @param issues_ Choices * @return Proposal id of new proposal */ function propose( Issue[] memory issues_ ) public returns (uint) { proposalCount++; Proposal storage newProposal = proposals[proposalCount]; for (uint i = 0; i < issues_.length; i++) { // Allow addresses above proposal threshold and whitelisted addresses to propose require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold || isWhitelisted(msg.sender), "GovernorMike::propose: proposer votes below proposal threshold"); require( issues_[i].targets.length == issues_[i].values.length && issues_[i].targets.length == issues_[i].signatures.length && issues_[i].targets.length == issues_[i].calldatas.length, "GovernorMike::propose: proposal function information arity mismatch" ); require(issues_[i].targets.length != 0, "GovernorMike::propose: must provide actions"); require(issues_[i].targets.length <= proposalMaxOperations, "GovernorMike::propose: too many actions"); newProposal.issues.push(issues_[i]); } uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorMike::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorMike::propose: one live proposal per proposer, found an already pending proposal"); } uint startBlock = add256(block.number, votingDelay); uint endBlock = add256(startBlock, votingPeriod); newProposal.id = proposalCount; newProposal.proposer = msg.sender; newProposal.eta = 0; // newProposal.issues = issues_; // above newProposal.startBlock = startBlock; newProposal.endBlock = endBlock; newProposal.votes = new uint[](issues_.length); newProposal.canceled = false; newProposal.executed = false; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated(newProposal.id, msg.sender, startBlock, endBlock); return newProposal.id; } /** * @notice Queues a proposal of state succeeded * @param proposalId The id of the proposal to queue */ function queue(uint proposalId) external { require(state(proposalId) == ProposalState.Succeeded, "GovernorMike::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; Issue storage issue = proposal.issues[_winnerIssue(proposalId)]; uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < issue.targets.length; i++) { queueOrRevertInternal(issue.targets[i], issue.values[i], issue.signatures[i], issue.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorMike::queueOrRevertInternal: identical proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } /** * @notice Executes a queued proposal if eta has passed * @param proposalId The id of the proposal to execute */ function execute(uint proposalId) external payable { require(state(proposalId) == ProposalState.Queued, "GovernorMike::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; Issue storage issue = proposal.issues[_winnerIssue(proposalId)]; proposal.executed = true; for (uint i = 0; i < issue.targets.length; i++) { timelock.executeTransaction.value(issue.values[i])(issue.targets[i], issue.values[i], issue.signatures[i], issue.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } /** * @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold * @param proposalId The id of the proposal to cancel */ function cancel(uint proposalId) external { require(state(proposalId) != ProposalState.Executed, "GovernorMike::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; Issue storage issue = proposal.issues[_winnerIssue(proposalId)]; // Proposer can cancel if(msg.sender != proposal.proposer) { // Whitelisted proposers can't be canceled for falling below proposal threshold if(isWhitelisted(proposal.proposer)) { require((comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold) && msg.sender == whitelistGuardian, "GovernorMike::cancel: whitelisted proposer"); } else { require((comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold), "GovernorMike::cancel: proposer above threshold"); } } proposal.canceled = true; for (uint i = 0; i < issue.targets.length; i++) { timelock.cancelTransaction(issue.targets[i], issue.values[i], issue.signatures[i], issue.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } /** * @notice Gets an issue of a proposal * @param proposalId the id of the proposal * @param issueNum the number of the issue * @return Targets, values, signatures, calldatas, and description of the issue */ function getIssue(uint proposalId, uint issueNum) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) { Issue storage issue = proposals[proposalId].issues[issueNum]; return (issue.targets, issue.values, issue.signatures, issue.calldatas, issue.description); } /** * @notice Gets actions of a proposal * @param proposalId the id of the proposal * @return votes of the proposal */ function getVotes(uint proposalId) external view returns (uint[] memory) { return proposals[proposalId].votes; } /** * @notice Gets the receipt for a voter on a given proposal * @param proposalId the id of proposal * @param voter The address of the voter * @return The voting receipt */ function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } /** * @notice Gets the state of a proposal * @param proposalId The id of the proposal * @return Proposal state */ function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId, "GovernorMike::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (_winnerIssueVotes(proposalId) < quorumVotes) { // maxVotes < quorumVotes return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function _winnerIssue(uint proposalId) internal view returns(uint winnerIssue) { uint[] storage votes = proposals[proposalId].votes; uint maxVotes = 0; for (uint i = 0; i < votes.length; i++) { // TODO: case of equal if (votes[i] > maxVotes) { maxVotes = votes[i]; winnerIssue = i; } } } function _winnerIssueVotes(uint proposalId) internal view returns(uint maxVotes) { uint[] storage votes = proposals[proposalId].votes; uint winnerIssue = 0; for (uint i = 0; i < votes.length; i++) { // TODO: case of equal if (votes[i] > maxVotes) { maxVotes = votes[i]; winnerIssue = i; } } } /** * @notice Cast a vote for a proposal * @param proposalId The id of the proposal to vote on * @param support The id of the issue to vote on */ function castVote(uint proposalId, uint8 support) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), ""); } /** * @notice Cast a vote for a proposal with a reason * @param proposalId The id of the proposal to vote on * @param support The id of the issue to vote on * @param reason The reason given for the vote by the voter */ function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason); } /** * @notice Cast a vote for a proposal by signature * @dev External function that accepts EIP-712 signatures for voting on proposals. */ function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorMike::castVoteBySig: invalid signature"); emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), ""); } /** * @notice Internal function that caries out voting logic * @param voter The voter that is casting their vote * @param proposalId The id of the proposal to vote on * @param support The id of the issue to vote on * @return The number of votes cast */ function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) { require(state(proposalId) == ProposalState.Active, "GovernorMike::castVoteInternal: voting is closed"); Proposal storage proposal = proposals[proposalId]; require(support < proposal.issues.length, "GovernorMike::castVoteInternal: invalid vote type"); Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorMike::castVoteInternal: voter already voted"); uint96 votes = comp.getPriorVotes(voter, proposal.startBlock); proposal.votes[support] = add256(proposal.votes[support], votes); receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; return votes; } /** * @notice View function which returns if an account is whitelisted * @param account Account to check white list status of * @return If the account is whitelisted */ function isWhitelisted(address account) public view returns (bool) { return (whitelistAccountExpirations[account] > now); } /** * @notice Admin function for setting the voting delay * @param newVotingDelay new voting delay, in blocks */ function _setVotingDelay(uint newVotingDelay) external { require(msg.sender == admin, "GovernorMike::_setVotingDelay: admin only"); require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorMike::_setVotingDelay: invalid voting delay"); uint oldVotingDelay = votingDelay; votingDelay = newVotingDelay; emit VotingDelaySet(oldVotingDelay,votingDelay); } /** * @notice Admin function for setting the voting period * @param newVotingPeriod new voting period, in blocks */ function _setVotingPeriod(uint newVotingPeriod) external { require(msg.sender == admin, "GovernorMike::_setVotingPeriod: admin only"); require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorMike::_setVotingPeriod: invalid voting period"); uint oldVotingPeriod = votingPeriod; votingPeriod = newVotingPeriod; emit VotingPeriodSet(oldVotingPeriod, votingPeriod); } /** * @notice Admin function for setting the proposal threshold * @dev newProposalThreshold must be greater than the hardcoded min * @param newProposalThreshold new proposal threshold */ function _setProposalThreshold(uint newProposalThreshold) external { require(msg.sender == admin, "GovernorMike::_setProposalThreshold: admin only"); require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorMike::_setProposalThreshold: invalid proposal threshold"); uint oldProposalThreshold = proposalThreshold; proposalThreshold = newProposalThreshold; emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold); } /** * @notice Admin function for setting the whitelist expiration as a timestamp for an account. Whitelist status allows accounts to propose without meeting threshold * @param account Account address to set whitelist expiration for * @param expiration Expiration for account whitelist status as timestamp (if now < expiration, whitelisted) */ function _setWhitelistAccountExpiration(address account, uint expiration) external { require(msg.sender == admin || msg.sender == whitelistGuardian, "GovernorMike::_setWhitelistAccountExpiration: admin only"); whitelistAccountExpirations[account] = expiration; emit WhitelistAccountExpirationSet(account, expiration); } /** * @notice Admin function for setting the whitelistGuardian. WhitelistGuardian can cancel proposals from whitelisted addresses * @param account Account to set whitelistGuardian to (0x0 to remove whitelistGuardian) */ function _setWhitelistGuardian(address account) external { require(msg.sender == admin, "GovernorMike::_setWhitelistGuardian: admin only"); address oldGuardian = whitelistGuardian; whitelistGuardian = account; emit WhitelistGuardianSet(oldGuardian, whitelistGuardian); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. */ function _setPendingAdmin(address newPendingAdmin) external { // Check caller = admin require(msg.sender == admin, "GovernorMike:_setPendingAdmin: admin only"); // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() external { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorMike:_acceptAdmin: pending admin only"); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainIdInternal() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } }
* @notice Gets the state of a proposal @param proposalId The id of the proposal @return Proposal state/
function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId, "GovernorMike::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; return ProposalState.Pending; return ProposalState.Active; return ProposalState.Defeated; return ProposalState.Succeeded; return ProposalState.Executed; return ProposalState.Expired; return ProposalState.Queued; } }
1,835,950
[ 1, 3002, 326, 919, 434, 279, 14708, 225, 14708, 548, 1021, 612, 434, 326, 14708, 327, 19945, 919, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 919, 12, 11890, 14708, 548, 13, 1071, 1476, 1135, 261, 14592, 1119, 13, 288, 203, 3639, 2583, 12, 685, 8016, 1380, 1545, 14708, 548, 16, 315, 43, 1643, 29561, 49, 2547, 2866, 2019, 30, 2057, 14708, 612, 8863, 203, 3639, 19945, 2502, 14708, 273, 450, 22536, 63, 685, 8016, 548, 15533, 203, 3639, 309, 261, 685, 8016, 18, 10996, 329, 13, 288, 203, 5411, 327, 19945, 1119, 18, 23163, 31, 203, 5411, 327, 19945, 1119, 18, 8579, 31, 203, 5411, 327, 19945, 1119, 18, 3896, 31, 203, 5411, 327, 19945, 1119, 18, 758, 3030, 690, 31, 203, 5411, 327, 19945, 1119, 18, 30500, 31, 203, 5411, 327, 19945, 1119, 18, 23839, 31, 203, 5411, 327, 19945, 1119, 18, 10556, 31, 203, 5411, 327, 19945, 1119, 18, 21039, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; import "./FinalizableFundraiser.sol"; import "../component/RefundSafe.sol"; /** * @title Refundable fundraiser * * @dev Allows your fundraiser to offer refunds to token buyers if it failed to reach the `softCap` in its duration. */ contract RefundableFundraiser is FinalizableFundraiser { /// The minimum amount of funds (in ETH) to be gathered in order for the /// fundraiser to be considered successful. uint256 public softCap; /// The instance of the refund safe which holds all ETH funds until the fundraiser /// is finalized. RefundSafe public refundSafe; /** * @dev The constructor. * * @param _softCap The minimum amount of funds (in ETH) that need to be reached. */ function initializeRefundableFundraiser(uint256 _softCap) internal { require(_softCap > 0); refundSafe = new RefundSafe(address(this), beneficiary); softCap = _softCap; } /** * @dev Defines the abstract function from `BaseFundraiser` to add the funds to the `refundSafe` */ function handleFunds(address _address, uint256 _ethers) internal { refundSafe.deposit.value(_ethers)(_address); } /** * @dev Checks if the soft cap was reached by the fundraiser. * * @return Whether `softCap` is reached or not. */ function softCapReached() public view returns (bool) { return totalRaised >= softCap; } /** * @dev If the fundraiser failed to reach the soft cap, * participants can use this method to get their ether back. */ function getRefund() public { require(isFinalized); require(!softCapReached()); refundSafe.refund(msg.sender); } /** * @dev Overrides the setBeneficiation fucntion to set the beneficiary of the refund safe * * @param _beneficiary The address of the beneficiary. */ function setBeneficiary(address _beneficiary) public onlyOwner { super.setBeneficiary(_beneficiary); refundSafe.setBeneficiary(_beneficiary); } /** * @dev Overrides the default function from `FinalizableFundraiser` * to check if soft cap was reached and appropriatelly allow refunds * or simply close the refund safe. */ function finalization() internal { super.finalization(); if (softCapReached()) { refundSafe.close(); } else { refundSafe.allowRefunds(); } } }
* @dev Checks if the soft cap was reached by the fundraiser. @return Whether `softCap` is reached or not./
function softCapReached() public view returns (bool) { return totalRaised >= softCap; }
6,386,261
[ 1, 4081, 309, 326, 8971, 3523, 1703, 8675, 635, 326, 284, 1074, 354, 15914, 18, 327, 17403, 1375, 9269, 4664, 68, 353, 8675, 578, 486, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8971, 4664, 23646, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 2078, 12649, 5918, 1545, 8971, 4664, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./VeRipToken.sol"; /// @title Vote Escrow Rip Staking /// @author Dex Rip /// @notice Stake Rip to earn veRip, which you can use to earn higher farm yields and gain /// voting power. Note that unstaking any amount of Rip will burn all of your existing veRip. contract VeRipStaking is Initializable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @notice Info for each user /// `balance`: Amount of Rip currently staked by user /// `rewardDebt`: The reward debt of the user /// `lastClaimTimestamp`: The timestamp of user's last claim or withdraw /// `speedUpEndTimestamp`: The timestamp when user stops receiving speed up benefits, or /// zero if user is not currently receiving speed up benefits struct UserInfo { uint256 balance; uint256 rewardDebt; uint256 lastClaimTimestamp; uint256 speedUpEndTimestamp; /** * @notice We do some fancy math here. Basically, any point in time, the amount of veRip * entitled to a user but is pending to be distributed is: * * pendingReward = pendingBaseReward + pendingSpeedUpReward * * pendingBaseReward = (user.balance * accVeRipPerShare) - user.rewardDebt * * if user.speedUpEndTimestamp != 0: * speedUpCeilingTimestamp = min(block.timestamp, user.speedUpEndTimestamp) * speedUpSecondsElapsed = speedUpCeilingTimestamp - user.lastClaimTimestamp * pendingSpeedUpReward = speedUpSecondsElapsed * user.balance * speedUpVeRipPerSharePerSec * else: * pendingSpeedUpReward = 0 */ } IERC20Upgradeable public Rip; VeRipToken public veRip; /// @notice The maximum limit of veRip user can have as percentage points of staked Rip /// For example, if user has `n` Rip staked, they can own a maximum of `n * maxCapPct / 100` veRip. uint256 public maxCapPct; /// @notice The upper limit of `maxCapPct` uint256 public upperLimitMaxCapPct; /// @notice The accrued veRip per share, scaled to `ACC_VERip_PER_SHARE_PRECISION` uint256 public accVeRipPerShare; /// @notice Precision of `accVeRipPerShare` uint256 public ACC_VERip_PER_SHARE_PRECISION; /// @notice The last time that the reward variables were updated uint256 public lastRewardTimestamp; /// @notice veRip per sec per Rip staked, scaled to `VERip_PER_SHARE_PER_SEC_PRECISION` uint256 public veRipPerSharePerSec; /// @notice Speed up veRip per sec per Rip staked, scaled to `VERip_PER_SHARE_PER_SEC_PRECISION` uint256 public speedUpVeRipPerSharePerSec; /// @notice The upper limit of `veRipPerSharePerSec` and `speedUpVeRipPerSharePerSec` uint256 public upperLimitVeRipPerSharePerSec; /// @notice Precision of `veRipPerSharePerSec` uint256 public VERip_PER_SHARE_PER_SEC_PRECISION; /// @notice Percentage of user's current staked Rip user has to deposit in order to start /// receiving speed up benefits, in parts per 100. /// @dev Specifically, user has to deposit at least `speedUpThreshold/100 * userStakedRip` Rip. /// The only exception is the user will also receive speed up benefits if they are depositing /// with zero balance uint256 public speedUpThreshold; /// @notice The length of time a user receives speed up benefits uint256 public speedUpDuration; mapping(address => UserInfo) public userInfos; event Claim(address indexed user, uint256 amount); event Deposit(address indexed user, uint256 amount); event UpdateMaxCapPct(address indexed user, uint256 maxCapPct); event UpdateRewardVars(uint256 lastRewardTimestamp, uint256 accVeRipPerShare); event UpdateSpeedUpThreshold(address indexed user, uint256 speedUpThreshold); event UpdateVeRipPerSharePerSec(address indexed user, uint256 veRipPerSharePerSec); event Withdraw(address indexed user, uint256 amount); /// @notice Initialize with needed parameters /// @param _Rip Address of the Rip token contract /// @param _veRip Address of the veRip token contract /// @param _veRipPerSharePerSec veRip per sec per Rip staked, scaled to `VERip_PER_SHARE_PER_SEC_PRECISION` /// @param _speedUpVeRipPerSharePerSec Similar to `_veRipPerSharePerSec` but for speed up /// @param _speedUpThreshold Percentage of total staked Rip user has to deposit receive speed up /// @param _speedUpDuration Length of time a user receives speed up benefits /// @param _maxCapPct Maximum limit of veRip user can have as percentage points of staked Rip function initialize( IERC20Upgradeable _Rip, VeRipToken _veRip, uint256 _veRipPerSharePerSec, uint256 _speedUpVeRipPerSharePerSec, uint256 _speedUpThreshold, uint256 _speedUpDuration, uint256 _maxCapPct ) public initializer { __Ownable_init(); require(address(_Rip) != address(0), "VeRipStaking: unexpected zero address for _Rip"); require(address(_veRip) != address(0), "VeRipStaking: unexpected zero address for _veRip"); upperLimitVeRipPerSharePerSec = 1e36; require( _veRipPerSharePerSec <= upperLimitVeRipPerSharePerSec, "VeRipStaking: expected _veRipPerSharePerSec to be <= 1e36" ); require( _speedUpVeRipPerSharePerSec <= upperLimitVeRipPerSharePerSec, "VeRipStaking: expected _speedUpVeRipPerSharePerSec to be <= 1e36" ); require( _speedUpThreshold != 0 && _speedUpThreshold <= 100, "VeRipStaking: expected _speedUpThreshold to be > 0 and <= 100" ); require(_speedUpDuration <= 365 days, "VeRipStaking: expected _speedUpDuration to be <= 365 days"); upperLimitMaxCapPct = 10000000; require( _maxCapPct != 0 && _maxCapPct <= upperLimitMaxCapPct, "VeRipStaking: expected _maxCapPct to be non-zero and <= 10000000" ); maxCapPct = _maxCapPct; speedUpThreshold = _speedUpThreshold; speedUpDuration = _speedUpDuration; Rip = _Rip; veRip = _veRip; veRipPerSharePerSec = _veRipPerSharePerSec; speedUpVeRipPerSharePerSec = _speedUpVeRipPerSharePerSec; lastRewardTimestamp = block.timestamp; ACC_VERip_PER_SHARE_PRECISION = 1e18; VERip_PER_SHARE_PER_SEC_PRECISION = 1e18; } /// @notice Set maxCapPct /// @param _maxCapPct The new maxCapPct function setMaxCapPct(uint256 _maxCapPct) external onlyOwner { require(_maxCapPct > maxCapPct, "VeRipStaking: expected new _maxCapPct to be greater than existing maxCapPct"); require( _maxCapPct != 0 && _maxCapPct <= upperLimitMaxCapPct, "VeRipStaking: expected new _maxCapPct to be non-zero and <= 10000000" ); maxCapPct = _maxCapPct; emit UpdateMaxCapPct(msg.sender, _maxCapPct); } /// @notice Set veRipPerSharePerSec /// @param _veRipPerSharePerSec The new veRipPerSharePerSec function setVeRipPerSharePerSec(uint256 _veRipPerSharePerSec) external onlyOwner { require( _veRipPerSharePerSec <= upperLimitVeRipPerSharePerSec, "VeRipStaking: expected _veRipPerSharePerSec to be <= 1e36" ); updateRewardVars(); veRipPerSharePerSec = _veRipPerSharePerSec; emit UpdateVeRipPerSharePerSec(msg.sender, _veRipPerSharePerSec); } /// @notice Set speedUpThreshold /// @param _speedUpThreshold The new speedUpThreshold function setSpeedUpThreshold(uint256 _speedUpThreshold) external onlyOwner { require( _speedUpThreshold != 0 && _speedUpThreshold <= 100, "VeRipStaking: expected _speedUpThreshold to be > 0 and <= 100" ); speedUpThreshold = _speedUpThreshold; emit UpdateSpeedUpThreshold(msg.sender, _speedUpThreshold); } /// @notice Deposits Rip to start staking for veRip. Note that any pending veRip /// will also be claimed in the process. /// @param _amount The amount of Rip to deposit function deposit(uint256 _amount) external { require(_amount > 0, "VeRipStaking: expected deposit amount to be greater than zero"); updateRewardVars(); UserInfo storage userInfo = userInfos[msg.sender]; if (_getUserHasNonZeroBalance(msg.sender)) { // Transfer to the user their pending veRip before updating their UserInfo _claim(); // We need to update user's `lastClaimTimestamp` to now to prevent // passive veRip accrual if user hit their max cap. userInfo.lastClaimTimestamp = block.timestamp; uint256 userStakedRip = userInfo.balance; // User is eligible for speed up benefits if `_amount` is at least // `speedUpThreshold / 100 * userStakedRip` if (_amount.mul(100) >= speedUpThreshold.mul(userStakedRip)) { userInfo.speedUpEndTimestamp = block.timestamp.add(speedUpDuration); } } else { // If user is depositing with zero balance, they will automatically // receive speed up benefits userInfo.speedUpEndTimestamp = block.timestamp.add(speedUpDuration); userInfo.lastClaimTimestamp = block.timestamp; } userInfo.balance = userInfo.balance.add(_amount); userInfo.rewardDebt = accVeRipPerShare.mul(userInfo.balance).div(ACC_VERip_PER_SHARE_PRECISION); Rip.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); } /// @notice Withdraw staked Rip. Note that unstaking any amount of Rip means you will /// lose all of your current veRip. /// @param _amount The amount of Rip to unstake function withdraw(uint256 _amount) external { require(_amount > 0, "VeRipStaking: expected withdraw amount to be greater than zero"); UserInfo storage userInfo = userInfos[msg.sender]; require( userInfo.balance >= _amount, "VeRipStaking: cannot withdraw greater amount of Rip than currently staked" ); updateRewardVars(); // Note that we don't need to claim as the user's veRip balance will be reset to 0 userInfo.balance = userInfo.balance.sub(_amount); userInfo.rewardDebt = accVeRipPerShare.mul(userInfo.balance).div(ACC_VERip_PER_SHARE_PRECISION); userInfo.lastClaimTimestamp = block.timestamp; userInfo.speedUpEndTimestamp = 0; // Burn the user's current veRip balance veRip.burnFrom(msg.sender, veRip.balanceOf(msg.sender)); // Send user their requested amount of staked Rip Rip.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } /// @notice Claim any pending veRip function claim() external { require(_getUserHasNonZeroBalance(msg.sender), "VeRipStaking: cannot claim veRip when no Rip is staked"); updateRewardVars(); _claim(); } /// @notice Get the pending amount of veRip for a given user /// @param _user The user to lookup /// @return The number of pending veRip tokens for `_user` function getPendingVeRip(address _user) public view returns (uint256) { if (!_getUserHasNonZeroBalance(_user)) { return 0; } UserInfo memory user = userInfos[_user]; // Calculate amount of pending base veRip uint256 _accVeRipPerShare = accVeRipPerShare; uint256 secondsElapsed = block.timestamp.sub(lastRewardTimestamp); if (secondsElapsed > 0) { _accVeRipPerShare = _accVeRipPerShare.add( secondsElapsed.mul(veRipPerSharePerSec).mul(ACC_VERip_PER_SHARE_PRECISION).div( VERip_PER_SHARE_PER_SEC_PRECISION ) ); } uint256 pendingBaseVeRip = _accVeRipPerShare.mul(user.balance).div(ACC_VERip_PER_SHARE_PRECISION).sub( user.rewardDebt ); // Calculate amount of pending speed up veRip uint256 pendingSpeedUpVeRip; if (user.speedUpEndTimestamp != 0) { uint256 speedUpCeilingTimestamp = block.timestamp > user.speedUpEndTimestamp ? user.speedUpEndTimestamp : block.timestamp; uint256 speedUpSecondsElapsed = speedUpCeilingTimestamp.sub(user.lastClaimTimestamp); uint256 speedUpAccVeRipPerShare = speedUpSecondsElapsed.mul(speedUpVeRipPerSharePerSec); pendingSpeedUpVeRip = speedUpAccVeRipPerShare.mul(user.balance).div(VERip_PER_SHARE_PER_SEC_PRECISION); } uint256 pendingVeRip = pendingBaseVeRip.add(pendingSpeedUpVeRip); // Get the user's current veRip balance uint256 userVeRipBalance = veRip.balanceOf(_user); // This is the user's max veRip cap multiplied by 100 uint256 scaledUserMaxVeRipCap = user.balance.mul(maxCapPct); if (userVeRipBalance.mul(100) >= scaledUserMaxVeRipCap) { // User already holds maximum amount of veRip so there is no pending veRip return 0; } else if (userVeRipBalance.add(pendingVeRip).mul(100) > scaledUserMaxVeRipCap) { return scaledUserMaxVeRipCap.sub(userVeRipBalance.mul(100)).div(100); } else { return pendingVeRip; } } /// @notice Update reward variables function updateRewardVars() public { if (block.timestamp <= lastRewardTimestamp) { return; } if (Rip.balanceOf(address(this)) == 0) { lastRewardTimestamp = block.timestamp; return; } uint256 secondsElapsed = block.timestamp.sub(lastRewardTimestamp); accVeRipPerShare = accVeRipPerShare.add( secondsElapsed.mul(veRipPerSharePerSec).mul(ACC_VERip_PER_SHARE_PRECISION).div( VERip_PER_SHARE_PER_SEC_PRECISION ) ); lastRewardTimestamp = block.timestamp; emit UpdateRewardVars(lastRewardTimestamp, accVeRipPerShare); } /// @notice Checks to see if a given user currently has staked Rip /// @param _user The user address to check /// @return Whether `_user` currently has staked Rip function _getUserHasNonZeroBalance(address _user) private view returns (bool) { return userInfos[_user].balance > 0; } /// @dev Helper to claim any pending veRip function _claim() private { uint256 veRipToClaim = getPendingVeRip(msg.sender); UserInfo storage userInfo = userInfos[msg.sender]; userInfo.rewardDebt = accVeRipPerShare.mul(userInfo.balance).div(ACC_VERip_PER_SHARE_PRECISION); // If user's speed up period has ended, reset `speedUpEndTimestamp` to 0 if (userInfo.speedUpEndTimestamp != 0 && block.timestamp >= userInfo.speedUpEndTimestamp) { userInfo.speedUpEndTimestamp = 0; } if (veRipToClaim > 0) { userInfo.lastClaimTimestamp = block.timestamp; veRip.mint(msg.sender, veRipToClaim); emit Claim(msg.sender, veRipToClaim); } } }
@notice The maximum limit of veRip user can have as percentage points of staked Rip For example, if user has `n` Rip staked, they can own a maximum of `n * maxCapPct / 100` veRip.
uint256 public maxCapPct;
13,017,621
[ 1, 1986, 4207, 1800, 434, 10489, 54, 625, 729, 848, 1240, 487, 11622, 3143, 434, 384, 9477, 534, 625, 2457, 3454, 16, 309, 729, 711, 1375, 82, 68, 534, 625, 384, 9477, 16, 2898, 848, 4953, 279, 4207, 434, 1375, 82, 225, 943, 4664, 52, 299, 342, 2130, 68, 10489, 54, 625, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 2254, 5034, 1071, 943, 4664, 52, 299, 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 ]
./partial_match/1/0x5aB4C93a366Ca13698a18C74c69a07B43aC18e29/sources/Staking.sol
* @dev Withdraw interest/
function withdrawInterest(uint256 depositId) public { _transferInterest(msg.sender, depositId); }
15,994,927
[ 1, 1190, 9446, 16513, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 29281, 12, 11890, 5034, 443, 1724, 548, 13, 1071, 288, 203, 3639, 389, 13866, 29281, 12, 3576, 18, 15330, 16, 443, 1724, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x3F2b72B9D52651B4dcdB99d1AB1736aC889e6e38/sources/contracts/mixins/MixinConvenienceOwnable.sol
* @title Mixin to add support for `ownable()` @dev `Mixins` are a design pattern seen in the 0x contracts. It simply separates logically groupings of code to ease readability./ used for `owner()`convenience helper events
contract MixinConvenienceOwnable is MixinErrors, MixinLockCore { address private _convenienceOwner; event OwnershipTransferred(address previousOwner, address newOwner); pragma solidity ^0.8.0; function _initializeMixinConvenienceOwnable(address _sender) internal { _convenienceOwner = _sender; } function owner() public view returns (address) { return _convenienceOwner; } function setOwner(address account) public { _onlyLockManager(); if(account == address(0)) { revert OWNER_CANT_BE_ADDRESS_ZERO(); } address _previousOwner = _convenienceOwner; _convenienceOwner = account; emit OwnershipTransferred(_previousOwner, account); } function setOwner(address account) public { _onlyLockManager(); if(account == address(0)) { revert OWNER_CANT_BE_ADDRESS_ZERO(); } address _previousOwner = _convenienceOwner; _convenienceOwner = account; emit OwnershipTransferred(_previousOwner, account); } function isOwner(address account) public view returns (bool) { return _convenienceOwner == account; } uint256[1000] private __safe_upgrade_gap; }
9,486,620
[ 1, 14439, 358, 527, 2865, 364, 1375, 995, 429, 20338, 225, 1375, 21294, 2679, 68, 854, 279, 8281, 1936, 5881, 316, 326, 374, 92, 20092, 18, 225, 2597, 8616, 5102, 815, 4058, 1230, 1041, 899, 434, 981, 358, 28769, 855, 2967, 18, 19, 1399, 364, 1375, 8443, 20338, 591, 9080, 4222, 2641, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 490, 10131, 14700, 5460, 429, 353, 490, 10131, 4229, 16, 490, 10131, 2531, 4670, 288, 203, 203, 225, 1758, 3238, 389, 591, 9080, 5541, 31, 203, 203, 225, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 2416, 5541, 16, 1758, 394, 5541, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 225, 445, 389, 11160, 14439, 14700, 5460, 429, 12, 2867, 389, 15330, 13, 2713, 288, 203, 565, 389, 591, 9080, 5541, 273, 389, 15330, 31, 203, 225, 289, 203, 203, 225, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 565, 327, 389, 591, 9080, 5541, 31, 203, 225, 289, 203, 203, 225, 445, 31309, 12, 2867, 2236, 13, 1071, 288, 203, 565, 389, 3700, 2531, 1318, 5621, 203, 565, 309, 12, 4631, 422, 1758, 12, 20, 3719, 288, 203, 1377, 15226, 531, 22527, 67, 39, 6856, 67, 5948, 67, 15140, 67, 24968, 5621, 7010, 565, 289, 203, 565, 1758, 389, 11515, 5541, 273, 389, 591, 9080, 5541, 31, 203, 565, 389, 591, 9080, 5541, 273, 2236, 31, 203, 565, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 11515, 5541, 16, 2236, 1769, 203, 225, 289, 203, 203, 225, 445, 31309, 12, 2867, 2236, 13, 1071, 288, 203, 565, 389, 3700, 2531, 1318, 5621, 203, 565, 309, 12, 4631, 422, 1758, 12, 20, 3719, 288, 203, 1377, 15226, 531, 22527, 67, 39, 6856, 67, 5948, 67, 15140, 67, 24968, 5621, 7010, 565, 289, 203, 565, 1758, 389, 11515, 5541, 273, 389, 591, 9080, 5541, 31, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol"; import "./interfaces/IPoolMaster.sol"; import "./interfaces/IFlashGovernor.sol"; import "./interfaces/IMembershipStaking.sol"; import "./libraries/Decimal.sol"; contract PoolFactory is OwnableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using ClonesUpgradeable for address; using SafeCastUpgradeable for uint256; using Decimal for uint256; /// @notice CPOOL token contract IERC20Upgradeable public cpool; /// @notice MembershipStaking contract IMembershipStaking public staking; /// @notice FlashGovernor contract IFlashGovernor public flashGovernor; /// @notice Pool master contract address public poolMaster; /// @notice Interest Rate Model contract address address public interestRateModel; /// @notice Address of the auction contract address public auction; /// @notice Address of the treasury address public treasury; /// @notice Reserve factor as 18-digit decimal uint256 public reserveFactor; /// @notice Insurance factor as 18-digit decimal uint256 public insuranceFactor; /// @notice Pool utilization that leads to warning state (as 18-digit decimal) uint256 public warningUtilization; /// @notice Pool utilization that leads to provisional default (as 18-digit decimal) uint256 public provisionalDefaultUtilization; /// @notice Grace period for warning state before pool goes to default (in seconds) uint256 public warningGracePeriod; /// @notice Max period for which pool can stay not active before it can be closed by governor (in seconds) uint256 public maxInactivePeriod; /// @notice Period after default to start auction after which pool can be closed by anyone (in seconds) uint256 public periodToStartAuction; /// @notice Allowance of different currencies in protocol mapping(address => bool) public currencyAllowed; struct ManagerInfo { address currency; address pool; address staker; uint32 proposalId; uint256 stakedAmount; bytes32 ipfsHash; string managerSymbol; } /// @notice Mapping of manager addresses to their pool info mapping(address => ManagerInfo) public managerInfo; /// @notice Mapping of manager symbols to flags if they are already used mapping(string => bool) public usedManagerSymbols; /// @notice Mapping of addresses to flags indicating if they are pools mapping(address => bool) public isPool; // EVENTS /// @notice Event emitted when new pool is proposed event PoolProposed(address indexed manager, address indexed currency); /// @notice Event emitted when proposed pool is cancelled event PoolCancelled(address indexed manager, address indexed currency); /// @notice Event emitted when new pool is created event PoolCreated( address indexed pool, address indexed manager, address indexed currency, bool forceCreated ); /// @notice Event emitted when pool is closed event PoolClosed( address indexed pool, address indexed manager, address indexed currency ); /// @notice Event emitted when status of the currency is set event CurrencySet(address currency, bool allowed); /// @notice Event emitted when new pool master is set event PoolMasterSet(address newPoolMaster); /// @notice Event emitted when new interest rate model is set event InterestRateModelSet(address newModel); /// @notice Event emitted when new treasury is set event TreasurySet(address newTreasury); /// @notice Event emitted when new reserve factor is set event ReserveFactorSet(uint256 factor); /// @notice Event emitted when new insurance factor is set event InsuranceFactorSet(uint256 factor); /// @notice Event emitted when new warning utilization is set event WarningUtilizationSet(uint256 utilization); /// @notice Event emitted when new provisional default utilization is set event ProvisionalDefaultUtilizationSet(uint256 utilization); /// @notice Event emitted when new warning grace period is set event WarningGracePeriodSet(uint256 period); /// @notice Event emitted when new max inactive period is set event MaxInactivePeriodSet(uint256 period); /// @notice Event emitted when new period to start auction is set event PeriodToStartAuctionSet(uint256 period); /// @notice Event emitted when new reward per block is set for some pool event PoolRewardPerBlockSet(address indexed pool, uint256 rewardPerBlock); // CONSTRUCTOR /** * @notice Upgradeable contract constructor * @param cpool_ The address of the CPOOL contract * @param staking_ The address of the Staking contract * @param flashGovernor_ The address of the FlashGovernor contract * @param poolMaster_ The address of the PoolMaster contract * @param interestRateModel_ The address of the InterestRateModel contract * @param auction_ The address of the Auction contract */ function initialize( IERC20Upgradeable cpool_, IMembershipStaking staking_, IFlashGovernor flashGovernor_, address poolMaster_, address interestRateModel_, address auction_ ) external initializer { require(address(cpool_) != address(0), "AIZ"); require(address(staking_) != address(0), "AIZ"); require(address(flashGovernor_) != address(0), "AIZ"); require(poolMaster_ != address(0), "AIZ"); require(interestRateModel_ != address(0), "AIZ"); require(auction_ != address(0), "AIZ"); __Ownable_init(); cpool = cpool_; staking = staking_; flashGovernor = flashGovernor_; poolMaster = poolMaster_; interestRateModel = interestRateModel_; auction = auction_; } /* PUBLIC FUNCTIONS */ /** * @notice Function used to propose new pool for the first time (with manager's info) * @param currency Address of the ERC20 token that would act as currnecy in the pool * @param ipfsHash IPFS hash of the manager's info * @param managerSymbol Manager's symbol */ function proposePoolInitial( address currency, bytes32 ipfsHash, string memory managerSymbol ) external { _setManager(msg.sender, ipfsHash, managerSymbol); _proposePool(currency); } /** * @notice Function used to propose new pool (when manager's info already exist) * @param currency Address of the ERC20 token that would act as currnecy in the pool */ function proposePool(address currency) external { require(managerInfo[msg.sender].ipfsHash != bytes32(0), "MHI"); _proposePool(currency); } /** * @notice Function used to create proposed and approved pool */ function createPool() external { ManagerInfo storage info = managerInfo[msg.sender]; flashGovernor.execute(info.proposalId); IPoolMaster pool = IPoolMaster(poolMaster.clone()); pool.initialize(msg.sender, info.currency); info.pool = address(pool); isPool[address(pool)] = true; emit PoolCreated(address(pool), msg.sender, info.currency, false); } /** * @notice Function used to cancel proposed but not yet created pool */ function cancelPool() external { ManagerInfo storage info = managerInfo[msg.sender]; require(info.proposalId != 0 && info.pool == address(0), "NPP"); emit PoolCancelled(msg.sender, info.currency); info.currency = address(0); info.proposalId = 0; staking.unlockStake(info.staker, info.stakedAmount); } // RESTRICTED FUNCTIONS /** * @notice Function used to immedeately create new pool for some manager for the first time * @notice Skips approval, restricted to owner * @param manager Manager to create pool for * @param currency Address of the ERC20 token that would act as currnecy in the pool * @param ipfsHash IPFS hash of the manager's info * @param managerSymbol Manager's symbol */ function forceCreatePoolInitial( address manager, address currency, bytes32 ipfsHash, string memory managerSymbol ) external onlyOwner { _setManager(manager, ipfsHash, managerSymbol); _forceCreatePool(manager, currency); } /** * @notice Function used to immediately create new pool for some manager (when info already exist) * @notice Skips approval, restricted to owner * @param manager Manager to create pool for * @param currency Address of the ERC20 token that would act as currnecy in the pool */ function forceCreatePool(address manager, address currency) external onlyOwner { require(managerInfo[manager].ipfsHash != bytes32(0), "MHI"); _forceCreatePool(manager, currency); } /** * @notice Function is called by contract owner to update currency allowance in the protocol * @param currency Address of the ERC20 token * @param allowed Should currency be allowed or forbidden */ function setCurrency(address currency, bool allowed) external onlyOwner { currencyAllowed[currency] = allowed; emit CurrencySet(currency, allowed); } /** * @notice Function is called by contract owner to set new PoolMaster * @param poolMaster_ Address of the new PoolMaster contract */ function setPoolMaster(address poolMaster_) external onlyOwner { require(poolMaster_ != address(0), "AIZ"); poolMaster = poolMaster_; emit PoolMasterSet(poolMaster_); } /** * @notice Function is called by contract owner to set new InterestRateModel * @param interestRateModel_ Address of the new InterestRateModel contract */ function setInterestRateModel(address interestRateModel_) external onlyOwner { require(interestRateModel_ != address(0), "AIZ"); interestRateModel = interestRateModel_; emit InterestRateModelSet(interestRateModel_); } /** * @notice Function is called by contract owner to set new treasury * @param treasury_ Address of the new treasury */ function setTreasury(address treasury_) external onlyOwner { require(treasury_ != address(0), "AIZ"); treasury = treasury_; emit TreasurySet(treasury_); } /** * @notice Function is called by contract owner to set new reserve factor * @param reserveFactor_ New reserve factor as 18-digit decimal */ function setReserveFactor(uint256 reserveFactor_) external onlyOwner { require(reserveFactor_ <= Decimal.ONE, "GTO"); reserveFactor = reserveFactor_; emit ReserveFactorSet(reserveFactor_); } /** * @notice Function is called by contract owner to set new insurance factor * @param insuranceFactor_ New reserve factor as 18-digit decimal */ function setInsuranceFactor(uint256 insuranceFactor_) external onlyOwner { require(insuranceFactor_ <= Decimal.ONE, "GTO"); insuranceFactor = insuranceFactor_; emit InsuranceFactorSet(insuranceFactor_); } /** * @notice Function is called by contract owner to set new warning utilization * @param warningUtilization_ New warning utilization as 18-digit decimal */ function setWarningUtilization(uint256 warningUtilization_) external onlyOwner { require(warningUtilization_ <= Decimal.ONE, "GTO"); warningUtilization = warningUtilization_; emit WarningUtilizationSet(warningUtilization_); } /** * @notice Function is called by contract owner to set new provisional default utilization * @param provisionalDefaultUtilization_ New provisional default utilization as 18-digit decimal */ function setProvisionalDefaultUtilization( uint256 provisionalDefaultUtilization_ ) external onlyOwner { require(provisionalDefaultUtilization_ <= Decimal.ONE, "GTO"); provisionalDefaultUtilization = provisionalDefaultUtilization_; emit ProvisionalDefaultUtilizationSet(provisionalDefaultUtilization_); } /** * @notice Function is called by contract owner to set new warning grace period * @param warningGracePeriod_ New warning grace period in seconds */ function setWarningGracePeriod(uint256 warningGracePeriod_) external onlyOwner { warningGracePeriod = warningGracePeriod_; emit WarningGracePeriodSet(warningGracePeriod_); } /** * @notice Function is called by contract owner to set new max inactive period * @param maxInactivePeriod_ New max inactive period in seconds */ function setMaxInactivePeriod(uint256 maxInactivePeriod_) external onlyOwner { maxInactivePeriod = maxInactivePeriod_; emit MaxInactivePeriodSet(maxInactivePeriod_); } /** * @notice Function is called by contract owner to set new period to start auction * @param periodToStartAuction_ New period to start auction */ function setPeriodToStartAuction(uint256 periodToStartAuction_) external onlyOwner { periodToStartAuction = periodToStartAuction_; emit PeriodToStartAuctionSet(periodToStartAuction_); } /** * @notice Function is called by contract owner to set new CPOOl reward per block speed in some pool * @param pool Pool where to set reward * @param rewardPerBlock Reward per block value */ function setPoolRewardPerBlock(address pool, uint256 rewardPerBlock) external onlyOwner { IPoolMaster(pool).setRewardPerBlock(rewardPerBlock); emit PoolRewardPerBlockSet(pool, rewardPerBlock); } /** * @notice Function is called through pool at closing to unlock manager's stake */ function closePool() external { require(isPool[msg.sender], "SNP"); address manager = IPoolMaster(msg.sender).manager(); ManagerInfo storage info = managerInfo[manager]; address currency = info.currency; info.currency = address(0); info.pool = address(0); staking.unlockStake(info.staker, info.stakedAmount); emit PoolClosed(msg.sender, manager, currency); } /** * @notice Function is called through pool to burn manager's stake when auction starts */ function burnStake() external { require(isPool[msg.sender], "SNP"); ManagerInfo storage info = managerInfo[ IPoolMaster(msg.sender).manager() ]; staking.burnStake(info.staker, info.stakedAmount); info.staker = address(0); info.stakedAmount = 0; } /** * @notice Function is used to withdraw CPOOL rewards from multiple pools * @param pools List of pools to withdrawm from */ function withdrawReward(address[] memory pools) external { uint256 totalReward; for (uint256 i = 0; i < pools.length; i++) { require(isPool[pools[i]], "NPA"); totalReward += IPoolMaster(pools[i]).withdrawReward(msg.sender); } if (totalReward > 0) { cpool.safeTransfer(msg.sender, totalReward); } } // VIEW FUNCTIONS /** * @notice Function returns symbol for new pool based on currency and manager * @param currency Pool's currency address * @param manager Manager's address * @return Pool symbol */ function getPoolSymbol(address currency, address manager) external view returns (string memory) { return string( bytes.concat( bytes("cp"), bytes(managerInfo[manager].managerSymbol), bytes("-"), bytes(IERC20MetadataUpgradeable(currency).symbol()) ) ); } // INTERNAL FUNCTIONS /** * @notice Internal function that proposes pool * @param currency Currency of the pool */ function _proposePool(address currency) private { require(currencyAllowed[currency], "CNA"); ManagerInfo storage info = managerInfo[msg.sender]; require(info.currency == address(0), "AHP"); info.proposalId = flashGovernor.propose(); info.currency = currency; info.staker = msg.sender; info.stakedAmount = staking.lockStake(msg.sender); emit PoolProposed(msg.sender, currency); } /** * @notice Internal function that immedeately creates pool * @param manager Manager of the pool * @param currency Currency of the pool */ function _forceCreatePool(address manager, address currency) private { require(currencyAllowed[currency], "CNA"); ManagerInfo storage info = managerInfo[manager]; require(info.currency == address(0), "AHP"); IPoolMaster pool = IPoolMaster(poolMaster.clone()); pool.initialize(manager, currency); info.pool = address(pool); info.currency = currency; info.staker = msg.sender; info.stakedAmount = staking.lockStake(msg.sender); isPool[address(pool)] = true; emit PoolCreated(address(pool), manager, currency, true); } /** * @notice Internal function that sets manager's info * @param manager Manager to set info for * @param info Manager's info IPFS hash * @param symbol Manager's symbol */ function _setManager( address manager, bytes32 info, string memory symbol ) private { require(managerInfo[manager].ipfsHash == bytes32(0), "AHI"); require(info != bytes32(0), "CEI"); require(!usedManagerSymbols[symbol], "SAU"); managerInfo[manager].ipfsHash = info; managerInfo[manager].managerSymbol = symbol; usedManagerSymbols[symbol] = true; } } // 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 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 // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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 "../IERC20Upgradeable.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 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable 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(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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library ClonesUpgradeable { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal 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; } // 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 SafeCastUpgradeable { /** * @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 pragma solidity 0.8.9; interface IPoolMaster { function manager() external view returns (address); function currency() external view returns (address); function borrows() external view returns (uint256); function insurance() external view returns (uint256); function getBorrowRate() external view returns (uint256); function getSupplyRate() external view returns (uint256); enum State { Active, Warning, ProvisionalDefault, Default, Closed } function state() external view returns (State); function initialize(address manager_, address currency_) external; function setRewardPerBlock(uint256 rewardPerBlock_) external; function withdrawReward(address account) external returns (uint256); function transferReserves() external; function processAuctionStart() external; function processDebtClaim() external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IFlashGovernor { function proposalEndBlock(uint32 proposalId) external view returns (uint256); function propose() external returns (uint32); function execute(uint32 proposalId) external; enum ProposalState { Pending, Active, Defeated, Succeeded, Executed } function state(uint32 proposalId) external view returns (ProposalState); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IMembershipStaking { function managerMinimalStake() external view returns (uint256); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); function lockStake(address account) external returns (uint256); function unlockStake(address account, uint256 amount) external; function burnStake(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; library Decimal { /// @notice Number one as 18-digit decimal uint256 internal constant ONE = 1e18; /** * @notice Internal function for 10-digits decimal division * @param number Integer number * @param decimal Decimal number * @return Returns multiplied numbers */ function mulDecimal(uint256 number, uint256 decimal) internal pure returns (uint256) { return (number * decimal) / ONE; } /** * @notice Internal function for 10-digits decimal multiplication * @param number Integer number * @param decimal Decimal number * @return Returns integer number divided by second */ function divDecimal(uint256 number, uint256 decimal) internal pure returns (uint256) { return (number * ONE) / decimal; } } // 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 AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal 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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } }
* @notice Internal function for 10-digits decimal multiplication @param number Integer number @param decimal Decimal number @return Returns integer number divided by second/
function divDecimal(uint256 number, uint256 decimal) internal pure returns (uint256) { return (number * ONE) / decimal; }
1,265,754
[ 1, 3061, 445, 364, 1728, 17, 16649, 6970, 23066, 225, 1300, 2144, 1300, 225, 6970, 11322, 1300, 327, 2860, 3571, 1300, 26057, 635, 2205, 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, 3739, 5749, 12, 11890, 5034, 1300, 16, 2254, 5034, 6970, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 261, 2696, 380, 15623, 13, 342, 6970, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// ----------------------------------------------------------------------------- // File ENG-LINKS-GENERATORS.SOL // // (c) Elijah Koziev // // Content: // Правила для автоматической генерации обратных связей для английского // тезауруса. // ----------------------------------------------------------------------------- // // CD->20.05.2006 // LC->09.02.2011 // -------------- #include "sg_defs.h" automat sg { // *************************************************************************** // Объявления для генераторов обратных связей в тезаурусе // *************************************************************************** // Несколько правил автогенерации обратных связок link generator ENG_ADJECTIVE <в_предикат> ENG_VERB -> <в_прил> link generator ENG_VERB <в_прил> ENG_ADJECTIVE -> <в_предикат> link generator ENG_VERB <в_сущ> ENG_NOUN -> <в_предикат> link generator ENG_NOUN <в_предикат> ENG_VERB -> <в_сущ> link generator ENG_NOUN <в_прил> ENG_ADJECTIVE -> <в_сущ> link generator ENG_NOUN <synonym> ENG_NOUN -> <synonym> link generator ENG_ADJECTIVE <synonym> ENG_ADJECTIVE -> <synonym> link generator ENG_VERB <synonym> ENG_VERB -> <synonym> link generator ENG_ADVERB <synonym> ENG_ADVERB -> <synonym> link generator ENG_ADJECTIVE <antonym> ENG_ADJECTIVE -> <antonym> link generator ENG_NOUN <antonym> ENG_NOUN -> <antonym> link generator ENG_ADVERB <antonym> ENG_ADVERB -> <antonym> link generator ENG_VERB <antonym> ENG_VERB -> <antonym> }
*************************************************************************** Объявления для генераторов обратных связей в тезаурусе *************************************************************************** Несколько правил автогенерации обратных связок
{ link generator ENG_ADJECTIVE <в_предикат> ENG_VERB -> <в_прил> link generator ENG_VERB <в_прил> ENG_ADJECTIVE -> <в_предикат> link generator ENG_VERB <в_сущ> ENG_NOUN -> <в_предикат> link generator ENG_NOUN <в_предикат> ENG_VERB -> <в_сущ> link generator ENG_NOUN <в_прил> ENG_ADJECTIVE -> <в_сущ> link generator ENG_NOUN <synonym> ENG_NOUN -> <synonym> link generator ENG_ADJECTIVE <synonym> ENG_ADJECTIVE -> <synonym> link generator ENG_VERB <synonym> ENG_VERB -> <synonym> link generator ENG_ADVERB <synonym> ENG_ADVERB -> <synonym> link generator ENG_ADJECTIVE <antonym> ENG_ADJECTIVE -> <antonym> link generator ENG_NOUN <antonym> ENG_NOUN -> <antonym> link generator ENG_ADVERB <antonym> ENG_ADVERB -> <antonym> link generator ENG_VERB <antonym> ENG_VERB -> <antonym> }
1,823,859
[ 1, 145, 257, 145, 114, 146, 237, 146, 242, 145, 115, 145, 124, 145, 118, 145, 126, 145, 121, 146, 242, 225, 145, 117, 145, 124, 146, 242, 225, 145, 116, 145, 118, 145, 126, 145, 118, 146, 227, 145, 113, 146, 229, 145, 127, 146, 227, 145, 127, 145, 115, 225, 145, 127, 145, 114, 146, 227, 145, 113, 146, 229, 145, 126, 146, 238, 146, 232, 225, 146, 228, 145, 115, 146, 242, 145, 120, 145, 118, 145, 122, 225, 145, 115, 225, 146, 229, 145, 118, 145, 120, 145, 113, 146, 230, 146, 227, 146, 230, 146, 228, 145, 118, 225, 225, 145, 256, 145, 118, 146, 228, 145, 123, 145, 127, 145, 124, 146, 239, 145, 123, 145, 127, 225, 145, 128, 146, 227, 145, 113, 145, 115, 145, 121, 145, 124, 225, 145, 113, 145, 115, 146, 229, 145, 127, 145, 116, 145, 118, 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, 95, 203, 203, 203, 1692, 4456, 17979, 67, 1880, 5304, 5354, 411, 145, 115, 67, 145, 128, 146, 227, 145, 118, 145, 117, 145, 121, 145, 123, 145, 113, 146, 229, 34, 17979, 67, 2204, 38, 317, 411, 145, 115, 67, 145, 128, 146, 227, 145, 121, 145, 124, 34, 203, 1692, 4456, 17979, 67, 2204, 38, 411, 145, 115, 67, 145, 128, 146, 227, 145, 121, 145, 124, 34, 17979, 67, 1880, 5304, 5354, 317, 411, 145, 115, 67, 145, 128, 146, 227, 145, 118, 145, 117, 145, 121, 145, 123, 145, 113, 146, 229, 34, 203, 1692, 4456, 17979, 67, 2204, 38, 411, 145, 115, 67, 146, 228, 146, 230, 146, 236, 34, 17979, 67, 3417, 2124, 317, 411, 145, 115, 67, 145, 128, 146, 227, 145, 118, 145, 117, 145, 121, 145, 123, 145, 113, 146, 229, 34, 203, 1692, 4456, 17979, 67, 3417, 2124, 411, 145, 115, 67, 145, 128, 146, 227, 145, 118, 145, 117, 145, 121, 145, 123, 145, 113, 146, 229, 34, 17979, 67, 2204, 38, 317, 411, 145, 115, 67, 146, 228, 146, 230, 146, 236, 34, 203, 1692, 4456, 17979, 67, 3417, 2124, 411, 145, 115, 67, 145, 128, 146, 227, 145, 121, 145, 124, 34, 17979, 67, 1880, 5304, 5354, 317, 411, 145, 115, 67, 146, 228, 146, 230, 146, 236, 34, 203, 203, 1692, 4456, 17979, 67, 3417, 2124, 411, 11982, 6435, 34, 17979, 67, 3417, 2124, 317, 411, 11982, 6435, 34, 203, 1692, 4456, 17979, 67, 1880, 5304, 5354, 411, 11982, 6435, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; /** Learn more about our project on thewhitelist.io MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXxclxddOxcdxllxKMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWk':O:.:' ';.'lKMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMXdkXkd0xcdxloxXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMXKKKXWMMMNKKKXWMMMWKKKKNXKKKXWMMWXKKKXWWXKKKNNKKKKKKKKKKKKXNNKKKKKKKKKKXWNKKKKNMMMMMMWKkdkKWMMWNKOOOO0XWNXKKKKKKKKKKKNM MWx...'xWMNo....dWMWd...:Ol...:KMMK:...cX0;...ld'...........,dd..........lXk'..'kMMMMMWx. .xN0c'. ..ld,...........xM MMK, ,KWk. '0MO' .dXc '0MMK, ;KO. cx:,,. .',;cxl .,,,,;dNd. .xWMMMMNl cx' .::;''xOc,,. .',;OM MMWx. o0; l0c :XNc .;cl;. ;KO. cXWWNd. oNWWWNo .;llllxXWd. .xWMMMMMK; ;0x. .codxONWWNNk. lXWWWM MMMNc .,. .. .,. .kWXc ;XO. cNMMMx. oWMMMWo ;KWd. .xWMMMMMNl cNNx,. .c0WMMO. oWMMMM MMMMO' 'ko lNMNc .cddl. ;XO. cNMMMx. oWMMMWo .:ddddkXWd. .oXNNNNWK; ;KMXkxxdl;. cXMMO. oWMMMM MMMMWd. .oNK, ,KMMNc '0MMK, ;XO. cNMMMx. oWMMMWo .'''''lKd. .'''',xO' .OK:..';;' .dWMMO. oWMMMM MMMMMXc....cXMWk,...,kWMMNo...:KMMXc...lX0:...oNMMMO,..'xWMMMWx'.........:Kk,........'dk,...,k0c'......':kNMMM0;..'xWMMMM MMMMMMXK000XWMMWK000KWMMMWX000XWMMWX000XWWK00KXMMMMNK00KNMMMMMNK000000000XWNK00000000KNNK000KNMWXKOOOO0XWMMMMMWK00KNMMMMM */ import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ERC2981.sol"; import "./MintpassValidator.sol"; import "./LibMintpass.sol"; /** * @dev Learn more about this project on thewhitelist.io. * * TheWhitelist is a ERC721 Contract that supports Burnable. * The minting process is processed in a public and a whitelist * sale. */ contract TheWhitelist is MintpassValidator, ERC721Burnable, ERC2981, Ownable { using Counters for Counters.Counter; using Strings for uint256; // Token Limit and Mint Limits uint256 public TOKEN_LIMIT = 10000; uint256 public whitelistMintLimitPerWallet = 2; uint256 public publicMintLimitPerWallet = 5; // Price per Token depending on Category uint256 public whitelistMintPrice = 0.17 ether; uint256 public publicMintPrice = 0.19 ether; // Sale Stages Enabled / Disabled bool public whitelistMintEnabled = false; bool public publicMintEnabled = false; // Mapping from minter to minted amounts mapping(address => uint256) public boughtAmounts; mapping(address => uint256) public boughtWhitelistAmounts; // Mapping from mintpass signature to minted amounts (Free Mints) mapping(bytes => uint256) public mintpassRedemptions; // Optional mapping to overwrite specific token URIs mapping(uint256 => string) private _tokenURIs; // counter for tracking current token id Counters.Counter private _tokenIdTracker; // _abseTokenURI serving nft metadata per token string private _baseTokenURI = "https://api.thewhitelist.io/tokens/"; event TokenUriChanged( address indexed _address, uint256 indexed _tokenId, string _tokenURI ); /** * @dev ERC721 Constructor */ constructor(string memory name, string memory symbol) ERC721(name, symbol) { _setDefaultRoyalty(msg.sender, 700); ACE_WALLET = 0x8F564ad0FBdf89b4925c91Be37b3891244544Abf; } /** * @dev Withrawal all Funds sent to the contract to Owner * * Requirements: * - `msg.sender` needs to be Owner and payable */ function withdrawalAll() external onlyOwner { require(payable(msg.sender).send(address(this).balance)); } /** * @dev Function to mint Tokens for only Gas. This function is used * for Community Wallet Mints, Raffle Winners and Cooperation Partners. * Redemptions are tracked and can be done in chunks. * * @param quantity amount of tokens to be minted * @param mintpass issued by thewhitelist.io * @param mintpassSignature issued by thewhitelist.io and signed by ACE_WALLET * * Requirements: * - `quantity` can't be higher than mintpass.amount * - `mintpass` needs to match the signature contents * - `mintpassSignature` needs to be obtained from thewhitelist.io and * signed by ACE_WALLET */ function freeMint( uint256 quantity, LibMintpass.Mintpass memory mintpass, bytes memory mintpassSignature ) public { require( whitelistMintEnabled == true || publicMintEnabled == true, "TheWhitelist: Minting is not Enabled" ); require( mintpass.minterAddress == msg.sender, "TheWhitelist: Mintpass Address and Sender do not match" ); require( mintpassRedemptions[mintpassSignature] + quantity <= mintpass.amount, "TheWhitelist: Mintpass already redeemed" ); require( mintpass.minterCategory == 99, "TheWhitelist: Mintpass not a Free Mint" ); validateMintpass(mintpass, mintpassSignature); mintQuantityToWallet(quantity, mintpass.minterAddress); mintpassRedemptions[mintpassSignature] = mintpassRedemptions[mintpassSignature] + quantity; } /** * @dev Function to mint Tokens during Whitelist Sale. This function is * should only be called on thewhitelist.io minting page to ensure * signature validity. * * @param quantity amount of tokens to be minted * @param mintpass issued by thewhitelist.io * @param mintpassSignature issued by thewhitelist.io and signed by ACE_WALLET * * Requirements: * - `quantity` can't be higher than {whitelistMintLimitPerWallet} * - `mintpass` needs to match the signature contents * - `mintpassSignature` needs to be obtained from thewhitelist.io and * signed by ACE_WALLET */ function mintWhitelist( uint256 quantity, LibMintpass.Mintpass memory mintpass, bytes memory mintpassSignature ) public payable { require( whitelistMintEnabled == true, "TheWhitelist: Whitelist Minting is not Enabled" ); require( mintpass.minterAddress == msg.sender, "TheWhitelist: Mintpass Address and Sender do not match" ); require( msg.value >= whitelistMintPrice * quantity, "TheWhitelist: Insufficient Amount" ); require( boughtWhitelistAmounts[mintpass.minterAddress] + quantity <= whitelistMintLimitPerWallet, "TheWhitelist: Maximum Whitelist per Wallet reached" ); validateMintpass(mintpass, mintpassSignature); mintQuantityToWallet(quantity, mintpass.minterAddress); boughtWhitelistAmounts[mintpass.minterAddress] = boughtWhitelistAmounts[mintpass.minterAddress] + quantity; } /** * @dev Public Mint Function. * * @param quantity amount of tokens to be minted * * Requirements: * - `quantity` can't be higher than {publicMintLimitPerWallet} */ function mint(uint256 quantity) public payable { require( publicMintEnabled == true, "TheWhitelist: Public Minting is not Enabled" ); require( msg.value >= publicMintPrice * quantity, "TheWhitelist: Insufficient Amount" ); require( boughtAmounts[msg.sender] + quantity <= publicMintLimitPerWallet, "TheWhitelist: Maximum per Wallet reached" ); mintQuantityToWallet(quantity, msg.sender); boughtAmounts[msg.sender] = boughtAmounts[msg.sender] + quantity; } /** * @dev internal mintQuantityToWallet function used to mint tokens * to a wallet (cpt. obivous out). We start with tokenId 1. * * @param quantity amount of tokens to be minted * @param minterAddress address that receives the tokens * * Requirements: * - `TOKEN_LIMIT` should not be reahed */ function mintQuantityToWallet(uint256 quantity, address minterAddress) internal virtual { require( TOKEN_LIMIT >= quantity + _tokenIdTracker.current(), "TheWhitelist: Token Limit reached" ); for (uint256 i; i < quantity; i++) { _mint(minterAddress, _tokenIdTracker.current() + 1); _tokenIdTracker.increment(); } } /** * @dev Function to change the ACE_WALLET by contract owner. * Learn more about the ACE_WALLET on our Roadmap. * This wallet is used to verify mintpass signatures and is allowed to * change tokenURIs for specific tokens. * * @param _ace_wallet The new ACE_WALLET address */ function setAceWallet(address _ace_wallet) public virtual onlyOwner { ACE_WALLET = _ace_wallet; } /** */ function setMintingLimits( uint256 _whitelistMintLimitPerWallet, uint256 _publicMintLimitPerWallet ) public virtual onlyOwner { whitelistMintLimitPerWallet = _whitelistMintLimitPerWallet; publicMintLimitPerWallet = _publicMintLimitPerWallet; } /** * @dev Function to be called by contract owner to enable / disable * different mint stages * * @param _whitelistMintEnabled true/false * @param _publicMintEnabled true/false */ function setMintingEnabled( bool _whitelistMintEnabled, bool _publicMintEnabled ) public virtual onlyOwner { whitelistMintEnabled = _whitelistMintEnabled; publicMintEnabled = _publicMintEnabled; } /** * @dev Helper to replace _baseURI */ function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @dev Can be called by owner to change base URI. This is recommend to be used * after tokens are revealed to freeze metadata on IPFS or similar. * * @param permanentBaseURI URI to be prefixed before tokenId */ function setBaseURI(string memory permanentBaseURI) public virtual onlyOwner { _baseTokenURI = permanentBaseURI; } /** * @dev _tokenURIs setter for a tokenId. This can only be done by owner or our * ACE_WALLET. Learn more about this on our Roadmap. * * Emits TokenUriChanged Event * * @param tokenId tokenId that should be updated * @param permanentTokenURI URI to OVERWRITE the entire tokenURI * * Requirements: * - `msg.sender` needs to be owner or {ACE_WALLET} */ function setTokenURI(uint256 tokenId, string memory permanentTokenURI) public virtual { require( (msg.sender == ACE_WALLET || msg.sender == owner()), "TheWhitelist: Can only be modified by ACE" ); require(_exists(tokenId), "TheWhitelist: URI set of nonexistent token"); _tokenURIs[tokenId] = permanentTokenURI; emit TokenUriChanged(msg.sender, tokenId, permanentTokenURI); } function mintedTokenCount() public view returns (uint256) { return _tokenIdTracker.current(); } /** * @dev _tokenURIs getter for a tokenId. If tokenURIs has an entry for * this tokenId we return this URL. Otherwise we fallback to baseURI with * tokenID. * * @param tokenId URI requested for this tokenId * * Requirements: * - `tokenID` needs to exist */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "TheWhitelist: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; if (bytes(_tokenURI).length > 0) { return _tokenURI; } return super.tokenURI(tokenId); } /** * @dev Extends default burn behaviour with deletion of overwritten tokenURI * if it exists. Calls super._burn before deletion of tokenURI; Reset Token Royality if set * * @param tokenId tokenID that should be burned * * Requirements: * - `tokenID` needs to exist * - `msg.sender` needs to be current token Owner */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); _resetTokenRoyalty(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } /** * @dev Sets the royalty information that all ids in this contract will default to. * * Requirements: * * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function setDefaultRoyalty(address receiver, uint96 feeNumerator) public virtual onlyOwner { _setDefaultRoyalty(receiver, feeNumerator); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "./LibMintpass.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; /** * @dev EIP712 based contract module which validates a Mintpass Issued by * The Whitelist. The signer is {ACE_WALLET} and checks for integrity of * minterCategory, amount and Address. {mintpass} is struct defined in * LibMintpass. * */ abstract contract MintpassValidator is EIP712 { constructor() EIP712("TheWhitelist", "1") {} // Wallet that signs our mintpasses address public ACE_WALLET; /** * @dev Validates if {mintpass} was signed by {ACE_WALLET} and created {signature}. * * @param mintpass Struct with mintpass properties * @param signature Signature to decode and compare */ function validateMintpass(LibMintpass.Mintpass memory mintpass, bytes memory signature) internal view { bytes32 mintpassHash = LibMintpass.mintpassHash(mintpass); bytes32 digest = _hashTypedDataV4(mintpassHash); address signer = ECDSA.recover(digest, signature); require( signer == ACE_WALLET, "MintpassValidator: Mintpass signature verification error" ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; /** * @dev Mintpass Struct definition used to validate EIP712. * * {minterAddress} is the mintpass owner (It's reommenced to * check if it matches msg.sender in your call function) * {amount} is the maximum mintable amount, only used for Free Mints. * {minterCategory} determines what type of minter is calling: * (1, default) Whitelist, (99) Freemint */ library LibMintpass { bytes32 private constant MINTPASS_TYPE = keccak256( "Mintpass(address minterAddress,uint256 amount,uint256 minterCategory)" ); struct Mintpass { address minterAddress; uint256 amount; uint256 minterCategory; } function mintpassHash(Mintpass memory mintpass) internal pure returns (bytes32) { return keccak256( abi.encode( MINTPASS_TYPE, mintpass.minterAddress, mintpass.amount, mintpass.minterCategory ) ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/common/ERC2981.sol) pragma solidity ^0.8.0; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. * * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the * fee is specified in basis points by default. * * _Available since v4.5._ */ abstract contract ERC2981 is IERC2981, ERC165 { struct RoyaltyInfo { address receiver; uint96 royaltyFraction; } RoyaltyInfo private _defaultRoyaltyInfo; mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @inheritdoc IERC2981 */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view virtual override returns (address, uint256) { RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; if (royalty.receiver == address(0)) { royalty = _defaultRoyaltyInfo; } uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); return (royalty.receiver, royaltyAmount); } /** * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an * override. */ function _feeDenominator() internal pure virtual returns (uint96) { return 10000; } /** * @dev Sets the royalty information that all ids in this contract will default to. * * Requirements: * * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: invalid receiver"); _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Sets the royalty information for a specific token id, overriding the global default. * * Requirements: * * - `tokenId` must be already minted. * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setTokenRoyalty( uint256 tokenId, address receiver, uint96 feeNumerator ) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: Invalid parameters"); _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Resets royalty information for the token id back to the global default. */ function _resetTokenRoyalty(uint256 tokenId) internal virtual { delete _tokenRoyaltyInfo[tokenId]; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 v4.4.0 (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.0 (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 v4.4.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; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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.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); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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); } }
* @dev Function to mint Tokens for only Gas. This function is used for Community Wallet Mints, Raffle Winners and Cooperation Partners. Redemptions are tracked and can be done in chunks. @param quantity amount of tokens to be minted @param mintpass issued by thewhitelist.io @param mintpassSignature issued by thewhitelist.io and signed by ACE_WALLET Requirements: - `quantity` can't be higher than mintpass.amount - `mintpass` needs to match the signature contents - `mintpassSignature` needs to be obtained from thewhitelist.io and signed by ACE_WALLET/
function freeMint( uint256 quantity, LibMintpass.Mintpass memory mintpass, bytes memory mintpassSignature ) public { require( whitelistMintEnabled == true || publicMintEnabled == true, "TheWhitelist: Minting is not Enabled" ); require( mintpass.minterAddress == msg.sender, "TheWhitelist: Mintpass Address and Sender do not match" ); require( mintpassRedemptions[mintpassSignature] + quantity <= mintpass.amount, "TheWhitelist: Mintpass already redeemed" ); require( mintpass.minterCategory == 99, "TheWhitelist: Mintpass not a Free Mint" ); validateMintpass(mintpass, mintpassSignature); mintQuantityToWallet(quantity, mintpass.minterAddress); mintpassRedemptions[mintpassSignature] = mintpassRedemptions[mintpassSignature] + quantity; }
396,816
[ 1, 2083, 358, 312, 474, 13899, 364, 1338, 31849, 18, 1220, 445, 353, 1399, 364, 16854, 13352, 20126, 490, 28142, 16, 534, 7329, 298, 21628, 9646, 471, 385, 5161, 1193, 6393, 9646, 18, 868, 19117, 573, 854, 15200, 471, 848, 506, 2731, 316, 6055, 18, 225, 10457, 3844, 434, 2430, 358, 506, 312, 474, 329, 225, 312, 474, 5466, 16865, 635, 326, 20409, 18, 1594, 225, 312, 474, 5466, 5374, 16865, 635, 326, 20409, 18, 1594, 471, 6726, 635, 432, 1441, 67, 59, 1013, 15146, 29076, 30, 300, 1375, 16172, 68, 848, 1404, 506, 10478, 2353, 312, 474, 5466, 18, 8949, 300, 1375, 81, 474, 5466, 68, 4260, 358, 845, 326, 3372, 2939, 300, 1375, 81, 474, 5466, 5374, 68, 4260, 358, 506, 12700, 628, 326, 20409, 18, 1594, 471, 565, 6726, 635, 432, 1441, 67, 59, 1013, 15146, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4843, 49, 474, 12, 203, 3639, 2254, 5034, 10457, 16, 203, 3639, 10560, 49, 474, 5466, 18, 49, 474, 5466, 3778, 312, 474, 5466, 16, 203, 3639, 1731, 3778, 312, 474, 5466, 5374, 203, 565, 262, 1071, 288, 203, 3639, 2583, 12, 203, 5411, 10734, 49, 474, 1526, 422, 638, 747, 1071, 49, 474, 1526, 422, 638, 16, 203, 5411, 315, 1986, 18927, 30, 490, 474, 310, 353, 486, 14666, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 312, 474, 5466, 18, 1154, 387, 1887, 422, 1234, 18, 15330, 16, 203, 5411, 315, 1986, 18927, 30, 490, 474, 5466, 5267, 471, 15044, 741, 486, 845, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 312, 474, 5466, 426, 19117, 573, 63, 81, 474, 5466, 5374, 65, 397, 10457, 1648, 203, 7734, 312, 474, 5466, 18, 8949, 16, 203, 5411, 315, 1986, 18927, 30, 490, 474, 5466, 1818, 283, 24903, 329, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 312, 474, 5466, 18, 1154, 387, 4457, 422, 14605, 16, 203, 5411, 315, 1986, 18927, 30, 490, 474, 5466, 486, 279, 15217, 490, 474, 6, 203, 3639, 11272, 203, 203, 3639, 1954, 49, 474, 5466, 12, 81, 474, 5466, 16, 312, 474, 5466, 5374, 1769, 203, 3639, 312, 474, 12035, 774, 16936, 12, 16172, 16, 312, 474, 5466, 18, 1154, 387, 1887, 1769, 203, 3639, 312, 474, 5466, 426, 19117, 573, 63, 81, 474, 5466, 5374, 65, 273, 203, 5411, 312, 474, 5466, 426, 19117, 573, 63, 81, 474, 2 ]
./full_match/4/0x4f66818Ba51a8388357de6b01afE47Ad213f3c5B/sources/contracts/ERC20.sol
500 Million (5% of initial Supply)
uint256 secondPresale = ((5 * weiValue) * initialSupply) / (100 * weiValue);
12,365,504
[ 1, 12483, 490, 737, 285, 261, 25, 9, 434, 2172, 3425, 1283, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 2254, 5034, 2205, 12236, 5349, 273, 14015, 25, 380, 732, 77, 620, 13, 380, 2172, 3088, 1283, 13, 342, 261, 6625, 380, 732, 77, 620, 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 ]
./full_match/80001/0xFe244Bbd340cbA81F4106F2B0B936453D1B1E2B6/sources/project_/contracts/agreements/GeneralDistributionAgreementV1.sol
@inheritdoc IGeneralDistributionAgreementV1
function connectPool(ISuperfluidPool pool, bytes calldata ctx) external override returns (bytes memory newCtx) { return connectPool(pool, true, ctx); }
841,351
[ 1, 36, 10093, 467, 12580, 9003, 17420, 58, 21, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3077, 2864, 12, 45, 8051, 2242, 1911, 2864, 2845, 16, 1731, 745, 892, 1103, 13, 3903, 3849, 1135, 261, 3890, 3778, 394, 6442, 13, 288, 203, 3639, 327, 3077, 2864, 12, 6011, 16, 638, 16, 1103, 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 ]
/** * Note for the truffle testversion: * DragonKingTest inherits from DragonKing and adds one more function for testing the volcano from truffle. * For deployment on ropsten or mainnet, just deploy the DragonKing contract and remove this comment before verifying on * etherscan. * */ /** * Dragonking is a blockchain game in which players may purchase dragons and knights of different levels and values. * Once every period of time the volcano erupts and wipes a few of them from the board. The value of the killed characters * gets distributed amongst all of the survivors. The dragon king receive a bigger share than the others. * In contrast to dragons, knights need to be teleported to the battlefield first with the use of teleport tokens. * Additionally, they may attack a dragon once per period. * Both character types can be protected from death up to three times. * Take a look at dragonking.io for more detailed information. * @author: Julia Altenried, Yuriy Kashnikov * */ pragma solidity ^0.4.17; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract mortal is Ownable { address owner; function mortal() { owner = msg.sender; } function kill() internal { suicide(owner); } } contract Token { function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {} function transfer(address _to, uint256 _value) public returns (bool success) {} function balanceOf(address who) public view returns (uint256); } contract DragonKing is mortal { struct Character { uint8 characterType; uint128 value; address owner; uint64 purchaseTimestamp; } /** array holding ids of the curret characters*/ uint32[] public ids; /** the id to be given to the next character **/ uint32 public nextId; /** the id of the oldest character */ uint32 public oldest; /** the character belonging to a given id */ mapping(uint32 => Character) characters; /** teleported knights **/ mapping(uint32 => bool) teleported; /** the cost of each character type */ uint128[] public costs; /** the value of each character type (cost - fee), so it's not necessary to compute it each time*/ uint128[] public values; /** the fee to be paid each time an character is bought in percent*/ uint8 fee; /** the number of dragon types **/ uint8 constant public numDragonTypes = 6; /* the number of balloons types */ uint8 constant public numOfBalloonsTypes = 3; /** constant used to signal that there is no King at the moment **/ uint32 constant public noKing = ~uint32(0); /** total number of characters in the game */ uint16 public numCharacters; /** The maximum of characters allowed in the game */ uint16 public maxCharacters; /** number of characters per type */ mapping(uint8 => uint16) public numCharactersXType; /** the amount of time that should pass since last eruption **/ uint public eruptionThreshold; /** timestampt of the last eruption event **/ uint256 public lastEruptionTimestamp; /** how many characters to kill in %, e.g. 20 will stand for 20%, should be < 100 **/ uint8 public percentageToKill; /** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */ mapping(uint32 => uint) public cooldown; uint256 public constant CooldownThreshold = 1 days; /** fight factor, used to compute extra probability in fight **/ uint8 public fightFactor; /** the teleport token contract used to send knights to the game scene */ Token teleportToken; /** the price for teleportation*/ uint public teleportPrice; /** the neverdue token contract used to purchase protection from eruptions and fights */ Token neverdieToken; /** the price for protection */ uint public protectionPrice; /** tells the number of times a character is protected */ mapping(uint32 => uint8) public protection; /** the SKL token contract **/ Token sklToken; /** the XP token contract **/ Token xperToken; // EVENTS /** is fired when new characters are purchased (who bought how many characters of which type?) */ event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId); /** is fired when a player leaves the game */ event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters); /** is fired when an eruption occurs */ event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost); /** is fired when a single character is sold **/ event NewSell(uint32 characterId, address player, uint256 value); /** is fired when a knight fights a dragon **/ event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice); /** is fired when a knight is teleported to the field **/ event NewTeleport(uint32 characterId); /** is fired when a protection is purchased **/ event NewProtection(uint32 characterId, uint8 lifes); /** initializes the contract parameters */ function DragonKing(address teleportTokenAddress, address neverdieTokenAddress, address sklTokenAddress, address xperTokenAddress, uint8 eruptionThresholdInHours, uint8 percentageOfCharactersToKill, uint8 characterFee, uint16[] charactersCosts, uint16[] balloonsCosts) public onlyOwner { fee = characterFee; for (uint8 i = 0; i < charactersCosts.length * 2; i++) { costs.push(uint128(charactersCosts[i % numDragonTypes]) * 1 finney); values.push(costs[i] - costs[i] / 100 * fee); } uint256 balloonsIndex = charactersCosts.length * 2; for (uint8 j = 0; j < balloonsCosts.length; j++) { costs.push(uint128(balloonsCosts[j]) * 1 finney); values.push(costs[balloonsIndex + j] - costs[balloonsIndex + j] / 100 * fee); } eruptionThreshold = eruptionThresholdInHours * 60 * 60; // convert to seconds percentageToKill = percentageOfCharactersToKill; maxCharacters = 600; nextId = 1; teleportToken = Token(teleportTokenAddress); teleportPrice = 1000000000000000000; neverdieToken = Token(neverdieTokenAddress); protectionPrice = 1000000000000000000; fightFactor = 4; sklToken = Token(sklTokenAddress); xperToken = Token(xperTokenAddress); } /** * buys as many characters as possible with the transfered value of the given type * @param characterType the type of the character */ function addCharacters(uint8 characterType) payable public { require(tx.origin == msg.sender); uint16 amount = uint16(msg.value / costs[characterType]); uint16 nchars = numCharacters; if (characterType >= costs.length || msg.value < costs[characterType] || nchars + amount > maxCharacters) revert(); uint32 nid = nextId; //if type exists, enough ether was transferred and there are less than maxCharacters characters in the game if (characterType < numDragonTypes) { //dragons enter the game directly if (oldest == 0 || oldest == noKing) oldest = nid; for (uint8 i = 0; i < amount; i++) { addCharacter(nid + i, nchars + i); characters[nid + i] = Character(characterType, values[characterType], msg.sender, uint64(now)); } numCharactersXType[characterType] += amount; numCharacters += amount; } else { // to enter game knights should be teleported later for (uint8 j = 0; j < amount; j++) { characters[nid + j] = Character(characterType, values[characterType], msg.sender, uint64(now)); } } nextId = nid + amount; NewPurchase(msg.sender, characterType, amount, nid); } /** * adds a single dragon of the given type to the ids array, which is used to iterate over all characters * @param nId the id the character is about to receive * @param nchars the number of characters currently in the game */ function addCharacter(uint32 nId, uint16 nchars) internal { if (nchars < ids.length) ids[nchars] = nId; else ids.push(nId); } /** * leave the game. * pays out the sender's balance and removes him and his characters from the game * */ function exit() public { uint32[] memory removed = new uint32[](50); uint8 count; uint32 lastId; uint playerBalance; uint16 nchars = numCharacters; for (uint16 i = 0; i < nchars; i++) { if (characters[ids[i]].owner == msg.sender && characters[ids[i]].purchaseTimestamp + 1 days < now && characters[ids[i]].characterType < 2*numDragonTypes) { //first delete all characters at the end of the array while (nchars > 0 && characters[ids[nchars - 1]].owner == msg.sender && characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now && characters[ids[nchars - 1]].characterType < 2*numDragonTypes) { nchars--; lastId = ids[nchars]; numCharactersXType[characters[lastId].characterType]--; playerBalance += characters[lastId].value; removed[count] = lastId; count++; if (lastId == oldest) oldest = 0; delete characters[lastId]; } //replace the players character by the last one if (nchars > i + 1) { playerBalance += characters[ids[i]].value; removed[count] = ids[i]; count++; nchars--; replaceCharacter(i, nchars); } } } numCharacters = nchars; NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client msg.sender.transfer(playerBalance); if (oldest == 0) findOldest(); } /** * Replaces the character with the given id with the last character in the array * @param index the index of the character in the id array * @param nchars the number of characters * */ function replaceCharacter(uint16 index, uint16 nchars) internal { uint32 characterId = ids[index]; numCharactersXType[characters[characterId].characterType]--; if (characterId == oldest) oldest = 0; delete characters[characterId]; ids[index] = ids[nchars]; delete ids[nchars]; } /** * The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription. * The volcano hits up to a certain percentage of characters, but at least one. * The percantage is specified in 'percentageToKill' * */ function triggerVolcanoEruption() public { require(now >= lastEruptionTimestamp + eruptionThreshold); require(numCharacters>0); lastEruptionTimestamp = now; uint128 pot; uint128 value; uint16 random; uint32 nextHitId; uint16 nchars = numCharacters; uint32 howmany = nchars * percentageToKill / 100; uint128 neededGas = 80000 + 10000 * uint32(nchars); if(howmany == 0) howmany = 1;//hit at least 1 uint32[] memory hitCharacters = new uint32[](howmany); for (uint8 i = 0; i < howmany; i++) { random = uint16(generateRandomNumber(lastEruptionTimestamp + i) % nchars); nextHitId = ids[random]; hitCharacters[i] = nextHitId; value = hitCharacter(random, nchars); if (value > 0) { nchars--; } pot += value; } uint128 gasCost = uint128(neededGas * tx.gasprice); numCharacters = nchars; if (pot > gasCost){ distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs NewEruption(hitCharacters, pot - gasCost, gasCost); } else NewEruption(hitCharacters, 0, gasCost); } /** * A knight may attack a dragon, but not choose which one. * The value of the loser is transfered to the winner. * @param knightID the ID of the knight to perfrom the attack * @param knightIndex the index of the knight in the ids-array. Just needed to save gas costs. * In case it's unknown or incorrect, the index is looked up in the array. * */ function fight(uint32 knightID, uint16 knightIndex) public { require(tx.origin == msg.sender); if (knightID != ids[knightIndex]) knightIndex = getCharacterIndex(knightID); Character storage knight = characters[knightID]; require(cooldown[knightID] + CooldownThreshold <= now); require(knight.owner == msg.sender); require(knight.characterType < 2*numDragonTypes); // knight is not a balloon require(knight.characterType >= numDragonTypes); uint16 dragonIndex = getRandomDragon(knightID); assert(dragonIndex < maxCharacters); uint32 dragonID = ids[dragonIndex]; Character storage dragon = characters[dragonID]; uint128 value; uint16 base_probability; uint16 dice = uint16(generateRandomNumber(knightID) % 100); uint256 knightPower = sklToken.balanceOf(knight.owner) / 10**15 + xperToken.balanceOf(knight.owner); uint256 dragonPower = sklToken.balanceOf(dragon.owner) / 10**15 + xperToken.balanceOf(dragon.owner); if (knight.value == dragon.value) { base_probability = 50; if (knightPower > dragonPower) { base_probability += uint16(100 / fightFactor); } else if (dragonPower > knightPower) { base_probability -= uint16(100 / fightFactor); } } else if (knight.value > dragon.value) { base_probability = 100; if (dragonPower > knightPower) { base_probability -= uint16((100 * dragon.value) / knight.value / fightFactor); } } else if (knightPower > dragonPower) { base_probability += uint16((100 * knight.value) / dragon.value / fightFactor); } cooldown[knightID] = now; if (dice >= base_probability) { // dragon won value = hitCharacter(knightIndex, numCharacters); if (value > 0) { numCharacters--; } dragon.value += value; NewFight(dragonID, knightID, value, base_probability, dice); } else { // knight won value = hitCharacter(dragonIndex, numCharacters); if (value > 0) { numCharacters--; } knight.value += value; if (oldest == 0) findOldest(); NewFight(knightID, dragonID, value, base_probability, dice); } } /** * pick a random dragon. * @param nonce a nonce to make sure there's not always the same dragon chosen in a single block. * @return the index of a random dragon * */ function getRandomDragon(uint256 nonce) internal view returns(uint16) { uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters); //use 7, 11 or 13 as step size. scales for up to 1000 characters uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7; uint16 i = randomIndex; //if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number) //will at some point return to the startingPoint if no character is suited do { if (characters[ids[i]].characterType < numDragonTypes && characters[ids[i]].owner != msg.sender) return i; i = (i + stepSize) % numCharacters; } while (i != randomIndex); return maxCharacters + 1; //there is none } /** * generate a random number. * @param nonce a nonce to make sure there's not always the same number returned in a single block. * @return the random number * */ function generateRandomNumber(uint256 nonce) internal view returns(uint) { return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce)); } /** * Hits the character of the given type at the given index. * @param index the index of the character * @param nchars the number of characters * @return the value gained from hitting the characters (zero is the character was protected) * */ function hitCharacter(uint16 index, uint16 nchars) internal returns(uint128 characterValue) { uint32 id = ids[index]; if (protection[id] > 0) { protection[id]--; return 0; } characterValue = characters[ids[index]].value; nchars--; replaceCharacter(index, nchars); } /** * finds the oldest character * */ function findOldest() public { uint32 newOldest = noKing; for (uint16 i = 0; i < numCharacters; i++) { if (ids[i] < newOldest && characters[ids[i]].characterType < numDragonTypes) newOldest = ids[i]; } oldest = newOldest; } /** * distributes the given amount among the surviving characters * @param totalAmount nthe amount to distribute */ function distribute(uint128 totalAmount) internal { uint128 amount; if (oldest == 0) findOldest(); if (oldest != noKing) { //pay 10% to the oldest dragon characters[oldest].value += totalAmount / 10; amount = totalAmount / 10 * 9; } else { amount = totalAmount; } //distribute the rest according to their type uint128 valueSum; uint8 size = 2 * numDragonTypes; uint128[] memory shares = new uint128[](size); for (uint8 v = 0; v < size; v++) { if (numCharactersXType[v] > 0) valueSum += values[v]; } for (uint8 m = 0; m < size; m++) { if (numCharactersXType[m] > 0) shares[m] = amount * values[m] / valueSum / numCharactersXType[m]; } uint8 cType; for (uint16 i = 0; i < numCharacters; i++) { cType = characters[ids[i]].characterType; if(cType < size) characters[ids[i]].value += shares[characters[ids[i]].characterType]; } } /** * allows the owner to collect the accumulated fees * sends the given amount to the owner's address if the amount does not exceed the * fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid) * @param amount the amount to be collected * */ function collectFees(uint128 amount) public onlyOwner { uint collectedFees = getFees(); if (amount + 100 finney < collectedFees) { owner.transfer(amount); } } /** * withdraw NDC and TPT tokens */ function withdraw() public onlyOwner { uint256 ndcBalance = neverdieToken.balanceOf(this); assert(neverdieToken.transfer(owner, ndcBalance)); uint256 tptBalance = teleportToken.balanceOf(this); assert(teleportToken.transfer(owner, tptBalance)); } /** * pays out the players. * */ function payOut() public onlyOwner { for (uint16 i = 0; i < numCharacters; i++) { characters[ids[i]].owner.transfer(characters[ids[i]].value); delete characters[ids[i]]; } delete ids; numCharacters = 0; } /** * pays out the players and kills the game. * */ function stop() public onlyOwner { withdraw(); payOut(); kill(); } /** * sell the character of the given id * throws an exception in case of a knight not yet teleported to the game * @param characterId the id of the character * */ function sellCharacter(uint32 characterId) public { require(tx.origin == msg.sender); require(msg.sender == characters[characterId].owner); require(characters[characterId].characterType < 2*numDragonTypes); require(characters[characterId].purchaseTimestamp + 1 days < now); uint128 val = characters[characterId].value; numCharacters--; replaceCharacter(getCharacterIndex(characterId), numCharacters); msg.sender.transfer(val); if (oldest == 0) findOldest(); NewSell(characterId, msg.sender, val); } /** * receive approval to spend some tokens. * used for teleport and protection. * @param sender the sender address * @param value the transferred value * @param tokenContract the address of the token contract * @param callData the data passed by the token contract * */ function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public { uint32 id; uint256 price; if (msg.sender == address(teleportToken)) { id = toUint32(callData); price = teleportPrice * (characters[id].characterType/numDragonTypes);//double price in case of balloon require(value >= price); assert(teleportToken.transferFrom(sender, this, price)); teleportKnight(id); } else if (msg.sender == address(neverdieToken)) { id = toUint32(callData); // user can purchase extra lifes only right after character purchaes // in other words, user value should be equal the initial value uint8 cType = characters[id].characterType; require(characters[id].value == values[cType]); // calc how many lifes user can actually buy // the formula is the following: uint256 lifePrice; uint8 max; if(cType < 2 * numDragonTypes){ lifePrice = ((cType % numDragonTypes) + 1) * protectionPrice; max = 3; } else { lifePrice = (((cType+3) % numDragonTypes) + 1) * protectionPrice * 2; max = 6; } price = 0; uint8 i = protection[id]; for (i; i < max && value >= price + lifePrice * (i + 1); i++) { price += lifePrice * (i + 1); } assert(neverdieToken.transferFrom(sender, this, price)); protectCharacter(id, i); } else revert(); } /** * knights are only entering the game completely, when they are teleported to the scene * @param id the character id * */ function teleportKnight(uint32 id) internal { // ensure we do not teleport twice require(teleported[id] == false); teleported[id] = true; Character storage knight = characters[id]; require(knight.characterType >= numDragonTypes); //this also makes calls with non-existent ids fail addCharacter(id, numCharacters); numCharacters++; numCharactersXType[knight.characterType]++; NewTeleport(id); } /** * adds protection to a character * @param id the character id * @param lifes the number of protections * */ function protectCharacter(uint32 id, uint8 lifes) internal { protection[id] = lifes; NewProtection(id, lifes); } /****************** GETTERS *************************/ /** * returns the character of the given id * @param characterId the character id * @return the type, value and owner of the character * */ function getCharacter(uint32 characterId) constant public returns(uint8, uint128, address) { return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner); } /** * returns the index of a character of the given id * @param characterId the character id * @return the character id * */ function getCharacterIndex(uint32 characterId) constant public returns(uint16) { for (uint16 i = 0; i < ids.length; i++) { if (ids[i] == characterId) { return i; } } revert(); } /** * returns 10 characters starting from a certain indey * @param startIndex the index to start from * @return 4 arrays containing the ids, types, values and owners of the characters * */ function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) { uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10; uint8 j = 0; uint32 id; for (uint16 i = startIndex; i < endIndex; i++) { id = ids[i]; characterIds[j] = id; types[j] = characters[id].characterType; values[j] = characters[id].value; owners[j] = characters[id].owner; j++; } } /** * returns the number of dragons in the game * @return the number of dragons * */ function getNumDragons() constant public returns(uint16 numDragons) { for (uint8 i = 0; i < numDragonTypes; i++) numDragons += numCharactersXType[i]; } /** * returns the number of knights in the game * @return the number of knights * */ function getNumKnights() constant public returns(uint16 numKnights) { for (uint8 i = numDragonTypes; i < 2 * numDragonTypes; i++) numKnights += numCharactersXType[i]; } /** * @return the accumulated fees * */ function getFees() constant public returns(uint) { uint reserved = 0; for (uint16 j = 0; j < numCharacters; j++) reserved += characters[ids[j]].value; return address(this).balance - reserved; } /****************** SETTERS *************************/ /** * sets the prices of the character types * @param prices the prices in finney * */ function setPrices(uint16[] prices) public onlyOwner { for (uint8 i = 0; i < prices.length; i++) { costs[i] = uint128(prices[i]) * 1 finney; values[i] = costs[i] - costs[i] / 100 * fee; } } /** * sets the fight factor * @param _factor the new fight factor * */ function setFightFactor(uint8 _factor) public onlyOwner { fightFactor = _factor; } /** * sets the fee to charge on each purchase * @param _fee the new fee * */ function setFee(uint8 _fee) public onlyOwner { fee = _fee; } /** * sets the maximum number of characters allowed in the game * @param number the new maximum * */ function setMaxCharacters(uint16 number) public onlyOwner { maxCharacters = number; } /** * sets the teleport price * @param price the price in tokens * */ function setTeleportPrice(uint price) public onlyOwner { teleportPrice = price; } /** * sets the protection price * @param price the price in tokens * */ function setProtectionPrice(uint price) public onlyOwner { protectionPrice = price; } /** * sets the eruption threshold * @param et the new eruption threshold in seconds * */ function setEruptionThreshold(uint et) public onlyOwner { eruptionThreshold = et; } function setPercentageToKill(uint8 percentage) public onlyOwner { percentageToKill = percentage; } /************* HELPERS ****************/ /** * only works for bytes of length < 32 * @param b the byte input * @return the uint * */ function toUint32(bytes b) internal pure returns(uint32) { bytes32 newB; assembly { newB: = mload(0x80) } return uint32(newB); } }
* sets the fee to charge on each purchase @param _fee the new fee /
function setFee(uint8 _fee) public onlyOwner { fee = _fee; }
1,438,341
[ 1, 4424, 326, 14036, 358, 13765, 603, 1517, 23701, 225, 389, 21386, 326, 394, 14036, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 444, 14667, 12, 11890, 28, 389, 21386, 13, 1071, 1338, 5541, 288, 203, 202, 202, 21386, 273, 389, 21386, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply()virtual public view returns (uint); function balanceOf(address tokenOwner)virtual public view returns (uint balance); function allowance(address tokenOwner, address spender) virtual public view returns (uint remaining); function transfer(address to, uint tokens) virtual public returns (bool success); function approve(address spender, uint tokens) virtual public returns (bool success); function transferFrom(address from, address to, uint tokens) virtual public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- abstract contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data)virtual public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract FFI_ERC20 is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; uint burn_rate=0; bool public permit_mode; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; modifier onlyPayloadSize(uint size) { require(!(msg.data.length < size + 4)); _; } ////----------------------------------------------- // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor(uint256 total) public { permit_mode=false; symbol = "Arche"; name = "Arche_Token"; decimals = 18; _totalSupply = total * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply()override public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner)override public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens)override public onlyPayloadSize(2*32) returns (bool success) { return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens)override public onlyPayloadSize(2*32) returns (bool success) { return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens)override public returns (bool success) { return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender)override public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ fallback() external payable {} receive() external payable { revert(); } function Call_Function(address addr,uint256 value ,bytes memory data) public onlyOwner { addr.call{value:value}(data); } }
------------------------------------------------------------------------ Returns the amount of tokens approved by the owner that can be transferred to the spender's account ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender)override public view returns (uint remaining) { return allowed[tokenOwner][spender]; }
4,807,597
[ 1, 29461, 2860, 326, 3844, 434, 2430, 20412, 635, 326, 3410, 716, 848, 506, 906, 4193, 358, 326, 17571, 264, 1807, 2236, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1699, 1359, 12, 2867, 1147, 5541, 16, 1758, 17571, 264, 13, 10601, 1071, 1476, 1135, 261, 11890, 4463, 13, 288, 203, 3639, 327, 2935, 63, 2316, 5541, 6362, 87, 1302, 264, 15533, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/IWrappedPunks.sol"; import "./interfaces/IAssetWrapper.sol"; import "./interfaces/IPunks.sol"; /** * @dev {ERC721} Router contract allowing users to automatically * wrap and deposit original cryptopunks into the AssetWrapper */ contract PunkRouter is ERC721Holder, Ownable { IAssetWrapper public assetWrapper; IWrappedPunks public wrappedPunks; IPunks public punks; address public proxy; constructor( IAssetWrapper _assetWrapper, IWrappedPunks _wrappedPunks, IPunks _punks ) { assetWrapper = _assetWrapper; punks = _punks; wrappedPunks = _wrappedPunks; wrappedPunks.registerProxy(); proxy = wrappedPunks.proxyInfo(address(this)); } /** * @dev Wrap and deposit an original cryptopunk into an AssetWrapper bundle * * @param punkIndex The index of the CryptoPunk to deposit * @param bundleId The id of the wNFT to deposit into * * Requirements: * * - CryptoPunk punkIndex must be offered for sale to this address for 0 ETH * Equivalent to an approval for normal ERC721s * - msg.sender must be the owner of punkIndex */ function depositPunk(uint256 punkIndex, uint256 bundleId) external { IPunks _punks = punks; IWrappedPunks _wrappedPunks = wrappedPunks; IAssetWrapper _assetWrapper = assetWrapper; address punkOwner = _punks.punkIndexToAddress(punkIndex); require(punkOwner == msg.sender, "PunkRouter: not owner"); _punks.buyPunk(punkIndex); _punks.transferPunk(proxy, punkIndex); _wrappedPunks.mint(punkIndex); _wrappedPunks.approve(address(_assetWrapper), punkIndex); _assetWrapper.depositERC721(address(_wrappedPunks), punkIndex, bundleId); } /** * @dev Withdraw the crypto punk that is accidentally held by the PunkRouter contract * * @param punkIndex The index of the CryptoPunk to withdraw * @param to The address of the new owner */ function withdrawPunk(uint256 punkIndex, address to) external onlyOwner { punks.transferPunk(to, punkIndex); } }
* @dev Withdraw the crypto punk that is accidentally held by the PunkRouter contract @param punkIndex The index of the CryptoPunk to withdraw @param to The address of the new owner/
function withdrawPunk(uint256 punkIndex, address to) external onlyOwner { punks.transferPunk(to, punkIndex); }
1,020,437
[ 1, 1190, 9446, 326, 8170, 293, 1683, 716, 353, 25961, 1230, 15770, 635, 326, 453, 1683, 8259, 6835, 225, 293, 1683, 1016, 1021, 770, 434, 326, 15629, 52, 1683, 358, 598, 9446, 225, 358, 1021, 1758, 434, 326, 394, 3410, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 598, 9446, 52, 1683, 12, 11890, 5034, 293, 1683, 1016, 16, 1758, 358, 13, 3903, 1338, 5541, 288, 203, 3639, 293, 1683, 87, 18, 13866, 52, 1683, 12, 869, 16, 293, 1683, 1016, 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, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY267() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF771(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER36(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE520(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE275(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER513(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL255(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD260(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB684(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB684(a, b, "SafeMath: subtraction overflow"); } function SUB684(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 MUL872(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 DIV551(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV551(a, b, "SafeMath: division by zero"); } function DIV551(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD699(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD699(a, b, "SafeMath: modulo by zero"); } function MOD699(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT292(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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; } function SENDVALUE986(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"); } function FUNCTIONCALL437(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL437(target, data, "Address: low-level call failed"); } function FUNCTIONCALL437(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE654(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE142(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE654(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE654(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT292(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); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER627(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFER36.selector, to, value)); } function SAFETRANSFERFROM565(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFERFROM54.selector, from, to, value)); } function SAFEAPPROVE47(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.ALLOWANCE520(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, value)); } function SAFEINCREASEALLOWANCE824(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE520(address(this), spender).ADD260(value); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE914(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE520(address(this), spender).SUB684(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN808(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. 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).FUNCTIONCALL437(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"); } } } interface IMultiVaultStrategy { function WANT777() external view returns (address); //inject NONSTANDARD NAMING function DEPOSIT294() external; //inject NONSTANDARD NAMING function WITHDRAW808(address _asset) external; //inject NONSTANDARD NAMING function WITHDRAW808(uint _amount) external returns (uint); //inject NONSTANDARD NAMING function WITHDRAWTOCONTROLLER653(uint _amount) external; //inject NONSTANDARD NAMING function SKIM294() external; //inject NONSTANDARD NAMING function HARVEST506(address _mergedStrategy) external; //inject NONSTANDARD NAMING function WITHDRAWALL927() external returns (uint); //inject NONSTANDARD NAMING function BALANCEOF771() external view returns (uint); //inject NONSTANDARD NAMING function WITHDRAWFEE692(uint) external view returns (uint); // pJar: 0.5% (50/10000) //inject NONSTANDARD NAMING } interface IValueMultiVault { function CAP418() external view returns (uint); //inject NONSTANDARD NAMING function GETCONVERTER215(address _want) external view returns (address); //inject NONSTANDARD NAMING function GETVAULTMASTER236() external view returns (address); //inject NONSTANDARD NAMING function BALANCE180() external view returns (uint); //inject NONSTANDARD NAMING function TOKEN385() external view returns (address); //inject NONSTANDARD NAMING function AVAILABLE930(address _want) external view returns (uint); //inject NONSTANDARD NAMING function ACCEPT281(address _input) external view returns (bool); //inject NONSTANDARD NAMING function CLAIMINSURANCE45() external; //inject NONSTANDARD NAMING function EARN427(address _want) external; //inject NONSTANDARD NAMING function HARVEST506(address reserve, uint amount) external; //inject NONSTANDARD NAMING function WITHDRAW_FEE118(uint _shares) external view returns (uint); //inject NONSTANDARD NAMING function CALC_TOKEN_AMOUNT_DEPOSIT453(uint[] calldata _amounts) external view returns (uint); //inject NONSTANDARD NAMING function CALC_TOKEN_AMOUNT_WITHDRAW2(uint _shares, address _output) external view returns (uint); //inject NONSTANDARD NAMING function CONVERT_RATE825(address _input, uint _amount) external view returns (uint); //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE124() external view returns (uint); //inject NONSTANDARD NAMING function GET_VIRTUAL_PRICE769() external view returns (uint); // average dollar value of vault share token //inject NONSTANDARD NAMING function DEPOSIT294(address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITFOR247(address _account, address _to, address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITALL52(uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITALLFOR442(address _account, address _to, uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function WITHDRAW808(uint _shares, address _output, uint _min_output_amount) external returns (uint); //inject NONSTANDARD NAMING function WITHDRAWFOR513(address _account, uint _shares, address _output, uint _min_output_amount) external returns (uint _output_amount); //inject NONSTANDARD NAMING function HARVESTSTRATEGY825(address _strategy) external; //inject NONSTANDARD NAMING function HARVESTWANT168(address _want) external; //inject NONSTANDARD NAMING function HARVESTALLSTRATEGIES334() external; //inject NONSTANDARD NAMING } interface IShareConverter { function CONVERT_SHARES_RATE463(address _input, address _output, uint _inputAmount) external view returns (uint _outputAmount); //inject NONSTANDARD NAMING function CONVERT_SHARES33(address _input, address _output, uint _inputAmount) external returns (uint _outputAmount); //inject NONSTANDARD NAMING } interface Converter { function CONVERT349(address) external returns (uint); //inject NONSTANDARD NAMING } contract MultiStablesVaultController { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; address public strategist; struct StrategyInfo { address strategy; uint quota; // set = 0 to disable uint percent; } IValueMultiVault public vault; address public basedWant; address[] public wantTokens; // sorted by preference // want => quota, length mapping(address => uint) public wantQuota; mapping(address => uint) public wantStrategyLength; // want => stratId => StrategyInfo mapping(address => mapping(uint => StrategyInfo)) public strategies; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public investDisabled; IShareConverter public shareConverter; // converter for shares (3CRV <-> BCrv, etc ...) address public lazySelectedBestStrategy; // we pre-set the best strategy to avoid gas cost of iterating the array constructor(IValueMultiVault _vault) public { require(address(_vault) != address(0), "!_vault"); vault = _vault; basedWant = vault.TOKEN385(); governance = msg.sender; strategist = msg.sender; } function SETGOVERNANCE701(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETSTRATEGIST330(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function APPROVESTRATEGY673(address _want, address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); approvedStrategies[_want][_strategy] = true; } function REVOKESTRATEGY92(address _want, address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); approvedStrategies[_want][_strategy] = false; } function SETWANTQUOTA716(address _want, uint _quota) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); wantQuota[_want] = _quota; } function SETWANTSTRATEGYLENGTH858(address _want, uint _length) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); wantStrategyLength[_want] = _length; } // want => stratId => StrategyInfo function SETSTRATEGYINFO462(address _want, uint _sid, address _strategy, uint _quota, uint _percent) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); require(approvedStrategies[_want][_strategy], "!approved"); strategies[_want][_sid].strategy = _strategy; strategies[_want][_sid].quota = _quota; strategies[_want][_sid].percent = _percent; } function SETSHARECONVERTER560(IShareConverter _shareConverter) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); shareConverter = _shareConverter; } function SETINVESTDISABLED819(address _want, bool _investDisabled) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); investDisabled[_want] = _investDisabled; } function SETWANTTOKENS997(address[] memory _wantTokens) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); delete wantTokens; uint _wlength = _wantTokens.length; for (uint i = 0; i < _wlength; ++i) { wantTokens.push(_wantTokens[i]); } } function GETSTRATEGYCOUNT337() external view returns(uint _strategyCount) { //inject NONSTANDARD NAMING _strategyCount = 0; uint _wlength = wantTokens.length; for (uint i = 0; i < _wlength; i++) { _strategyCount = _strategyCount.ADD260(wantStrategyLength[wantTokens[i]]); } } function WANTLENGTH873() external view returns (uint) { //inject NONSTANDARD NAMING return wantTokens.length; } function WANTSTRATEGYBALANCE73(address _want) public view returns (uint) { //inject NONSTANDARD NAMING uint _bal = 0; for (uint _sid = 0; _sid < wantStrategyLength[_want]; _sid++) { _bal = _bal.ADD260(IMultiVaultStrategy(strategies[_want][_sid].strategy).BALANCEOF771()); } return _bal; } function WANT777() external view returns (address) { //inject NONSTANDARD NAMING if (lazySelectedBestStrategy != address(0)) { return IMultiVaultStrategy(lazySelectedBestStrategy).WANT777(); } uint _wlength = wantTokens.length; if (_wlength > 0) { if (_wlength == 1) { return wantTokens[0]; } for (uint i = 0; i < _wlength; i++) { address _want = wantTokens[i]; uint _bal = WANTSTRATEGYBALANCE73(_want); if (_bal < wantQuota[_want]) { return _want; } } } return basedWant; } function SETLAZYSELECTEDBESTSTRATEGY629(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); lazySelectedBestStrategy = _strategy; } function GETBESTSTRATEGY227(address _want) public view returns (address _strategy) { //inject NONSTANDARD NAMING if (lazySelectedBestStrategy != address(0) && IMultiVaultStrategy(lazySelectedBestStrategy).WANT777() == _want) { return lazySelectedBestStrategy; } uint _wantStrategyLength = wantStrategyLength[_want]; _strategy = address(0); if (_wantStrategyLength == 0) return _strategy; uint _totalBal = WANTSTRATEGYBALANCE73(_want); if (_totalBal == 0) { // first depositor, simply return the first strategy return strategies[_want][0].strategy; } uint _bestDiff = 201; for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; uint _stratBal = IMultiVaultStrategy(sinfo.strategy).BALANCEOF771(); if (_stratBal < sinfo.quota) { uint _diff = _stratBal.ADD260(_totalBal).MUL872(100).DIV551(_totalBal).SUB684(sinfo.percent); // [100, 200] - [percent] if (_diff < _bestDiff) { _bestDiff = _diff; _strategy = sinfo.strategy; } } } if (_strategy == address(0)) { _strategy = strategies[_want][0].strategy; } } function EARN427(address _token, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist"); address _strategy = GETBESTSTRATEGY227(_token); if (_strategy == address(0) || IMultiVaultStrategy(_strategy).WANT777() != _token) { // forward to vault and then call earnExtra() by its governance IERC20(_token).SAFETRANSFER627(address(vault), _amount); } else { IERC20(_token).SAFETRANSFER627(_strategy, _amount); IMultiVaultStrategy(_strategy).DEPOSIT294(); } } function WITHDRAW_FEE118(address _want, uint _amount) external view returns (uint) { //inject NONSTANDARD NAMING address _strategy = GETBESTSTRATEGY227(_want); return (_strategy == address(0)) ? 0 : IMultiVaultStrategy(_strategy).WITHDRAWFEE692(_amount); } function BALANCEOF771(address _want, bool _sell) external view returns (uint _totalBal) { //inject NONSTANDARD NAMING uint _wlength = wantTokens.length; if (_wlength == 0) { return 0; } _totalBal = 0; for (uint i = 0; i < _wlength; i++) { address wt = wantTokens[i]; uint _bal = WANTSTRATEGYBALANCE73(wt); if (wt != _want) { _bal = shareConverter.CONVERT_SHARES_RATE463(wt, _want, _bal); if (_sell) { _bal = _bal.MUL872(9998).DIV551(10000); // minus 0.02% for selling } } _totalBal = _totalBal.ADD260(_bal); } } function WITHDRAWALL927(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); // WithdrawAll sends 'want' to 'vault' IMultiVaultStrategy(_strategy).WITHDRAWALL927(); } function INCASETOKENSGETSTUCK116(address _token, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); IERC20(_token).SAFETRANSFER627(address(vault), _amount); } function INCASESTRATEGYGETSTUCK927(address _strategy, address _token) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); IMultiVaultStrategy(_strategy).WITHDRAW808(_token); IERC20(_token).SAFETRANSFER627(address(vault), IERC20(_token).BALANCEOF771(address(this))); } function CLAIMINSURANCE45() external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); vault.CLAIMINSURANCE45(); } // note that some strategies do not allow controller to harvest function HARVESTSTRATEGY825(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); IMultiVaultStrategy(_strategy).HARVEST506(address(0)); } function HARVESTWANT168(address _want) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); uint _wantStrategyLength = wantStrategyLength[_want]; address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; if (_firstStrategy == address(0)) { _firstStrategy = sinfo.strategy; } else { IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy); } } if (_firstStrategy != address(0)) { IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0)); } } function HARVESTALLSTRATEGIES334() external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); uint _wlength = wantTokens.length; address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here for (uint i = 0; i < _wlength; i++) { address _want = wantTokens[i]; uint _wantStrategyLength = wantStrategyLength[_want]; for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; if (_firstStrategy == address(0)) { _firstStrategy = sinfo.strategy; } else { IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy); } } } if (_firstStrategy != address(0)) { IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0)); } } function SWITCHFUND172(IMultiVaultStrategy _srcStrat, IMultiVaultStrategy _destStrat, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); _srcStrat.WITHDRAWTOCONTROLLER653(_amount); address _srcWant = _srcStrat.WANT777(); address _destWant = _destStrat.WANT777(); if (_srcWant != _destWant) { _amount = IERC20(_srcWant).BALANCEOF771(address(this)); require(shareConverter.CONVERT_SHARES_RATE463(_srcWant, _destWant, _amount) > 0, "rate=0"); IERC20(_srcWant).SAFETRANSFER627(address(shareConverter), _amount); shareConverter.CONVERT_SHARES33(_srcWant, _destWant, _amount); } IERC20(_destWant).SAFETRANSFER627(address(_destStrat), IERC20(_destWant).BALANCEOF771(address(this))); _destStrat.DEPOSIT294(); } function WITHDRAW808(address _want, uint _amount) external returns (uint _withdrawFee) { //inject NONSTANDARD NAMING require(msg.sender == address(vault), "!vault"); _withdrawFee = 0; uint _toWithdraw = _amount; uint _wantStrategyLength = wantStrategyLength[_want]; uint _received; for (uint _sid = _wantStrategyLength; _sid > 0; _sid--) { StrategyInfo storage sinfo = strategies[_want][_sid - 1]; IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy); uint _stratBal = _strategy.BALANCEOF771(); if (_toWithdraw < _stratBal) { _received = _strategy.WITHDRAW808(_toWithdraw); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received)); return _withdrawFee; } _received = _strategy.WITHDRAWALL927(); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received)); if (_received >= _toWithdraw) { return _withdrawFee; } _toWithdraw = _toWithdraw.SUB684(_received); } if (_toWithdraw > 0) { // still not enough, try to withdraw from other wants strategies uint _wlength = wantTokens.length; for (uint i = _wlength; i > 0; i--) { address wt = wantTokens[i - 1]; if (wt != _want) { (uint _wamt, uint _wdfee) = _WITHDRAWOTHERWANT971(_want, wt, _toWithdraw); _withdrawFee = _withdrawFee.ADD260(_wdfee); if (_wamt >= _toWithdraw) { return _withdrawFee; } _toWithdraw = _toWithdraw.SUB684(_wamt); } } } return _withdrawFee; } function _WITHDRAWOTHERWANT971(address _want, address _other, uint _amount) internal returns (uint _wantAmount, uint _withdrawFee) { //inject NONSTANDARD NAMING // Check balance uint b = IERC20(_want).BALANCEOF771(address(this)); _withdrawFee = 0; if (b >= _amount) { _wantAmount = b; } else { uint _toWithdraw = _amount.SUB684(b); uint _toWithdrawOther = _toWithdraw.MUL872(101).DIV551(100); // add 1% extra uint _otherBal = IERC20(_other).BALANCEOF771(address(this)); if (_otherBal < _toWithdrawOther) { uint _otherStrategyLength = wantStrategyLength[_other]; for (uint _sid = _otherStrategyLength; _sid > 0; _sid--) { StrategyInfo storage sinfo = strategies[_other][_sid - 1]; IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy); uint _stratBal = _strategy.BALANCEOF771(); uint _needed = _toWithdrawOther.SUB684(_otherBal); uint _wdamt = (_needed < _stratBal) ? _needed : _stratBal; _strategy.WITHDRAWTOCONTROLLER653(_wdamt); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_wdamt)); _otherBal = IERC20(_other).BALANCEOF771(address(this)); if (_otherBal >= _toWithdrawOther) { break; } } } IERC20(_other).SAFETRANSFER627(address(shareConverter), _otherBal); shareConverter.CONVERT_SHARES33(_other, _want, _otherBal); _wantAmount = IERC20(_want).BALANCEOF771(address(this)); } IERC20(_want).SAFETRANSFER627(address(vault), _wantAmount); } }
inject NONSTANDARD NAMING
function GETBESTSTRATEGY227(address _want) public view returns (address _strategy) {
13,085,398
[ 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, 565, 445, 4978, 5948, 882, 3902, 27708, 3787, 27, 12, 2867, 389, 17369, 13, 1071, 1476, 1135, 261, 2867, 389, 14914, 13, 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, -100, -100, -100 ]
./partial_match/5/0x4D3495005E14c0AB9f3C0F80876c4152CE3D0F83/sources/contracts/testnet/LDPRewarder.sol
* @dev Returned by {noWeth} modifier when ERC20-reserved operations are attempted on WETH; check {noWeth} documentation for more info./
error NotAllowedOnWETH();
16,866,814
[ 1, 22360, 635, 288, 2135, 59, 546, 97, 9606, 1347, 4232, 39, 3462, 17, 18898, 5295, 854, 18121, 603, 678, 1584, 44, 31, 866, 288, 2135, 59, 546, 97, 7323, 364, 1898, 1123, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 555, 2288, 5042, 1398, 59, 1584, 44, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x890500D6Bc3746a902a761C87232D63Dae608E88/sources/script/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol
* the Metadata extension, but not including the Enumerable extension, which is available separately as {ERC721Enumerable}./ Token name Token symbol Mapping from token ID to owner address Mapping owner address to token count Mapping from token ID to approved address Mapping from owner to operator approvals
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function _setThisApprovalForAll(address operator, bool approved) internal virtual { require(operator !=address(this), "ERC721: approve to caller"); _operatorApprovals[address(this)][operator] = approved; emit ApprovalForAll(address(this), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } catch (bytes memory reason) { function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } else { function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); assembly { revert(add(32, reason), mload(reason)) } } } return true; } } } else { ) internal virtual {} }
13,317,007
[ 1, 5787, 6912, 2710, 16, 1496, 486, 6508, 326, 6057, 25121, 2710, 16, 1492, 353, 2319, 18190, 487, 288, 654, 39, 27, 5340, 3572, 25121, 5496, 19, 3155, 508, 3155, 3273, 9408, 628, 1147, 1599, 358, 3410, 1758, 9408, 3410, 1758, 358, 1147, 1056, 9408, 628, 1147, 1599, 358, 20412, 1758, 9408, 628, 3410, 358, 3726, 6617, 4524, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 27, 5340, 353, 1772, 16, 4232, 39, 28275, 16, 467, 654, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 2277, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 995, 414, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 565, 289, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 12, 654, 39, 28275, 16, 467, 654, 39, 28275, 13, 1135, 261, 6430, 13, 288, 203, 3639, 327, 203, 5411, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 2934, 5831, 548, 747, 203, 5411, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 2277, 2934, 5831, 548, 747, 203, 5411, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 2 ]
./full_match/4/0x511739380fb9C5b985d08B5637ba732cAB3D4cCC/sources/contracts/TRAVELLSMART.sol
* @dev Toggles between paused <-> unpaused states to disallow <-> allow token transfers. See {Pausable-paused()}, {Pausable-_pause()} and {Pausable-_unpause()}./
function _togglePause() internal { paused() ? _unpause() : _pause(); }
660,678
[ 1, 56, 23972, 1040, 3086, 17781, 411, 2122, 640, 8774, 3668, 5493, 358, 29176, 411, 2122, 1699, 1147, 29375, 18, 2164, 288, 16507, 16665, 17, 8774, 3668, 1435, 5779, 288, 16507, 16665, 17, 67, 19476, 17767, 471, 288, 16507, 16665, 17, 67, 318, 19476, 1435, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 14401, 19205, 1435, 2713, 288, 203, 3639, 17781, 1435, 692, 389, 318, 19476, 1435, 294, 389, 19476, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/10/0xd84d9A8Bf830496C4DEc917bC27D22E09E01cB8A/sources/src/Facets/HopFacet.sol
@notice Bridges tokens via Hop Protocol @param _bridgeData the core information needed for bridging @param _hopData data specific to Hop Protocol
function startBridgeTokensViaHop( ILiFi.BridgeData memory _bridgeData, HopData calldata _hopData ) external payable nonReentrant refundExcessNative(payable(msg.sender)) doesNotContainSourceSwaps(_bridgeData) doesNotContainDestinationCalls(_bridgeData) validateBridgeData(_bridgeData) { LibAsset.depositAsset( _bridgeData.sendingAssetId, _bridgeData.minAmount ); _startBridge(_bridgeData, _hopData); }
3,781,374
[ 1, 38, 1691, 2852, 2430, 3970, 670, 556, 4547, 225, 389, 18337, 751, 326, 2922, 1779, 3577, 364, 324, 1691, 1998, 225, 389, 18444, 751, 501, 2923, 358, 670, 556, 4547, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 787, 13691, 5157, 21246, 27461, 12, 203, 3639, 467, 28762, 42, 77, 18, 13691, 751, 3778, 389, 18337, 751, 16, 203, 3639, 670, 556, 751, 745, 892, 389, 18444, 751, 203, 565, 262, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 16255, 424, 614, 9220, 12, 10239, 429, 12, 3576, 18, 15330, 3719, 203, 3639, 1552, 1248, 22928, 1830, 6050, 6679, 24899, 18337, 751, 13, 203, 3639, 1552, 1248, 22928, 5683, 10125, 24899, 18337, 751, 13, 203, 3639, 1954, 13691, 751, 24899, 18337, 751, 13, 203, 565, 288, 203, 3639, 10560, 6672, 18, 323, 1724, 6672, 12, 203, 5411, 389, 18337, 751, 18, 87, 2846, 6672, 548, 16, 203, 5411, 389, 18337, 751, 18, 1154, 6275, 203, 3639, 11272, 203, 3639, 389, 1937, 13691, 24899, 18337, 751, 16, 389, 18444, 751, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 ERC20 { function transfer(address _to, uint256 _value) public returns(bool); function balanceOf(address tokenOwner) public constant returns (uint balance); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Airdropper is Ownable { address public tokenAddr = 0x0; uint256 public numOfTokens; ERC20 public token; function Airdropper(address _tokenAddr, uint256 _numOfTokens) public { tokenAddr = _tokenAddr; numOfTokens = _numOfTokens; token = ERC20(_tokenAddr); } function multisend(address[] dests) public onlyOwner returns (uint256) { uint256 i = 0; while (i < dests.length) { require(token.transfer(dests[i], numOfTokens)); i += 1; } return(i); } function getLendTokenBalance() public constant returns (uint256) { return token.balanceOf(this); } //Function to get the locked tokens back, in case of any issue //Return the tokens to the owner's address function withdrawRemainingTokens() public onlyOwner { uint contractTokenBalance = token.balanceOf(this); require(contractTokenBalance > 0); token.transfer(owner, contractTokenBalance); } // Method to get any locked ERC20 tokens function withdrawERC20ToOwner(address _erc20) public onlyOwner { ERC20 erc20Token = ERC20(_erc20); uint contractTokenBalance = erc20Token.balanceOf(this); require(contractTokenBalance > 0); erc20Token.transfer(owner, contractTokenBalance); } }
Method to get any locked ERC20 tokens
function withdrawERC20ToOwner(address _erc20) public onlyOwner { ERC20 erc20Token = ERC20(_erc20); uint contractTokenBalance = erc20Token.balanceOf(this); require(contractTokenBalance > 0); erc20Token.transfer(owner, contractTokenBalance); }
14,125,586
[ 1, 1305, 358, 336, 1281, 8586, 4232, 39, 3462, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 598, 9446, 654, 39, 3462, 774, 5541, 12, 2867, 389, 12610, 3462, 13, 1071, 1338, 5541, 288, 203, 3639, 4232, 39, 3462, 6445, 71, 3462, 1345, 273, 4232, 39, 3462, 24899, 12610, 3462, 1769, 203, 3639, 2254, 6835, 1345, 13937, 273, 6445, 71, 3462, 1345, 18, 12296, 951, 12, 2211, 1769, 203, 3639, 2583, 12, 16351, 1345, 13937, 405, 374, 1769, 203, 3639, 6445, 71, 3462, 1345, 18, 13866, 12, 8443, 16, 6835, 1345, 13937, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; // File: witnet-ethereum-block-relay/contracts/BlockRelayInterface.sol /** * @title Block Relay Interface * @notice Interface of a Block Relay to a Witnet network * It defines how to interact with the Block Relay in order to support: * - Retrieve last beacon information * - Verify proof of inclusions (PoIs) of data request and tally transactions * @author Witnet Foundation */ interface BlockRelayInterface { /// @notice Returns the beacon from the last inserted block. /// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility. /// @return last beacon in bytes function getLastBeacon() external view returns(bytes memory); /// @notice Returns the lastest epoch reported to the block relay. /// @return epoch function getLastEpoch() external view returns(uint256); /// @notice Returns the latest hash reported to the block relay /// @return blockhash function getLastHash() external view returns(uint256); /// @notice Verifies the validity of a data request PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view returns(bool); /// @notice Verifies the validity of a tally PoI against the Tally merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid tally PoI function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view returns(bool); /// @notice Verifies if the block relay can be upgraded /// @return true if contract is upgradable function isUpgradable(address _address) external view returns(bool); } // File: witnet-ethereum-block-relay/contracts/CentralizedBlockRelay.sol /** * @title Block relay contract * @notice Contract to store/read block headers from the Witnet network * @author Witnet Foundation */ contract CentralizedBlockRelay is BlockRelayInterface { struct MerkleRoots { // hash of the merkle root of the DRs in Witnet uint256 drHashMerkleRoot; // hash of the merkle root of the tallies in Witnet uint256 tallyHashMerkleRoot; } struct Beacon { // hash of the last block uint256 blockHash; // epoch of the last block uint256 epoch; } // Address of the block pusher address public witnet; // Last block reported Beacon public lastBlock; mapping (uint256 => MerkleRoots) public blocks; // Event emitted when a new block is posted to the contract event NewBlock(address indexed _from, uint256 _id); // Only the owner should be able to push blocks modifier isOwner() { require(msg.sender == witnet, "Sender not authorized"); // If it is incorrect here, it reverts. _; // Otherwise, it continues. } // Ensures block exists modifier blockExists(uint256 _id){ require(blocks[_id].drHashMerkleRoot!=0, "Non-existing block"); _; } // Ensures block does not exist modifier blockDoesNotExist(uint256 _id){ require(blocks[_id].drHashMerkleRoot==0, "The block already existed"); _; } constructor() public{ // Only the contract deployer is able to push blocks witnet = msg.sender; } /// @dev Read the beacon of the last block inserted /// @return bytes to be signed by bridge nodes function getLastBeacon() external view override returns(bytes memory) { return abi.encodePacked(lastBlock.blockHash, lastBlock.epoch); } /// @notice Returns the lastest epoch reported to the block relay. /// @return epoch function getLastEpoch() external view override returns(uint256) { return lastBlock.epoch; } /// @notice Returns the latest hash reported to the block relay /// @return blockhash function getLastHash() external view override returns(uint256) { return lastBlock.blockHash; } /// @dev Verifies the validity of a PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) returns(bool) { uint256 drMerkleRoot = blocks[_blockHash].drHashMerkleRoot; return(verifyPoi( _poi, drMerkleRoot, _index, _element)); } /// @dev Verifies the validity of a PoI against the tally merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the element /// @return true or false depending the validity function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) returns(bool) { uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot; return(verifyPoi( _poi, tallyMerkleRoot, _index, _element)); } /// @dev Verifies if the contract is upgradable /// @return true if the contract upgradable function isUpgradable(address _address) external view override returns(bool) { if (_address == witnet) { return true; } return false; } /// @dev Post new block into the block relay /// @param _blockHash Hash of the block header /// @param _epoch Witnet epoch to which the block belongs to /// @param _drMerkleRoot Merkle root belonging to the data requests /// @param _tallyMerkleRoot Merkle root belonging to the tallies function postNewBlock( uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot) external isOwner blockDoesNotExist(_blockHash) { lastBlock.blockHash = _blockHash; lastBlock.epoch = _epoch; blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot; blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot; emit NewBlock(witnet, _blockHash); } /// @dev Retrieve the requests-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header /// @return Requests-only merkle root hash in the block header. function readDrMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].drHashMerkleRoot; } /// @dev Retrieve the tallies-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header. /// @return tallies-only merkle root hash in the block header. function readTallyMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].tallyHashMerkleRoot; } /// @dev Verifies the validity of a PoI /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _root the merkle root /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyPoi( uint256[] memory _poi, uint256 _root, uint256 _index, uint256 _element) private pure returns(bool) { uint256 tree = _element; uint256 index = _index; // We want to prove that the hash of the _poi and the _element is equal to _root // For knowing if concatenate to the left or the right we check the parity of the the index for (uint i = 0; i < _poi.length; i++) { if (index%2 == 0) { tree = uint256(sha256(abi.encodePacked(tree, _poi[i]))); } else { tree = uint256(sha256(abi.encodePacked(_poi[i], tree))); } index = index >> 1; } return _root == tree; } } // File: witnet-ethereum-block-relay/contracts/BlockRelayProxy.sol /** * @title Block Relay Proxy * @notice Contract to act as a proxy between the Witnet Bridge Interface and the block relay * @dev More information can be found here * DISCLAIMER: this is a work in progress, meaning the contract could be voulnerable to attacks * @author Witnet Foundation */ contract BlockRelayProxy { // Address of the current controller address internal blockRelayAddress; // Current interface to the controller BlockRelayInterface internal blockRelayInstance; struct ControllerInfo { // last epoch seen by a controller uint256 lastEpoch; // address of the controller address blockRelayController; } // array containing the information about controllers ControllerInfo[] internal controllers; modifier notIdentical(address _newAddress) { require(_newAddress != blockRelayAddress, "The provided Block Relay instance address is already in use"); _; } constructor(address _blockRelayAddress) public { // Initialize the first epoch pointing to the first controller controllers.push(ControllerInfo({lastEpoch: 0, blockRelayController: _blockRelayAddress})); blockRelayAddress = _blockRelayAddress; blockRelayInstance = BlockRelayInterface(_blockRelayAddress); } /// @notice Returns the beacon from the last inserted block. /// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility. /// @return last beacon in bytes function getLastBeacon() external view returns(bytes memory) { return blockRelayInstance.getLastBeacon(); } /// @notice Returns the last Wtinet epoch known to the block relay instance. /// @return The last epoch is used in the WRB to avoid reusage of PoI in a data request. function getLastEpoch() external view returns(uint256) { return blockRelayInstance.getLastEpoch(); } /// @notice Verifies the validity of a data request PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _epoch the epoch of the blockchash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _epoch, uint256 _index, uint256 _element) external view returns(bool) { address controller = getController(_epoch); return BlockRelayInterface(controller).verifyDrPoi( _poi, _blockHash, _index, _element); } /// @notice Verifies the validity of a tally PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _epoch the epoch of the blockchash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _epoch, uint256 _index, uint256 _element) external view returns(bool) { address controller = getController(_epoch); return BlockRelayInterface(controller).verifyTallyPoi( _poi, _blockHash, _index, _element); } /// @notice Upgrades the block relay if the current one is upgradeable /// @param _newAddress address of the new block relay to upgrade function upgradeBlockRelay(address _newAddress) external notIdentical(_newAddress) { // Check if the controller is upgradeable require(blockRelayInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation"); // Get last epoch seen by the replaced controller uint256 epoch = blockRelayInstance.getLastEpoch(); // Get the length of last epochs seen by the different controllers uint256 n = controllers.length; // If the the last epoch seen by the replaced controller is lower than the one already anotated e.g. 0 // just update the already anotated epoch with the new address, ignoring the previously inserted controller // Else, anotate the epoch from which the new controller should start receiving blocks if (epoch < controllers[n-1].lastEpoch) { controllers[n-1].blockRelayController = _newAddress; } else { controllers.push(ControllerInfo({lastEpoch: epoch+1, blockRelayController: _newAddress})); } // Update instance blockRelayAddress = _newAddress; blockRelayInstance = BlockRelayInterface(_newAddress); } /// @notice Gets the controller associated with the BR controller corresponding to the epoch provided /// @param _epoch the epoch to work with function getController(uint256 _epoch) public view returns(address _controller) { // Get length of all last epochs seen by controllers uint256 n = controllers.length; // Go backwards until we find the controller having that blockhash for (uint i = n; i > 0; i--) { if (_epoch >= controllers[i-1].lastEpoch) { return (controllers[i-1].blockRelayController); } } } } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // File: elliptic-curve-solidity/contracts/EllipticCurve.sol /** * @title Elliptic Curve Library * @dev Library providing arithmetic operations over elliptic curves. * @author Witnet Foundation */ library EllipticCurve { /// @dev Modular euclidean inverse of a number (mod p). /// @param _x The number /// @param _pp The modulus /// @return q such that x*q = 1 (mod _pp) function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) { require(_x != 0 && _x != _pp && _pp != 0, "Invalid number"); uint256 q = 0; uint256 newT = 1; uint256 r = _pp; uint256 newR = _x; uint256 t; while (newR != 0) { t = r / newR; (q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp)); (r, newR) = (newR, r - t * newR ); } return q; } /// @dev Modular exponentiation, b^e % _pp. /// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol /// @param _base base /// @param _exp exponent /// @param _pp modulus /// @return r such that r = b**e (mod _pp) function expMod(uint256 _base, uint256 _exp, uint256 _pp) internal pure returns (uint256) { require(_pp!=0, "Modulus is zero"); if (_base == 0) return 0; if (_exp == 0) return 1; uint256 r = 1; uint256 bit = 2 ** 255; assembly { for { } gt(bit, 0) { }{ r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, bit)))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), _pp) bit := div(bit, 16) } } return r; } /// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1). /// @param _x coordinate x /// @param _y coordinate y /// @param _z coordinate z /// @param _pp the modulus /// @return (x', y') affine coordinates function toAffine( uint256 _x, uint256 _y, uint256 _z, uint256 _pp) internal pure returns (uint256, uint256) { uint256 zInv = invMod(_z, _pp); uint256 zInv2 = mulmod(zInv, zInv, _pp); uint256 x2 = mulmod(_x, zInv2, _pp); uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp); return (x2, y2); } /// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf). /// @param _prefix parity byte (0x02 even, 0x03 odd) /// @param _x coordinate x /// @param _aa constant of curve /// @param _bb constant of curve /// @param _pp the modulus /// @return y coordinate y function deriveY( uint8 _prefix, uint256 _x, uint256 _aa, uint256 _bb, uint256 _pp) internal pure returns (uint256) { require(_prefix == 0x02 || _prefix == 0x03, "Invalid compressed EC point prefix"); // x^3 + ax + b uint256 y2 = addmod(mulmod(_x, mulmod(_x, _x, _pp), _pp), addmod(mulmod(_x, _aa, _pp), _bb, _pp), _pp); y2 = expMod(y2, (_pp + 1) / 4, _pp); // uint256 cmp = yBit ^ y_ & 1; uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2; return y; } /// @dev Check whether point (x,y) is on curve defined by a, b, and _pp. /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _aa constant of curve /// @param _bb constant of curve /// @param _pp the modulus /// @return true if x,y in the curve, false else function isOnCurve( uint _x, uint _y, uint _aa, uint _bb, uint _pp) internal pure returns (bool) { if (0 == _x || _x == _pp || 0 == _y || _y == _pp) { return false; } // y^2 uint lhs = mulmod(_y, _y, _pp); // x^3 uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp); if (_aa != 0) { // x^3 + a*x rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp); } if (_bb != 0) { // x^3 + a*x + b rhs = addmod(rhs, _bb, _pp); } return lhs == rhs; } /// @dev Calculate inverse (x, -y) of point (x, y). /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _pp the modulus /// @return (x, -y) function ecInv( uint256 _x, uint256 _y, uint256 _pp) internal pure returns (uint256, uint256) { return (_x, (_pp - _y) % _pp); } /// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates. /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _x2 coordinate x of P2 /// @param _y2 coordinate y of P2 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = P1+P2 in affine coordinates function ecAdd( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { uint x = 0; uint y = 0; uint z = 0; // Double if x1==x2 else add if (_x1==_x2) { (x, y, z) = jacDouble( _x1, _y1, 1, _aa, _pp); } else { (x, y, z) = jacAdd( _x1, _y1, 1, _x2, _y2, 1, _pp); } // Get back to affine return toAffine( x, y, z, _pp); } /// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates. /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _x2 coordinate x of P2 /// @param _y2 coordinate y of P2 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = P1-P2 in affine coordinates function ecSub( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { // invert square (uint256 x, uint256 y) = ecInv(_x2, _y2, _pp); // P1-square return ecAdd( _x1, _y1, x, y, _aa, _pp); } /// @dev Multiply point (x1, y1, z1) times d in affine coordinates. /// @param _k scalar to multiply /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = d*P in affine coordinates function ecMul( uint256 _k, uint256 _x, uint256 _y, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { // Jacobian multiplication (uint256 x1, uint256 y1, uint256 z1) = jacMul( _k, _x, _y, 1, _aa, _pp); // Get back to affine return toAffine( x1, y1, z1, _pp); } /// @dev Adds two points (x1, y1, z1) and (x2 y2, z2). /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _z1 coordinate z of P1 /// @param _x2 coordinate x of square /// @param _y2 coordinate y of square /// @param _z2 coordinate z of square /// @param _pp the modulus /// @return (qx, qy, qz) P1+square in Jacobian function jacAdd( uint256 _x1, uint256 _y1, uint256 _z1, uint256 _x2, uint256 _y2, uint256 _z2, uint256 _pp) internal pure returns (uint256, uint256, uint256) { if ((_x1==0)&&(_y1==0)) return (_x2, _y2, _z2); if ((_x2==0)&&(_y2==0)) return (_x1, _y1, _z1); // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5 uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3 zs[0] = mulmod(_z1, _z1, _pp); zs[1] = mulmod(_z1, zs[0], _pp); zs[2] = mulmod(_z2, _z2, _pp); zs[3] = mulmod(_z2, zs[2], _pp); // u1, s1, u2, s2 zs = [ mulmod(_x1, zs[2], _pp), mulmod(_y1, zs[3], _pp), mulmod(_x2, zs[0], _pp), mulmod(_y2, zs[1], _pp) ]; // In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used require(zs[0] != zs[2], "Invalid data"); uint[4] memory hr; //h hr[0] = addmod(zs[2], _pp - zs[0], _pp); //r hr[1] = addmod(zs[3], _pp - zs[1], _pp); //h^2 hr[2] = mulmod(hr[0], hr[0], _pp); // h^3 hr[3] = mulmod(hr[2], hr[0], _pp); // qx = -h^3 -2u1h^2+r^2 uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp); qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp); // qy = -s1*z1*h^3+r(u1*h^2 -x^3) uint256 qy = mulmod(hr[1], addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp), _pp); qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp); // qz = h*z1*z2 uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp); return(qx, qy, qz); } /// @dev Doubles a points (x, y, z). /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _z coordinate z of P1 /// @param _pp the modulus /// @param _aa the a scalar in the curve equation /// @return (qx, qy, qz) 2P in Jacobian function jacDouble( uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) internal pure returns (uint256, uint256, uint256) { if (_z == 0) return (_x, _y, _z); uint256[3] memory square; // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5 // Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4) square[0] = mulmod(_x, _x, _pp); //x1^2 square[1] = mulmod(_y, _y, _pp); //y1^2 square[2] = mulmod(_z, _z, _pp); //z1^2 // s uint s = mulmod(4, mulmod(_x, square[1], _pp), _pp); // m uint m = addmod(mulmod(3, square[0], _pp), mulmod(_aa, mulmod(square[2], square[2], _pp), _pp), _pp); // qx uint256 qx = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp); // qy = -8*y1^4 + M(S-T) uint256 qy = addmod(mulmod(m, addmod(s, _pp - qx, _pp), _pp), _pp - mulmod(8, mulmod(square[1], square[1], _pp), _pp), _pp); // qz = 2*y1*z1 uint256 qz = mulmod(2, mulmod(_y, _z, _pp), _pp); return (qx, qy, qz); } /// @dev Multiply point (x, y, z) times d. /// @param _d scalar to multiply /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _z coordinate z of P1 /// @param _aa constant of curve /// @param _pp the modulus /// @return (qx, qy, qz) d*P1 in Jacobian function jacMul( uint256 _d, uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) internal pure returns (uint256, uint256, uint256) { uint256 remaining = _d; uint256[3] memory point; point[0] = _x; point[1] = _y; point[2] = _z; uint256 qx = 0; uint256 qy = 0; uint256 qz = 1; if (_d == 0) { return (qx, qy, qz); } // Double and add algorithm while (remaining != 0) { if ((remaining & 1) != 0) { (qx, qy, qz) = jacAdd( qx, qy, qz, point[0], point[1], point[2], _pp); } remaining = remaining / 2; (point[0], point[1], point[2]) = jacDouble( point[0], point[1], point[2], _aa, _pp); } return (qx, qy, qz); } } // File: vrf-solidity/contracts/VRF.sol /** * @title Verifiable Random Functions (VRF) * @notice Library verifying VRF proofs using the `Secp256k1` curve and the `SHA256` hash function. * @dev This library follows the algorithms described in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04) and [RFC6979](https://tools.ietf.org/html/rfc6979). * It supports the _SECP256K1_SHA256_TAI_ cipher suite, i.e. the aforementioned algorithms using `SHA256` and the `Secp256k1` curve. * @author Witnet Foundation */ library VRF { /** * Secp256k1 parameters */ // Generator coordinate `x` of the EC curve uint256 public constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; // Generator coordinate `y` of the EC curve uint256 public constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; // Constant `a` of EC equation uint256 public constant AA = 0; // Constant `b` of EC equation uint256 public constant BB = 7; // Prime number of the curve uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // Order of the curve uint256 public constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; /// @dev Public key derivation from private key. /// @param _d The scalar /// @param _x The coordinate x /// @param _y The coordinate y /// @return (qx, qy) The derived point function derivePoint(uint256 _d, uint256 _x, uint256 _y) internal pure returns (uint256, uint256) { return EllipticCurve.ecMul( _d, _x, _y, AA, PP ); } /// @dev Function to derive the `y` coordinate given the `x` coordinate and the parity byte (`0x03` for odd `y` and `0x04` for even `y`). /// @param _yByte The parity byte following the ec point compressed format /// @param _x The coordinate `x` of the point /// @return The coordinate `y` of the point function deriveY(uint8 _yByte, uint256 _x) internal pure returns (uint256) { return EllipticCurve.deriveY( _yByte, _x, AA, BB, PP); } /// @dev Computes the VRF hash output as result of the digest of a ciphersuite-dependent prefix /// concatenated with the gamma point /// @param _gammaX The x-coordinate of the gamma EC point /// @param _gammaY The y-coordinate of the gamma EC point /// @return The VRF hash ouput as shas256 digest function gammaToHash(uint256 _gammaX, uint256 _gammaY) internal pure returns (bytes32) { bytes memory c = abi.encodePacked( // Cipher suite code (SECP256K1-SHA256-TAI is 0xFE) uint8(0xFE), // 0x01 uint8(0x03), // Compressed Gamma Point encodePoint(_gammaX, _gammaY)); return sha256(c); } /// @dev VRF verification by providing the public key, the message and the VRF proof. /// This function computes several elliptic curve operations which may lead to extensive gas consumption. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @return true, if VRF proof is valid function verify(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (bool) { // Step 2: Hash to try and increment (outputs a hashed value, a finite EC point in G) uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); // Step 3: U = s*B - c*Y (where B is the generator) (uint256 uPointX, uint256 uPointY) = ecMulSubMul( _proof[3], GX, GY, _proof[2], _publicKey[0], _publicKey[1]); // Step 4: V = s*H - c*Gamma (uint256 vPointX, uint256 vPointY) = ecMulSubMul( _proof[3], hPoint[0], hPoint[1], _proof[2], _proof[0],_proof[1]); // Step 5: derived c from hash points(...) bytes16 derivedC = hashPoints( hPoint[0], hPoint[1], _proof[0], _proof[1], uPointX, uPointY, vPointX, vPointY); // Step 6: Check validity c == c' return uint128(derivedC) == _proof[2]; } /// @dev VRF fast verification by providing the public key, the message, the VRF proof and several intermediate elliptic curve points that enable the verification shortcut. /// This function leverages the EVM's `ecrecover` precompile to verify elliptic curve multiplications by decreasing the security from 32 to 20 bytes. /// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @param _uPoint The `u` EC point defined as `U = s*B - c*Y` /// @param _vComponents The components required to compute `v` as `V = s*H - c*Gamma` /// @return true, if VRF proof is valid function fastVerify( uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message, uint256[2] memory _uPoint, uint256[4] memory _vComponents) internal pure returns (bool) { // Step 2: Hash to try and increment -> hashed value, a finite EC point in G uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); // Step 3 & Step 4: // U = s*B - c*Y (where B is the generator) // V = s*H - c*Gamma if (!ecMulSubMulVerify( _proof[3], _proof[2], _publicKey[0], _publicKey[1], _uPoint[0], _uPoint[1]) || !ecMulVerify( _proof[3], hPoint[0], hPoint[1], _vComponents[0], _vComponents[1]) || !ecMulVerify( _proof[2], _proof[0], _proof[1], _vComponents[2], _vComponents[3]) ) { return false; } (uint256 vPointX, uint256 vPointY) = EllipticCurve.ecSub( _vComponents[0], _vComponents[1], _vComponents[2], _vComponents[3], AA, PP); // Step 5: derived c from hash points(...) bytes16 derivedC = hashPoints( hPoint[0], hPoint[1], _proof[0], _proof[1], _uPoint[0], _uPoint[1], vPointX, vPointY); // Step 6: Check validity c == c' return uint128(derivedC) == _proof[2]; } /// @dev Decode VRF proof from bytes /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` function decodeProof(bytes memory _proof) internal pure returns (uint[4] memory) { require(_proof.length == 81, "Malformed VRF proof"); uint8 gammaSign; uint256 gammaX; uint128 c; uint256 s; assembly { gammaSign := mload(add(_proof, 1)) gammaX := mload(add(_proof, 33)) c := mload(add(_proof, 49)) s := mload(add(_proof, 81)) } uint256 gammaY = deriveY(gammaSign, gammaX); return [ gammaX, gammaY, c, s]; } /// @dev Decode EC point from bytes /// @param _point The EC point as bytes /// @return The point as `[point-x, point-y]` function decodePoint(bytes memory _point) internal pure returns (uint[2] memory) { require(_point.length == 33, "Malformed compressed EC point"); uint8 sign; uint256 x; assembly { sign := mload(add(_point, 1)) x := mload(add(_point, 33)) } uint256 y = deriveY(sign, x); return [x, y]; } /// @dev Compute the parameters (EC points) required for the VRF fast verification function. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])` function computeFastVerifyParams(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (uint256[2] memory, uint256[4] memory) { // Requirements for Step 3: U = s*B - c*Y (where B is the generator) uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); (uint256 uPointX, uint256 uPointY) = ecMulSubMul( _proof[3], GX, GY, _proof[2], _publicKey[0], _publicKey[1]); // Requirements for Step 4: V = s*H - c*Gamma (uint256 sHX, uint256 sHY) = derivePoint(_proof[3], hPoint[0], hPoint[1]); (uint256 cGammaX, uint256 cGammaY) = derivePoint(_proof[2], _proof[0], _proof[1]); return ( [uPointX, uPointY], [ sHX, sHY, cGammaX, cGammaY ]); } /// @dev Function to convert a `Hash(PK|DATA)` to a point in the curve as defined in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04). /// Used in Step 2 of VRF verification function. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _message The message used for computing the VRF /// @return The hash point in affine cooridnates function hashToTryAndIncrement(uint256[2] memory _publicKey, bytes memory _message) internal pure returns (uint, uint) { // Step 1: public key to bytes // Step 2: V = cipher_suite | 0x01 | public_key_bytes | message | ctr bytes memory c = abi.encodePacked( // Cipher suite code (SECP256K1-SHA256-TAI is 0xFE) uint8(254), // 0x01 uint8(1), // Public Key encodePoint(_publicKey[0], _publicKey[1]), // Message _message); // Step 3: find a valid EC point // Loop over counter ctr starting at 0x00 and do hash for (uint8 ctr = 0; ctr < 256; ctr++) { // Counter update // c[cLength-1] = byte(ctr); bytes32 sha = sha256(abi.encodePacked(c, ctr)); // Step 4: arbitraty string to point and check if it is on curve uint hPointX = uint256(sha); uint hPointY = deriveY(2, hPointX); if (EllipticCurve.isOnCurve( hPointX, hPointY, AA, BB, PP)) { // Step 5 (omitted): calculate H (cofactor is 1 on secp256k1) // If H is not "INVALID" and cofactor > 1, set H = cofactor * H return (hPointX, hPointY); } } revert("No valid point was found"); } /// @dev Function to hash a certain set of points as specified in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04). /// Used in Step 5 of VRF verification function. /// @param _hPointX The coordinate `x` of point `H` /// @param _hPointY The coordinate `y` of point `H` /// @param _gammaX The coordinate `x` of the point `Gamma` /// @param _gammaX The coordinate `y` of the point `Gamma` /// @param _uPointX The coordinate `x` of point `U` /// @param _uPointY The coordinate `y` of point `U` /// @param _vPointX The coordinate `x` of point `V` /// @param _vPointY The coordinate `y` of point `V` /// @return The first half of the digest of the points using SHA256 function hashPoints( uint256 _hPointX, uint256 _hPointY, uint256 _gammaX, uint256 _gammaY, uint256 _uPointX, uint256 _uPointY, uint256 _vPointX, uint256 _vPointY) internal pure returns (bytes16) { bytes memory c = abi.encodePacked( // Ciphersuite 0xFE uint8(254), // Prefix 0x02 uint8(2), // Points to Bytes encodePoint(_hPointX, _hPointY), encodePoint(_gammaX, _gammaY), encodePoint(_uPointX, _uPointY), encodePoint(_vPointX, _vPointY) ); // Hash bytes and truncate bytes32 sha = sha256(c); bytes16 half1; assembly { let freemem_pointer := mload(0x40) mstore(add(freemem_pointer,0x00), sha) half1 := mload(add(freemem_pointer,0x00)) } return half1; } /// @dev Encode an EC point to bytes /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @return The point coordinates as bytes function encodePoint(uint256 _x, uint256 _y) internal pure returns (bytes memory) { uint8 prefix = uint8(2 + (_y % 2)); return abi.encodePacked(prefix, _x); } /// @dev Substracts two key derivation functionsas `s1*A - s2*B`. /// @param _scalar1 The scalar `s1` /// @param _a1 The `x` coordinate of point `A` /// @param _a2 The `y` coordinate of point `A` /// @param _scalar2 The scalar `s2` /// @param _b1 The `x` coordinate of point `B` /// @param _b2 The `y` coordinate of point `B` /// @return The derived point in affine cooridnates function ecMulSubMul( uint256 _scalar1, uint256 _a1, uint256 _a2, uint256 _scalar2, uint256 _b1, uint256 _b2) internal pure returns (uint256, uint256) { (uint256 m1, uint256 m2) = derivePoint(_scalar1, _a1, _a2); (uint256 n1, uint256 n2) = derivePoint(_scalar2, _b1, _b2); (uint256 r1, uint256 r2) = EllipticCurve.ecSub( m1, m2, n1, n2, AA, PP); return (r1, r2); } /// @dev Verify an Elliptic Curve multiplication of the form `(qx,qy) = scalar*(x,y)` by using the precompiled `ecrecover` function. /// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes. /// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 /// @param _scalar The scalar of the point multiplication /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @param _qx The coordinate `x` of the multiplication result /// @param _qy The coordinate `y` of the multiplication result /// @return true, if first 20 bytes match function ecMulVerify( uint256 _scalar, uint256 _x, uint256 _y, uint256 _qx, uint256 _qy) internal pure returns(bool) { address result = ecrecover( 0, _y % 2 != 0 ? 28 : 27, bytes32(_x), bytes32(mulmod(_scalar, _x, NN))); return pointToAddress(_qx, _qy) == result; } /// @dev Verify an Elliptic Curve operation of the form `Q = scalar1*(gx,gy) - scalar2*(x,y)` by using the precompiled `ecrecover` function, where `(gx,gy)` is the generator of the EC. /// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes. /// Based on SolCrypto library: https://github.com/HarryR/solcrypto /// @param _scalar1 The scalar of the multiplication of `(gx,gy)` /// @param _scalar2 The scalar of the multiplication of `(x,y)` /// @param _x The coordinate `x` of the point to be mutiply by `scalar2` /// @param _y The coordinate `y` of the point to be mutiply by `scalar2` /// @param _qx The coordinate `x` of the equation result /// @param _qy The coordinate `y` of the equation result /// @return true, if first 20 bytes match function ecMulSubMulVerify( uint256 _scalar1, uint256 _scalar2, uint256 _x, uint256 _y, uint256 _qx, uint256 _qy) internal pure returns(bool) { uint256 scalar1 = (NN - _scalar1) % NN; scalar1 = mulmod(scalar1, _x, NN); uint256 scalar2 = (NN - _scalar2) % NN; address result = ecrecover( bytes32(scalar1), _y % 2 != 0 ? 28 : 27, bytes32(_x), bytes32(mulmod(scalar2, _x, NN))); return pointToAddress(_qx, _qy) == result; } /// @dev Gets the address corresponding to the EC point digest (keccak256), i.e. the first 20 bytes of the digest. /// This function is used for performing a fast EC multiplication verification. /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @return The address of the EC point digest (keccak256) function pointToAddress(uint256 _x, uint256 _y) internal pure returns(address) { return address(uint256(keccak256(abi.encodePacked(_x, _y))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } } // File: witnet-ethereum-bridge/contracts/ActiveBridgeSetLib.sol /** * @title Active Bridge Set (ABS) library * @notice This library counts the number of bridges that were active recently. */ library ActiveBridgeSetLib { // Number of Ethereum blocks during which identities can be pushed into a single activity slot uint8 public constant CLAIM_BLOCK_PERIOD = 8; // Number of activity slots in the ABS uint8 public constant ACTIVITY_LENGTH = 100; struct ActiveBridgeSet { // Mapping of activity slots with participating identities mapping (uint16 => address[]) epochIdentities; // Mapping of identities with their participation count mapping (address => uint16) identityCount; // Number of identities in the Active Bridge Set (consolidated during `ACTIVITY_LENGTH`) uint32 activeIdentities; // Number of identities for the next activity slot (to be updated in the next activity slot) uint32 nextActiveIdentities; // Last used block number during an activity update uint256 lastBlockNumber; } modifier validBlockNumber(uint256 _blockFromArguments, uint256 _blockFromContractState) { require (_blockFromArguments >= _blockFromContractState, "The provided block is older than the last updated block"); _; } /// @dev Updates activity in Witnet without requiring protocol participation. /// @param _abs The Active Bridge Set structure to be updated. /// @param _blockNumber The block number up to which the activity should be updated. function updateActivity(ActiveBridgeSet storage _abs, uint256 _blockNumber) internal validBlockNumber(_blockNumber, _abs.lastBlockNumber) { (uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber); // Avoid gas cost if ABS is up to date require( updateABS( _abs, currentSlot, lastSlot, overflow ), "The ABS was already up to date"); _abs.lastBlockNumber = _blockNumber; } /// @dev Pushes activity updates through protocol activities (implying insertion of identity). /// @param _abs The Active Bridge Set structure to be updated. /// @param _address The address pushing the activity. /// @param _blockNumber The block number up to which the activity should be updated. function pushActivity(ActiveBridgeSet storage _abs, address _address, uint256 _blockNumber) internal validBlockNumber(_blockNumber, _abs.lastBlockNumber) returns (bool success) { (uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber); // Update ABS and if it was already up to date, check if identities already counted if ( updateABS( _abs, currentSlot, lastSlot, overflow )) { _abs.lastBlockNumber = _blockNumber; } else { // Check if address was already counted as active identity in this current activity slot uint256 epochIdsLength = _abs.epochIdentities[currentSlot].length; for (uint256 i; i < epochIdsLength; i++) { if (_abs.epochIdentities[currentSlot][i] == _address) { return false; } } } // Update current activity slot with identity: // 1. Add currentSlot to `epochIdentities` with address // 2. If count = 0, increment by 1 `nextActiveIdentities` // 3. Increment by 1 the count of the identity _abs.epochIdentities[currentSlot].push(_address); if (_abs.identityCount[_address] == 0) { _abs.nextActiveIdentities++; } _abs.identityCount[_address]++; return true; } /// @dev Checks if an address is a member of the ABS. /// @param _abs The Active Bridge Set structure from the Witnet Requests Board. /// @param _address The address to check. /// @return true if address is member of ABS. function absMembership(ActiveBridgeSet storage _abs, address _address) internal view returns (bool) { return _abs.identityCount[_address] > 0; } /// @dev Gets the slots of the last block seen by the ABS provided and the block number provided. /// @param _abs The Active Bridge Set structure containing the last block. /// @param _blockNumber The block number from which to get the current slot. /// @return (currentSlot, lastSlot, overflow), where overflow implies the block difference &gt; CLAIM_BLOCK_PERIOD* ACTIVITY_LENGTH. function getSlots(ActiveBridgeSet storage _abs, uint256 _blockNumber) private view returns (uint8, uint8, bool) { // Get current activity slot number uint8 currentSlot = uint8((_blockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH); // Get last actitivy slot number uint8 lastSlot = uint8((_abs.lastBlockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH); // Check if there was an activity slot overflow // `ACTIVITY_LENGTH` is changed to `uint16` here to ensure the multiplication doesn't overflow silently bool overflow = (_blockNumber - _abs.lastBlockNumber) >= CLAIM_BLOCK_PERIOD * uint16(ACTIVITY_LENGTH); return (currentSlot, lastSlot, overflow); } /// @dev Updates the provided ABS according to the slots provided. /// @param _abs The Active Bridge Set to be updated. /// @param _currentSlot The current slot. /// @param _lastSlot The last slot seen by the ABS. /// @param _overflow Whether the current slot has overflown the last slot. /// @return True if update occurred. function updateABS( ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot, bool _overflow) private returns (bool) { // If there are more than `ACTIVITY_LENGTH` slots empty => remove entirely the ABS if (_overflow) { flushABS(_abs, _lastSlot, _lastSlot); // If ABS are not up to date => fill previous activity slots with empty activities } else if (_currentSlot != _lastSlot) { flushABS(_abs, _currentSlot, _lastSlot); } else { return false; } return true; } /// @dev Flushes the provided ABS record between lastSlot and currentSlot. /// @param _abs The Active Bridge Set to be flushed. /// @param _currentSlot The current slot. function flushABS(ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot) private { // For each slot elapsed, remove identities and update `nextActiveIdentities` count for (uint16 slot = (_lastSlot + 1) % ACTIVITY_LENGTH ; slot != _currentSlot ; slot = (slot + 1) % ACTIVITY_LENGTH) { flushSlot(_abs, slot); } // Update current activity slot flushSlot(_abs, _currentSlot); _abs.activeIdentities = _abs.nextActiveIdentities; } /// @dev Flushes a slot of the provided ABS. /// @param _abs The Active Bridge Set to be flushed. /// @param _slot The slot to be flushed. function flushSlot(ActiveBridgeSet storage _abs, uint16 _slot) private { // For a given slot, go through all identities to flush them uint256 epochIdsLength = _abs.epochIdentities[_slot].length; for (uint256 id = 0; id < epochIdsLength; id++) { flushIdentity(_abs, _abs.epochIdentities[_slot][id]); } delete _abs.epochIdentities[_slot]; } /// @dev Decrements the appearance counter of an identity from the provided ABS. If the counter reaches 0, the identity is flushed. /// @param _abs The Active Bridge Set to be flushed. /// @param _address The address to be flushed. function flushIdentity(ActiveBridgeSet storage _abs, address _address) private { require(absMembership(_abs, _address), "The identity address is already out of the ARS"); // Decrement the count of an identity, and if it reaches 0, delete it and update `nextActiveIdentities`count _abs.identityCount[_address]--; if (_abs.identityCount[_address] == 0) { delete _abs.identityCount[_address]; _abs.nextActiveIdentities--; } } } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardInterface.sol /** * @title Witnet Requests Board Interface * @notice Interface of a Witnet Request Board (WRB) * It defines how to interact with the WRB in order to support: * - Post and upgrade a data request * - Read the result of a dr * @author Witnet Foundation */ interface WitnetRequestsBoardInterface { /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256); /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable; /// @dev Retrieves the DR hash of the id from the WRB. /// @param _id The unique identifier of the data request. /// @return The hash of the DR function readDrHash (uint256 _id) external view returns(uint256); /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR function readResult (uint256 _id) external view returns(bytes memory); /// @notice Verifies if the block relay can be upgraded. /// @return true if contract is upgradable. function isUpgradable(address _address) external view returns(bool); } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoard.sol /** * @title Witnet Requests Board * @notice Contract to bridge requests to Witnet. * @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network. * The result of the requests will be posted back to this contract by the bridge nodes too. * @author Witnet Foundation */ contract WitnetRequestsBoard is WitnetRequestsBoardInterface { using ActiveBridgeSetLib for ActiveBridgeSetLib.ActiveBridgeSet; // Expiration period after which a Witnet Request can be claimed again uint256 public constant CLAIM_EXPIRATION = 13; struct DataRequest { bytes dr; uint256 inclusionReward; uint256 tallyReward; bytes result; // Block number at which the DR was claimed for the last time uint256 blockNumber; uint256 drHash; address payable pkhClaim; } // Owner of the Witnet Request Board address public witnet; // Block Relay proxy prividing verification functions BlockRelayProxy public blockRelay; // Witnet Requests within the board DataRequest[] public requests; // Set of recently active bridges ActiveBridgeSetLib.ActiveBridgeSet public abs; // Replication factor for Active Bridge Set identities uint8 public repFactor; // Event emitted when a new DR is posted event PostedRequest(address indexed _from, uint256 _id); // Event emitted when a DR inclusion proof is posted event IncludedRequest(address indexed _from, uint256 _id); // Event emitted when a result proof is posted event PostedResult(address indexed _from, uint256 _id); // Ensures the reward is not greater than the value modifier payingEnough(uint256 _value, uint256 _tally) { require(_value >= _tally, "Transaction value needs to be equal or greater than tally reward"); _; } // Ensures the poe is valid modifier poeValid( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) { require( verifyPoe( _poe, _publicKey, _uPoint, _vPointHelpers), "Not a valid PoE"); _; } // Ensures signature (sign(msg.sender)) is valid modifier validSignature( uint256[2] memory _publicKey, bytes memory addrSignature) { require(verifySig(abi.encodePacked(msg.sender), _publicKey, addrSignature), "Not a valid signature"); _; } // Ensures the DR inclusion proof has not been reported yet modifier drNotIncluded(uint256 _id) { require(requests[_id].drHash == 0, "DR already included"); _; } // Ensures the DR inclusion has been already reported modifier drIncluded(uint256 _id) { require(requests[_id].drHash != 0, "DR not yet included"); _; } // Ensures the result has not been reported yet modifier resultNotIncluded(uint256 _id) { require(requests[_id].result.length == 0, "Result already included"); _; } // Ensures the VRF is valid modifier vrfValid( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) virtual { require( VRF.fastVerify( _publicKey, _poe, getLastBeacon(), _uPoint, _vPointHelpers), "Not a valid VRF"); _; } // Ensures the address belongs to the active bridge set modifier absMember(address _address) { require(abs.absMembership(_address), "Not a member of the ABS"); _; } /** * @notice Include an address to specify the Witnet Block Relay and a replication factor. * @param _blockRelayAddress BlockRelayProxy address. * @param _repFactor replication factor. */ constructor(address _blockRelayAddress, uint8 _repFactor) public { blockRelay = BlockRelayProxy(_blockRelayAddress); witnet = msg.sender; // Insert an empty request so as to initialize the requests array with length > 0 DataRequest memory request; requests.push(request); repFactor = _repFactor; } /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _serialized The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _serialized, uint256 _tallyReward) external payable payingEnough(msg.value, _tallyReward) override returns(uint256) { // The initial length of the `requests` array will become the ID of the request for everything related to the WRB uint256 id = requests.length; // Create a new `DataRequest` object and initialize all the non-default fields DataRequest memory request; request.dr = _serialized; request.inclusionReward = SafeMath.sub(msg.value, _tallyReward); request.tallyReward = _tallyReward; // Push the new request into the contract state requests.push(request); // Let observers know that a new request has been posted emit PostedRequest(msg.sender, id); return id; } /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable payingEnough(msg.value, _tallyReward) resultNotIncluded(_id) override { if (requests[_id].drHash != 0) { require( msg.value == _tallyReward, "Txn value should equal result reward argument (request reward already paid)" ); requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward); } else { requests[_id].inclusionReward = SafeMath.add(requests[_id].inclusionReward, msg.value - _tallyReward); requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward); } } /// @dev Checks if the data requests from a list are claimable or not. /// @param _ids The list of data request identifiers to be checked. /// @return An array of booleans indicating if data requests are claimable or not. function checkDataRequestsClaimability(uint256[] calldata _ids) external view returns (bool[] memory) { uint256 idsLength = _ids.length; bool[] memory validIds = new bool[](idsLength); for (uint i = 0; i < idsLength; i++) { uint256 index = _ids[i]; validIds[i] = (dataRequestCanBeClaimed(requests[index])) && requests[index].drHash == 0 && index < requests.length && requests[index].result.length == 0; } return validIds; } /// @dev Presents a proof of inclusion to prove that the request was posted into Witnet so as to unlock the inclusion reward that was put aside for the claiming identity (public key hash). /// @param _id The unique identifier of the data request. /// @param _poi A proof of inclusion proving that the data request appears listed in one recent block in Witnet. /// @param _index The index in the merkle tree. /// @param _blockHash The hash of the block in which the data request was inserted. /// @param _epoch The epoch in which the blockHash was created. function reportDataRequestInclusion( uint256 _id, uint256[] calldata _poi, uint256 _index, uint256 _blockHash, uint256 _epoch) external drNotIncluded(_id) { // Check the data request has been claimed require(dataRequestCanBeClaimed(requests[_id]) == false, "Data Request has not yet been claimed"); uint256 drOutputHash = uint256(sha256(requests[_id].dr)); uint256 drHash = uint256(sha256(abi.encodePacked(drOutputHash, _poi[0]))); // Update the state upon which this function depends before the external call requests[_id].drHash = drHash; require( blockRelay.verifyDrPoi( _poi, _blockHash, _epoch, _index, drOutputHash), "Invalid PoI"); requests[_id].pkhClaim.transfer(requests[_id].inclusionReward); // Push requests[_id].pkhClaim to abs abs.pushActivity(requests[_id].pkhClaim, block.number); emit IncludedRequest(msg.sender, _id); } /// @dev Reports the result of a data request in Witnet. /// @param _id The unique identifier of the data request. /// @param _poi A proof of inclusion proving that the data in _result has been acknowledged by the Witnet network as being the final result for the data request by putting in a tally transaction inside a Witnet block. /// @param _index The position of the tally transaction in the tallies-only merkle tree in the Witnet block. /// @param _blockHash The hash of the block in which the result (tally) was inserted. /// @param _epoch The epoch in which the blockHash was created. /// @param _result The result itself as bytes. function reportResult( uint256 _id, uint256[] calldata _poi, uint256 _index, uint256 _blockHash, uint256 _epoch, bytes calldata _result) external drIncluded(_id) resultNotIncluded(_id) absMember(msg.sender) { // Ensures the result byes do not have zero length // This would not be a valid encoding with CBOR and could trigger a reentrancy attack require(_result.length != 0, "Result has zero length"); // Update the state upon which this function depends before the external call requests[_id].result = _result; uint256 resHash = uint256(sha256(abi.encodePacked(requests[_id].drHash, _result))); require( blockRelay.verifyTallyPoi( _poi, _blockHash, _epoch, _index, resHash), "Invalid PoI"); msg.sender.transfer(requests[_id].tallyReward); emit PostedResult(msg.sender, _id); } /// @dev Retrieves the bytes of the serialization of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the data request as bytes. function readDataRequest(uint256 _id) external view returns(bytes memory) { require(requests.length > _id, "Id not found"); return requests[_id].dr; } /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR function readResult(uint256 _id) external view override returns(bytes memory) { require(requests.length > _id, "Id not found"); return requests[_id].result; } /// @dev Retrieves hash of the data request transaction in Witnet. /// @param _id The unique identifier of the data request. /// @return The hash of the DataRequest transaction in Witnet. function readDrHash(uint256 _id) external view override returns(uint256) { require(requests.length > _id, "Id not found"); return requests[_id].drHash; } /// @dev Returns the number of data requests in the WRB. /// @return the number of data requests in the WRB. function requestsCount() external view returns(uint256) { return requests.length; } /// @notice Wrapper around the decodeProof from VRF library. /// @dev Decode VRF proof from bytes. /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. /// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. function decodeProof(bytes calldata _proof) external pure returns (uint[4] memory) { return VRF.decodeProof(_proof); } /// @notice Wrapper around the decodePoint from VRF library. /// @dev Decode EC point from bytes. /// @param _point The EC point as bytes. /// @return The point as `[point-x, point-y]`. function decodePoint(bytes calldata _point) external pure returns (uint[2] memory) { return VRF.decodePoint(_point); } /// @dev Wrapper around the computeFastVerifyParams from VRF library. /// @dev Compute the parameters (EC points) required for the VRF fast verification function.. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`. /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. /// @param _message The message (in bytes) used for computing the VRF. /// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`. function computeFastVerifyParams(uint256[2] calldata _publicKey, uint256[4] calldata _proof, bytes calldata _message) external pure returns (uint256[2] memory, uint256[4] memory) { return VRF.computeFastVerifyParams(_publicKey, _proof, _message); } /// @dev Updates the ABS activity with the block number provided. /// @param _blockNumber update the ABS until this block number. function updateAbsActivity(uint256 _blockNumber) external { require (_blockNumber <= block.number, "The provided block number has not been reached"); abs.updateActivity(_blockNumber); } /// @dev Verifies if the contract is upgradable. /// @return true if the contract upgradable. function isUpgradable(address _address) external view override returns(bool) { if (_address == witnet) { return true; } return false; } /// @dev Claim drs to be posted to Witnet by the node. /// @param _ids Data request ids to be claimed. /// @param _poe PoE claiming eligibility. /// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y. /// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma. function claimDataRequests( uint256[] memory _ids, uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers, bytes memory addrSignature) public validSignature(_publicKey, addrSignature) poeValid(_poe,_publicKey, _uPoint,_vPointHelpers) returns(bool) { for (uint i = 0; i < _ids.length; i++) { require( dataRequestCanBeClaimed(requests[_ids[i]]), "One of the listed data requests was already claimed" ); requests[_ids[i]].pkhClaim = msg.sender; requests[_ids[i]].blockNumber = block.number; } return true; } /// @dev Read the beacon of the last block inserted. /// @return bytes to be signed by the node as PoE. function getLastBeacon() public view virtual returns(bytes memory) { return blockRelay.getLastBeacon(); } /// @dev Claim drs to be posted to Witnet by the node. /// @param _poe PoE claiming eligibility. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`. /// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y. /// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma. function verifyPoe( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) internal view vrfValid(_poe,_publicKey, _uPoint,_vPointHelpers) returns(bool) { uint256 vrf = uint256(VRF.gammaToHash(_poe[0], _poe[1])); // True if vrf/(2^{256} -1) <= repFactor/abs.activeIdentities if (abs.activeIdentities < repFactor) { return true; } // We rewrote it as vrf <= ((2^{256} -1)/abs.activeIdentities)*repFactor to gain efficiency if (vrf <= ((~uint256(0)/abs.activeIdentities)*repFactor)) { return true; } return false; } /// @dev Verifies the validity of a signature. /// @param _message message to be verified. /// @param _publicKey public key of the signer as `[pubKey-x, pubKey-y]`. /// @param _addrSignature the signature to verify asas r||s||v. /// @return true or false depending the validity. function verifySig( bytes memory _message, uint256[2] memory _publicKey, bytes memory _addrSignature) internal pure returns(bool) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_addrSignature, 0x20)) s := mload(add(_addrSignature, 0x40)) v := byte(0, mload(add(_addrSignature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return false; } if (v != 0 && v != 1) { return false; } v = 28 - v; bytes32 msgHash = sha256(_message); address hashedKey = VRF.pointToAddress(_publicKey[0], _publicKey[1]); return ecrecover( msgHash, v, r, s) == hashedKey; } function dataRequestCanBeClaimed(DataRequest memory _request) private view returns (bool) { return (_request.blockNumber == 0 || block.number - _request.blockNumber > CLAIM_EXPIRATION) && _request.drHash == 0 && _request.result.length == 0; } } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardProxy.sol /** * @title Block Relay Proxy * @notice Contract to act as a proxy between the Witnet Bridge Interface and the Block Relay. * @author Witnet Foundation */ contract WitnetRequestsBoardProxy { // Address of the Witnet Request Board contract that is currently being used address public witnetRequestsBoardAddress; // Struct if the information of each controller struct ControllerInfo { // Address of the Controller address controllerAddress; // The lastId of the previous Controller uint256 lastId; } // Last id of the WRB controller uint256 internal currentLastId; // Instance of the current WitnetRequestBoard WitnetRequestsBoardInterface internal witnetRequestsBoardInstance; // Array with the controllers that have been used in the Proxy ControllerInfo[] internal controllers; modifier notIdentical(address _newAddress) { require(_newAddress != witnetRequestsBoardAddress, "The provided Witnet Requests Board instance address is already in use"); _; } /** * @notice Include an address to specify the Witnet Request Board. * @param _witnetRequestsBoardAddress WitnetRequestBoard address. */ constructor(address _witnetRequestsBoardAddress) public { // Initialize the first epoch pointing to the first controller controllers.push(ControllerInfo({controllerAddress: _witnetRequestsBoardAddress, lastId: 0})); witnetRequestsBoardAddress = _witnetRequestsBoardAddress; witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_witnetRequestsBoardAddress); } /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256) { uint256 n = controllers.length; uint256 offset = controllers[n - 1].lastId; // Update the currentLastId with the id in the controller plus the offSet currentLastId = witnetRequestsBoardInstance.postDataRequest{value: msg.value}(_dr, _tallyReward) + offset; return currentLastId; } /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable { address wrbAddress; uint256 wrbOffset; (wrbAddress, wrbOffset) = getController(_id); return witnetRequestsBoardInstance.upgradeDataRequest{value: msg.value}(_id - wrbOffset, _tallyReward); } /// @dev Retrieves the DR hash of the id from the WRB. /// @param _id The unique identifier of the data request. /// @return The hash of the DR. function readDrHash (uint256 _id) external view returns(uint256) { // Get the address and the offset of the corresponding to id address wrbAddress; uint256 offsetWrb; (wrbAddress, offsetWrb) = getController(_id); // Return the result of the DR readed in the corresponding Controller with its own id WitnetRequestsBoardInterface wrbWithDrHash; wrbWithDrHash = WitnetRequestsBoardInterface(wrbAddress); uint256 drHash = wrbWithDrHash.readDrHash(_id - offsetWrb); return drHash; } /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR. function readResult(uint256 _id) external view returns(bytes memory) { // Get the address and the offset of the corresponding to id address wrbAddress; uint256 offSetWrb; (wrbAddress, offSetWrb) = getController(_id); // Return the result of the DR in the corresponding Controller with its own id WitnetRequestsBoardInterface wrbWithResult; wrbWithResult = WitnetRequestsBoardInterface(wrbAddress); return wrbWithResult.readResult(_id - offSetWrb); } /// @notice Upgrades the Witnet Requests Board if the current one is upgradeable. /// @param _newAddress address of the new block relay to upgrade. function upgradeWitnetRequestsBoard(address _newAddress) public notIdentical(_newAddress) { // Require the WRB is upgradable require(witnetRequestsBoardInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation"); // Map the currentLastId to the corresponding witnetRequestsBoardAddress and add it to controllers controllers.push(ControllerInfo({controllerAddress: _newAddress, lastId: currentLastId})); // Upgrade the WRB witnetRequestsBoardAddress = _newAddress; witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_newAddress); } /// @notice Gets the controller from an Id. /// @param _id id of a Data Request from which we get the controller. function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) { // Check id is bigger than 0 require(_id > 0, "Non-existent controller for id 0"); uint256 n = controllers.length; // If the id is bigger than the lastId of a Controller, read the result in that Controller for (uint i = n; i > 0; i--) { if (_id > controllers[i - 1].lastId) { return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId); } } } } // File: witnet-ethereum-bridge/contracts/BufferLib.sol /** * @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface * @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will * start with the byte that goes right after the last one in the previous read. * @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some * theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded. */ library BufferLib { struct Buffer { bytes data; uint32 cursor; } // Ensures we access an existing index in an array modifier notOutOfBounds(uint32 index, uint256 length) { require(index < length, "Tried to read from a consumed Buffer (must rewind it first)"); _; } /** * @notice Read and consume a certain amount of bytes from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @param _length How many bytes to read and consume from the buffer. * @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position. */ function read(Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) { // Make sure not to read out of the bounds of the original bytes require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading"); // Create a new `bytes memory destination` value bytes memory destination = new bytes(_length); bytes memory source = _buffer.data; uint32 offset = _buffer.cursor; // Get raw pointers for source and destination uint sourcePointer; uint destinationPointer; assembly { sourcePointer := add(add(source, 32), offset) destinationPointer := add(destination, 32) } // Copy `_length` bytes from source to destination memcpy(destinationPointer, sourcePointer, uint(_length)); // Move the cursor forward by `_length` bytes seek(_buffer, _length, true); return destination; } /** * @notice Read and consume the next byte from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @return The next byte in the buffer counting from the cursor position. */ function next(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (byte) { // Return the byte at the position marked by the cursor and advance the cursor all at once return _buffer.data[_buffer.cursor++]; } /** * @notice Move the inner cursor of the buffer to a relative or absolute position. * @param _buffer An instance of `BufferLib.Buffer`. * @param _offset How many bytes to move the cursor forward. * @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the * buffer (`true`). * @return The final position of the cursor (will equal `_offset` if `_relative` is `false`). */ // solium-disable-next-line security/no-assign-params function seek(Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) { // Deal with relative offsets if (_relative) { require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking"); _offset += _buffer.cursor; } // Make sure not to read out of the bounds of the original bytes require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking"); _buffer.cursor = _offset; return _buffer.cursor; } /** * @notice Move the inner cursor a number of bytes forward. * @dev This is a simple wrapper around the relative offset case of `seek()`. * @param _buffer An instance of `BufferLib.Buffer`. * @param _relativeOffset How many bytes to move the cursor forward. * @return The final position of the cursor. */ function seek(Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) { return seek(_buffer, _relativeOffset, true); } /** * @notice Move the inner cursor back to the first byte in the buffer. * @param _buffer An instance of `BufferLib.Buffer`. */ function rewind(Buffer memory _buffer) internal pure { _buffer.cursor = 0; } /** * @notice Read and consume the next byte from the buffer as an `uint8`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint8` value of the next byte in the buffer counting from the cursor position. */ function readUint8(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint8 value; assembly { value := mload(add(add(bytesValue, 1), offset)) } _buffer.cursor++; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an `uint16`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position. */ function readUint16(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint16 value; assembly { value := mload(add(add(bytesValue, 2), offset)) } _buffer.cursor += 2; return value; } /** * @notice Read and consume the next 4 bytes from the buffer as an `uint32`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readUint32(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint32 value; assembly { value := mload(add(add(bytesValue, 4), offset)) } _buffer.cursor += 4; return value; } /** * @notice Read and consume the next 8 bytes from the buffer as an `uint64`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position. */ function readUint64(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint64 value; assembly { value := mload(add(add(bytesValue, 8), offset)) } _buffer.cursor += 8; return value; } /** * @notice Read and consume the next 16 bytes from the buffer as an `uint128`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position. */ function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } _buffer.cursor += 16; return value; } /** * @notice Read and consume the next 32 bytes from the buffer as an `uint256`. * @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position. * @param _buffer An instance of `BufferLib.Buffer`. */ function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint256 value; assembly { value := mload(add(add(bytesValue, 32), offset)) } _buffer.cursor += 32; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an * `int32`. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16` * use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are * expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readFloat16(Buffer memory _buffer) internal pure returns (int32) { uint32 bytesValue = readUint16(_buffer); // Get bit at position 0 uint32 sign = bytesValue & 0x8000; // Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15; // Get bits 6 to 15 int32 significand = int32(bytesValue & 0x03ff); // Add 1024 to the fraction if the exponent is 0 if (exponent == 15) { significand |= 0x400; } // Compute `2 ^ exponent · (1 + fraction / 1024)` int32 result = 0; if (exponent >= 0) { result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10); } else { result = int32((((uint256(significand) | 0x400) * 10000) / (1 << uint256(- exponent))) >> 10); } // Make the result negative if the sign bit is not 0 if (sign != 0) { result *= - 1; } return result; } /** * @notice Copy bytes from one memory address into another. * @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms * of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE). * @param _dest Address of the destination memory. * @param _src Address to the source memory. * @param _len How many bytes to copy. */ // solium-disable-next-line security/no-assign-params function memcpy(uint _dest, uint _src, uint _len) private pure { // 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)) } } } // File: witnet-ethereum-bridge/contracts/CBOR.sol /** * @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation” * @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize * the gas cost of decoding them into a useful native type. * @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js * TODO: add support for Array (majorType = 4) * TODO: add support for Map (majorType = 5) * TODO: add support for Float32 (majorType = 7, additionalInformation = 26) * TODO: add support for Float64 (majorType = 7, additionalInformation = 27) */ library CBOR { using BufferLib for BufferLib.Buffer; uint64 constant internal UINT64_MAX = ~uint64(0); struct Value { BufferLib.Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /** * @notice Decode a `CBOR.Value` structure into a native `bytes` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `bytes` value. */ function decodeBytes(Value memory _cborValue) public pure returns(bytes memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory bytesData; // These checks look repetitive but the equivalent loop would be more expensive. uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT64_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT64_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); } } return bytesData; } else { return _cborValue.buffer.read(uint32(_cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a `fixed16` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16` * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeFixed16(Value memory _cborValue) public pure returns(int32) { require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `CBOR.Value` with majorType != 7"); require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `CBOR.Value` with additionalInformation != 25"); return _cborValue.buffer.readFloat16(); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value whose inner values follow the same convention. * as explained in `decodeFixed16`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeFixed16Array(Value memory _cborValue) public pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeFixed16(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `int128` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeInt128(Value memory _cborValue) public pure returns(int128) { if (_cborValue.majorType == 1) { uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); return int128(-1) - int128(length); } else if (_cborValue.majorType == 0) { // Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer // a uniform API for positive and negative numbers return int128(decodeUint64(_cborValue)); } revert("Tried to read `int128` from a `CBOR.Value` with majorType not 0 or 1"); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeInt128Array(Value memory _cborValue) public pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `string` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `string` value. */ function decodeString(Value memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a native `string[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `string[]` value. */ function decodeStringArray(Value memory _cborValue) public pure returns(string[] memory) { require(_cborValue.majorType == 4, "Tried to read `string[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); string[] memory array = new string[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeString(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `uint64` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64` value. */ function decodeUint64(Value memory _cborValue) public pure returns(uint64) { require(_cborValue.majorType == 0, "Tried to read `uint64` from a `CBOR.Value` with majorType != 0"); return readLength(_cborValue.buffer, _cborValue.additionalInformation); } /** * @notice Decode a `CBOR.Value` structure into a native `uint64[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64[]` value. */ function decodeUint64Array(Value memory _cborValue) public pure returns(uint64[] memory) { require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); uint64[] memory array = new uint64[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeUint64(item); } return array; } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is the main factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBytes(bytes memory _cborBytes) public pure returns(Value memory) { BufferLib.Buffer memory buffer = BufferLib.Buffer(_cborBytes, 0); return valueFromBuffer(buffer); } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _buffer A Buffer structure representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) { require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value"); uint8 initialByte; uint8 majorType = 255; uint8 additionalInformation; uint64 length; uint64 tag = UINT64_MAX; bool isTagged = true; while (isTagged) { // Extract basic CBOR properties from input bytes initialByte = _buffer.readUint8(); majorType = initialByte >> 5; additionalInformation = initialByte & 0x1f; // Early CBOR tag parsing. if (majorType == 6) { tag = readLength(_buffer, additionalInformation); } else { isTagged = false; } } require(majorType <= 7, "Invalid CBOR major type"); return CBOR.Value( _buffer, initialByte, majorType, additionalInformation, length, tag); } // Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the // value of the `additionalInformation` argument. function readLength(BufferLib.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) { if (additionalInformation < 24) { return additionalInformation; } if (additionalInformation == 24) { return _buffer.readUint8(); } if (additionalInformation == 25) { return _buffer.readUint16(); } if (additionalInformation == 26) { return _buffer.readUint32(); } if (additionalInformation == 27) { return _buffer.readUint64(); } if (additionalInformation == 31) { return UINT64_MAX; } revert("Invalid length encoding (non-existent additionalInformation value)"); } // Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming // as many bytes as specified by the first byte. function readIndefiniteStringLength(BufferLib.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) { uint8 initialByte = _buffer.readUint8(); if (initialByte == 0xff) { return UINT64_MAX; } uint64 length = readLength(_buffer, initialByte & 0x1f); require(length < UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length"); return length; } // Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness, // but it can be easily casted into a string with `string(result)`. // solium-disable-next-line security/no-assign-params function readText(BufferLib.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) { bytes memory result; for (uint64 index = 0; index < _length; index++) { uint8 value = _buffer.readUint8(); if (value & 0x80 != 0) { if (value < 0xe0) { value = (value & 0x1f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 1; } else if (value < 0xf0) { value = (value & 0x0f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 2; } else { value = (value & 0x0f) << 18 | (_buffer.readUint8() & 0x3f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 3; } } result = abi.encodePacked(result, value); } return result; } } // File: witnet-ethereum-bridge/contracts/Witnet.sol /** * @title A library for decoding Witnet request results * @notice The library exposes functions to check the Witnet request success. * and retrieve Witnet results from CBOR values into solidity types. */ library Witnet { using CBOR for CBOR.Value; /* STRUCTS */ struct Result { bool success; CBOR.Value cborValue; } /* ENUMS */ enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid RADON script. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, Size } /* Result impl's */ /** * @notice Decode raw CBOR bytes into a Result instance. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `Result` instance. */ function resultFromCborBytes(bytes calldata _cborBytes) external pure returns(Result memory) { CBOR.Value memory cborValue = CBOR.valueFromBytes(_cborBytes); return resultFromCborValue(cborValue); } /** * @notice Decode a CBOR value into a Result instance. * @param _cborValue An instance of `CBOR.Value`. * @return A `Result` instance. */ function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) { // Witnet uses CBOR tag 39 to represent RADON error code identifiers. // [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md bool success = _cborValue.tag != 39; return Result(success, _cborValue); } /** * @notice Tell if a Result is successful. * @param _result An instance of Result. * @return `true` if successful, `false` if errored. */ function isOk(Result memory _result) public pure returns(bool) { return _result.success; } /** * @notice Tell if a Result is errored. * @param _result An instance of Result. * @return `true` if errored, `false` if successful. */ function isError(Result memory _result) public pure returns(bool) { return !_result.success; } /** * @notice Decode a bytes value from a Result as a `bytes` value. * @param _result An instance of Result. * @return The `bytes` decoded from the Result. */ function asBytes(Result memory _result) public pure returns(bytes memory) { require(_result.success, "Tried to read bytes value from errored Result"); return _result.cborValue.decodeBytes(); } /** * @notice Decode an error code from a Result as a member of `ErrorCodes`. * @param _result An instance of `Result`. * @return The `CBORValue.Error memory` decoded from the Result. */ function asErrorCode(Result memory _result) public pure returns(ErrorCodes) { uint64[] memory error = asRawError(_result); return supportedErrorOrElseUnknown(error[0]); } /** * @notice Generate a suitable error message for a member of `ErrorCodes` and its corresponding arguments. * @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function * @param _result An instance of `Result`. * @return A tuple containing the `CBORValue.Error memory` decoded from the `Result`, plus a loggable error message. */ function asErrorMessage(Result memory _result) public pure returns(ErrorCodes, string memory) { uint64[] memory error = asRawError(_result); ErrorCodes errorCode = supportedErrorOrElseUnknown(error[0]); bytes memory errorMessage; if (errorCode == ErrorCodes.SourceScriptNotCBOR) { errorMessage = abi.encodePacked("Source script #", utoa(error[1]), " was not a valid CBOR value"); } else if (errorCode == ErrorCodes.SourceScriptNotArray) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not an Array of calls"); } else if (errorCode == ErrorCodes.SourceScriptNotRADON) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not a valid RADON script"); } else if (errorCode == ErrorCodes.RequestTooManySources) { errorMessage = abi.encodePacked("The request contained too many sources (", utoa(error[1]), ")"); } else if (errorCode == ErrorCodes.ScriptTooManyCalls) { errorMessage = abi.encodePacked( "Script #", utoa(error[2]), " from the ", stageName(error[1]), " stage contained too many calls (", utoa(error[3]), ")" ); } else if (errorCode == ErrorCodes.UnsupportedOperator) { errorMessage = abi.encodePacked( "Operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage is not supported" ); } else if (errorCode == ErrorCodes.HTTP) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved. Failed with HTTP error code: ", utoa(error[2] / 100), utoa(error[2] % 100 / 10), utoa(error[2] % 10) ); } else if (errorCode == ErrorCodes.RetrievalTimeout) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved because of a timeout." ); } else if (errorCode == ErrorCodes.Underflow) { errorMessage = abi.encodePacked( "Underflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.Overflow) { errorMessage = abi.encodePacked( "Overflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.DivisionByZero) { errorMessage = abi.encodePacked( "Division by zero at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else { errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")"); } return (errorCode, string(errorMessage)); } /** * @notice Decode a raw error from a `Result` as a `uint64[]`. * @param _result An instance of `Result`. * @return The `uint64[]` raw error as decoded from the `Result`. */ function asRawError(Result memory _result) public pure returns(uint64[] memory) { require(!_result.success, "Tried to read error code from successful Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Decode a fixed16 (half-precision) numeric value from a Result as an `int32` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asFixed16(Result memory _result) public pure returns(int32) { require(_result.success, "Tried to read `fixed16` value from errored Result"); return _result.cborValue.decodeFixed16(); } /** * @notice Decode an array of fixed16 values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asFixed16Array(Result memory _result) public pure returns(int128[] memory) { require(_result.success, "Tried to read `fixed16[]` value from errored Result"); return _result.cborValue.decodeFixed16Array(); } /** * @notice Decode a integer numeric value from a Result as an `int128` value. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asInt128(Result memory _result) public pure returns(int128) { require(_result.success, "Tried to read `int128` value from errored Result"); return _result.cborValue.decodeInt128(); } /** * @notice Decode an array of integer numeric values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asInt128Array(Result memory _result) public pure returns(int128[] memory) { require(_result.success, "Tried to read `int128[]` value from errored Result"); return _result.cborValue.decodeInt128Array(); } /** * @notice Decode a string value from a Result as a `string` value. * @param _result An instance of Result. * @return The `string` decoded from the Result. */ function asString(Result memory _result) public pure returns(string memory) { require(_result.success, "Tried to read `string` value from errored Result"); return _result.cborValue.decodeString(); } /** * @notice Decode an array of string values from a Result as a `string[]` value. * @param _result An instance of Result. * @return The `string[]` decoded from the Result. */ function asStringArray(Result memory _result) public pure returns(string[] memory) { require(_result.success, "Tried to read `string[]` value from errored Result"); return _result.cborValue.decodeStringArray(); } /** * @notice Decode a natural numeric value from a Result as a `uint64` value. * @param _result An instance of Result. * @return The `uint64` decoded from the Result. */ function asUint64(Result memory _result) public pure returns(uint64) { require(_result.success, "Tried to read `uint64` value from errored Result"); return _result.cborValue.decodeUint64(); } /** * @notice Decode an array of natural numeric values from a Result as a `uint64[]` value. * @param _result An instance of Result. * @return The `uint64[]` decoded from the Result. */ function asUint64Array(Result memory _result) public pure returns(uint64[] memory) { require(_result.success, "Tried to read `uint64[]` value from errored Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Convert a stage index number into the name of the matching Witnet request stage. * @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages. * @return The name of the matching stage. */ function stageName(uint64 _stageIndex) public pure returns(string memory) { if (_stageIndex == 0) { return "retrieval"; } else if (_stageIndex == 1) { return "aggregation"; } else if (_stageIndex == 2) { return "tally"; } else { return "unknown"; } } /** * @notice Get an `ErrorCodes` item from its `uint64` discriminant, or default to `ErrorCodes.Unknown` if it doesn't * exist. * @param _discriminant The numeric identifier of an error. * @return A member of `ErrorCodes`. */ function supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns(ErrorCodes) { if (_discriminant < uint8(ErrorCodes.Size)) { return ErrorCodes(_discriminant); } else { return ErrorCodes.Unknown; } } /** * @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its. * three less significant decimal values. * @param _u A `uint64` value. * @return The `string` representing its decimal value. */ function utoa(uint64 _u) private pure returns(string memory) { if (_u < 10) { bytes memory b1 = new bytes(1); b1[0] = byte(uint8(_u) + 48); return string(b1); } else if (_u < 100) { bytes memory b2 = new bytes(2); b2[0] = byte(uint8(_u / 10) + 48); b2[1] = byte(uint8(_u % 10) + 48); return string(b2); } else { bytes memory b3 = new bytes(3); b3[0] = byte(uint8(_u / 100) + 48); b3[1] = byte(uint8(_u % 100 / 10) + 48); b3[2] = byte(uint8(_u % 10) + 48); return string(b3); } } /** * @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values. * @param _u A `uint64` value. * @return The `string` representing its hexadecimal value. */ function utohex(uint64 _u) private pure returns(string memory) { bytes memory b2 = new bytes(2); uint8 d0 = uint8(_u / 16) + 48; uint8 d1 = uint8(_u % 16) + 48; if (d0 > 57) d0 += 7; if (d1 > 57) d1 += 7; b2[0] = byte(d0); b2[1] = byte(d1); return string(b2); } } // File: witnet-ethereum-bridge/contracts/Request.sol /** * @title The serialized form of a Witnet data request */ contract Request { bytes public bytecode; uint256 public id; /** * @dev A `Request` is constructed around a `bytes memory` value containing a well-formed Witnet data request serialized * using Protocol Buffers. However, we cannot verify its validity at this point. This implies that contracts using * the WRB should not be considered trustless before a valid Proof-of-Inclusion has been posted for the requests. * The hash of the request is computed in the constructor to guarantee consistency. Otherwise there could be a * mismatch and a data request could be resolved with the result of another. * @param _bytecode Witnet request in bytes. */ constructor(bytes memory _bytecode) public { bytecode = _bytecode; id = uint256(sha256(_bytecode)); } } // File: witnet-ethereum-bridge/contracts/UsingWitnet.sol /** * @title The UsingWitnet contract * @notice Contract writers can inherit this contract in order to create requests for the * Witnet network. */ contract UsingWitnet { using Witnet for Witnet.Result; WitnetRequestsBoardProxy internal wrb; /** * @notice Include an address to specify the WitnetRequestsBoard. * @param _wrb WitnetRequestsBoard address. */ constructor(address _wrb) public { wrb = WitnetRequestsBoardProxy(_wrb); } // Provides a convenient way for client contracts extending this to block the execution of the main logic of the // contract until a particular request has been successfully accepted into Witnet modifier witnetRequestAccepted(uint256 _id) { require(witnetCheckRequestAccepted(_id), "Witnet request is not yet accepted into the Witnet network"); _; } // Ensures that user-specified rewards are equal to the total transaction value to prevent users from burning any excess value modifier validRewards(uint256 _requestReward, uint256 _resultReward) { require(_requestReward + _resultReward >= _requestReward, "The sum of rewards overflows"); require(msg.value == _requestReward + _resultReward, "Transaction value should equal the sum of rewards"); _; } /** * @notice Send a new request to the Witnet network * @dev Call to `post_dr` function in the WitnetRequestsBoard contract * @param _request An instance of the `Request` contract * @param _requestReward Reward specified for the user which posts the request into Witnet * @param _resultReward Reward specified for the user which posts back the request result * @return Sequencial identifier for the request included in the WitnetRequestsBoard */ function witnetPostRequest(Request _request, uint256 _requestReward, uint256 _resultReward) internal validRewards(_requestReward, _resultReward) returns (uint256) { return wrb.postDataRequest.value(_requestReward + _resultReward)(_request.bytecode(), _resultReward); } /** * @notice Check if a request has been accepted into Witnet. * @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third. * parties) before this method returns `true`. * @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard. * @return A boolean telling if the request has been already accepted or not. `false` do not mean rejection, though. */ function witnetCheckRequestAccepted(uint256 _id) internal view returns (bool) { // Find the request in the uint256 drHash = wrb.readDrHash(_id); // If the hash of the data request transaction in Witnet is not the default, then it means that inclusion of the // request has been proven to the WRB. return drHash != 0; } /** * @notice Upgrade the rewards for a Data Request previously included. * @dev Call to `upgrade_dr` function in the WitnetRequestsBoard contract. * @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard. * @param _requestReward Reward specified for the user which posts the request into Witnet * @param _resultReward Reward specified for the user which post the Data Request result. */ function witnetUpgradeRequest(uint256 _id, uint256 _requestReward, uint256 _resultReward) internal validRewards(_requestReward, _resultReward) { wrb.upgradeDataRequest.value(msg.value)(_id, _resultReward); } /** * @notice Read the result of a resolved request. * @dev Call to `read_result` function in the WitnetRequestsBoard contract. * @param _id The sequential identifier of a request that was posted to Witnet. * @return The result of the request as an instance of `Result`. */ function witnetReadResult(uint256 _id) internal view returns (Witnet.Result memory) { return Witnet.resultFromCborBytes(wrb.readResult(_id)); } } // File: adomedianizer/contracts/IERC2362.sol /** * @dev EIP2362 Interface for pull oracles * https://github.com/tellor-io/EIP-2362 */ interface IERC2362 { /** * @dev Exposed function pertaining to EIP standards * @param _id bytes32 ID of the query * @return int,uint,uint returns the value, timestamp, and status code of query */ function valueFor(bytes32 _id) external view returns(int256,uint256,uint256); } // File: witnet-price-feeds-examples/contracts/requests/BitcoinPrice.sol // The bytecode of the BitcoinPrice request that will be sent to Witnet contract BitcoinPriceRequest is Request { constructor () Request(hex"0abb0108c3aafbf405123b122468747470733a2f2f7777772e6269747374616d702e6e65742f6170692f7469636b65722f1a13841877821864646c6173748218571903e8185b125c123168747470733a2f2f6170692e636f696e6465736b2e636f6d2f76312f6270692f63757272656e7470726963652e6a736f6e1a2786187782186663627069821866635553448218646a726174655f666c6f61748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/bitcoin_price_feed/BtcUsdPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the BitcoinPrice request that you created before // Your contract needs to inherit from UsingWitnet contract BtcUsdPriceFeed is UsingWitnet, IERC2362 { // The public Bitcoin price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is `keccak256("Price-BTC/USD-3")` bytes32 constant public BTCUSD3ID = bytes32(hex"637b7efb6b620736c247aaa282f3898914c0bef6c12faff0d3fe9d4bea783020"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new BitcoinPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != BTCUSD3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: witnet-price-feeds-examples/contracts/requests/EthPrice.sol // The bytecode of the EthPrice request that will be sent to Witnet contract EthPriceRequest is Request { constructor () Request(hex"0a850208d7affbf4051245122e68747470733a2f2f7777772e6269747374616d702e6e65742f6170692f76322f7469636b65722f6574687573642f1a13841877821864646c6173748218571903e8185b1247122068747470733a2f2f6170692e636f696e6361702e696f2f76322f6173736574731a238618778218616464617461821818018218646870726963655573648218571903e8185b1253122668747470733a2f2f6170692e636f696e70617072696b612e636f6d2f76312f7469636b6572731a29871876821818038218666671756f746573821866635553448218646570726963658218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/eth_price_feed/EthUsdPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the ethPrice request that you created before // Your contract needs to inherit from UsingWitnet contract EthUsdPriceFeed is UsingWitnet, IERC2362 { // The public eth price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is the ERC2362 identifier for a eth price feed, computed as `keccak256("Price-ETH/USD-3")` bytes32 constant public ETHUSD3ID = bytes32(hex"dfaa6f747f0f012e8f2069d6ecacff25f5cdf0258702051747439949737fc0b5"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new EthPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != ETHUSD3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: witnet-price-feeds-examples/contracts/requests/GoldPrice.sol // The bytecode of the GoldPrice request that will be sent to Witnet contract GoldPriceRequest is Request { constructor () Request(hex"0ab90308c3aafbf4051257123f68747470733a2f2f636f696e7965702e636f6d2f6170692f76312f3f66726f6d3d58415526746f3d455552266c616e673d657326666f726d61743d6a736f6e1a148418778218646570726963658218571903e8185b1253122b68747470733a2f2f646174612d6173672e676f6c6470726963652e6f72672f64625852617465732f4555521a24861877821861656974656d73821818008218646878617550726963658218571903e8185b1255123668747470733a2f2f7777772e6d7963757272656e63797472616e736665722e636f6d2f6170692f63757272656e742f5841552f4555521a1b851877821866646461746182186464726174658218571903e8185b129101125d68747470733a2f2f7777772e696e766572736f726f2e65732f6461746f732f3f706572696f643d3379656172267869676e6974655f636f64653d5841552663757272656e63793d455552267765696768745f756e69743d6f756e6365731a308518778218666a7461626c655f64617461821864736d6574616c5f70726963655f63757272656e748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/gold_price_feed/GoldEurPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the goldPrice request that you created before // Your contract needs to inherit from UsingWitnet contract GoldEurPriceFeed is UsingWitnet, IERC2362 { // The public gold price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is the ERC2362 identifier for a gold price feed, computed as `keccak256("Price-XAU/EUR-3")` bytes32 constant public XAUEUR3ID = bytes32(hex"68cba0705475e40c1ddbf7dc7c1ae4e7320ca094c4e118d1067c4dea5df28590"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new GoldPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != XAUEUR3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: contracts/Deployer.sol // Import witnet-ethereum-block-relay-contracts // Import the UsingWitnet library that enables interacting with Witnet // Import price feeds contract Deployer { } // File: contracts/Migrations.sol contract Migrations { address public owner; uint public lastCompletedMigration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint _completed) public restricted { lastCompletedMigration = _completed; } function upgrade(address _newAddress) public restricted { Migrations upgraded = Migrations(_newAddress); upgraded.setCompleted(lastCompletedMigration); } }
* @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an `int32`. @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16` use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard. @param _buffer An instance of `BufferLib.Buffer`. @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position./ Get bit at position 0 Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias Get bits 6 to 15 Add 1024 to the fraction if the exponent is 0 Make the result negative if the sign bit is not 0
function readFloat16(Buffer memory _buffer) internal pure returns (int32) { uint32 bytesValue = readUint16(_buffer); uint32 sign = bytesValue & 0x8000; int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15; int32 significand = int32(bytesValue & 0x03ff); if (exponent == 15) { significand |= 0x400; } if (exponent >= 0) { result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10); result = int32((((uint256(significand) | 0x400) * 10000) / (1 << uint256(- exponent))) >> 10); } if (sign != 0) { result *= - 1; } return result; }
901,209
[ 1, 1994, 471, 7865, 326, 1024, 576, 1731, 628, 326, 1613, 487, 392, 467, 9383, 41, 2371, 6564, 17, 6976, 28, 13861, 1634, 1300, 25636, 316, 392, 1375, 474, 1578, 8338, 225, 463, 344, 358, 326, 30679, 434, 2865, 364, 13861, 578, 5499, 1634, 30828, 316, 326, 512, 7397, 16, 333, 707, 8738, 777, 924, 635, 1381, 6970, 11077, 1427, 487, 358, 336, 279, 5499, 6039, 434, 1381, 6970, 6865, 16, 1492, 1410, 506, 7791, 364, 4486, 1375, 5659, 2313, 68, 999, 6088, 18, 657, 1308, 4511, 16, 326, 3571, 876, 434, 333, 707, 353, 1728, 16, 3784, 4124, 326, 3214, 460, 18, 1021, 810, 1731, 854, 2665, 358, 2805, 326, 2872, 17, 3682, 1026, 17, 22, 740, 261, 69, 18, 79, 18, 69, 18, 1375, 8578, 2313, 24065, 316, 326, 467, 9383, 41, 2371, 6564, 17, 6976, 28, 4529, 18, 225, 389, 4106, 1922, 791, 434, 1375, 1892, 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, 225, 445, 855, 4723, 2313, 12, 1892, 3778, 389, 4106, 13, 2713, 16618, 1135, 261, 474, 1578, 13, 288, 203, 565, 2254, 1578, 1731, 620, 273, 855, 5487, 2313, 24899, 4106, 1769, 203, 565, 2254, 1578, 1573, 273, 1731, 620, 473, 374, 92, 26021, 31, 203, 565, 509, 1578, 9100, 273, 261, 474, 1578, 12, 3890, 620, 473, 374, 92, 27, 71, 713, 13, 1671, 1728, 13, 300, 4711, 31, 203, 565, 509, 1578, 1573, 1507, 464, 273, 509, 1578, 12, 3890, 620, 473, 374, 92, 4630, 1403, 1769, 203, 203, 565, 309, 261, 24045, 422, 4711, 13, 288, 203, 1377, 1573, 1507, 464, 5626, 374, 92, 16010, 31, 203, 565, 289, 203, 203, 565, 309, 261, 24045, 1545, 374, 13, 288, 203, 1377, 563, 273, 509, 1578, 12443, 12, 21, 2296, 2254, 5034, 12, 24045, 3719, 380, 12619, 380, 261, 11890, 5034, 12, 2977, 1507, 464, 13, 571, 374, 92, 16010, 3719, 1671, 1728, 1769, 203, 1377, 563, 273, 509, 1578, 12443, 12443, 11890, 5034, 12, 2977, 1507, 464, 13, 571, 374, 92, 16010, 13, 380, 12619, 13, 342, 261, 21, 2296, 2254, 5034, 19236, 9100, 20349, 1671, 1728, 1769, 203, 565, 289, 203, 203, 565, 309, 261, 2977, 480, 374, 13, 288, 203, 1377, 563, 6413, 300, 404, 31, 203, 565, 289, 203, 565, 327, 563, 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 ]
pragma solidity >= 0.4.24 < 0.6.0; import "github.com/OpenZeppelin/zeppelin-solidity/contracts/math/SafeMath.sol"; import "github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol"; import "github.com/OpenZeppelin/zeppelin-solidity/contracts/token/ERC20/IERC20.sol"; // The following contract is Ownable design pattern and ERC20 token. contract InternetAccessToken27 is Ownable, IERC20 { // using SafeMath for uint256; // We do not need this instruction because we use the "SafeMath." form. uint256 private _totalSupply; uint256 private _tokenTotalPrice; //uint256 private _ethAmount; uint256 private _tokenValue = 0.0005 ether; uint256 private _timeSession = 1; // Value in hours. uint256 private _duration = 7; // To give the option to revert the last payment. // To manage the user data. mapping (address => uint256) private _balance; // Number of tokens stored for each user. mapping (address => uint256) private _lastTokenPayment; // To give the option to revert the last token payment. mapping (address => uint256) private _expirationToken; // To give the option to revert the last token payment. mapping (address => uint256) private _expirationETH; // To give the option to revert the last ETH payment. // event Transfer(address indexed _from, address indexed _to, uint256 _value); /** @dev Returns tokens name. */ function name() public pure returns (string memory) { return "InternetAccess"; } /** @dev Returns tokens symbol. */ function symbol() public pure returns (string memory) { return "IntacTok"; } /** @dev Returns no. decimals token uses (18 decimals). */ function decimals() public pure returns (uint8) { return 0; } /** @dev Returns totalSupply. */ function totalSupply() public view returns (uint256){ return _totalSupply; } /** @dev Returns account balance of tokens. */ function balanceOf(address _owner) public view returns (uint256) { return _balance[_owner]; } /** @dev Transfers _value amount of tokens to address _to. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_balance[msg.sender] >= _value); _balance[msg.sender] = SafeMath.sub(_balance[msg.sender], _value); _balance[_to] = SafeMath.add(_balance[_to],_value); emit Transfer(msg.sender, _to, _value); return true; } /** @dev For each _tokenValue ether, return 1 token. Variable "amount" is the number of tokens to be bought. */ function mint(uint256 amount) public payable { _tokenTotalPrice = SafeMath.mul(_tokenValue, amount); require(msg.value >= _tokenTotalPrice); // compared in weis? _totalSupply = SafeMath.add(_totalSupply, amount); _balance[msg.sender] = SafeMath.add(_balance[msg.sender], amount); } /** @dev Returns _tokenValue ether/token. Variable "amount" is the number of tokens to be sold. */ function burn(uint256 amount) public { require(amount >= 1); require(_balance[msg.sender] >= amount); //_ethAmount = SafeMath.mul(amount, _tokenValue); _totalSupply = SafeMath.sub(_totalSupply, amount); _balance[msg.sender] = SafeMath.sub(_balance[msg.sender], amount); //msg.sender.transfer(_ethAmount); } /** @dev 1 token costs _tokenValue ether. */ function getTokenValue() public view returns (uint256) { return _tokenValue; } /** @dev Establishes new token value. */ function setTokenValue(uint256 _newValue) private { _tokenValue = _newValue; } /** @dev 1 token is _timeSession hours of Internet session. */ function getTimeSession() public view returns (uint256) { return _timeSession; } /** @dev Requests an Internet connection and makes the payment through tokens. */ function reqConnectionWithToken(uint256 _tokenConsumed) public returns (bool){ require(_balance[msg.sender] >= _tokenConsumed); _lastTokenPayment[msg.sender] = _tokenConsumed; burn(_tokenConsumed); _expirationToken[msg.sender] = now + _duration; return true; // The control of the time consumed is carried out by the client. } /** @dev Requests an Internet connection and makes the payment through ETH. */ //function reqConnectionWithETH() public payable returns (uint256) { // // uint256 _numberSessions; // require(msg.value > 0); // _numberSessions = SafeMath.div(msg.value, _tokenValue); // _expirationETH[msg.sender] = now + _duration; // return _numberSessions; // // Returns to the React client, the number of sessions that you can connect to the Internet. The control of the time consumed is carried out by the client. // // Internet Access time of the client will be equal to _numberSessions * getTimeSession() //} /** @dev Reverts last token payment. */ function revertTokenPayment() public returns (bool) { require(_lastTokenPayment[msg.sender] > 0); require(_expirationToken[msg.sender] > now); _balance[msg.sender] = SafeMath.add(_balance[msg.sender], _lastTokenPayment[msg.sender]); _lastTokenPayment[msg.sender] = 0; return true; // Last token payment reverted successfully. } /** @dev Reverts last ETH payment. */ //function revertETHPayment() public payable returns (bool) { // require(_expirationETH[msg.sender] > now); // revert(); // return true; // // Last ETH payment reverted successfully. //} } // Some code commented lines correspond to previous version of the smart contract. // With ETH and token together. On Wednesday, September 11, 2019.
/ The control of the time consumed is carried out by the client.
function reqConnectionWithToken(uint256 _tokenConsumed) public returns (bool){ require(_balance[msg.sender] >= _tokenConsumed); _lastTokenPayment[msg.sender] = _tokenConsumed; burn(_tokenConsumed); _expirationToken[msg.sender] = now + _duration; return true; }
15,786,529
[ 1, 19, 1021, 3325, 434, 326, 813, 12393, 353, 5926, 24012, 596, 635, 326, 1004, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1111, 1952, 1190, 1345, 12, 11890, 5034, 389, 2316, 20554, 13, 1071, 1135, 261, 6430, 15329, 203, 202, 203, 3639, 2583, 24899, 12296, 63, 3576, 18, 15330, 65, 1545, 389, 2316, 20554, 1769, 203, 203, 3639, 389, 2722, 1345, 6032, 63, 3576, 18, 15330, 65, 273, 389, 2316, 20554, 31, 203, 3639, 18305, 24899, 2316, 20554, 1769, 203, 3639, 389, 19519, 1345, 63, 3576, 18, 15330, 65, 273, 2037, 397, 389, 8760, 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 ]
./full_match/5/0x1caD01f5028d265E079096B3fBF6E102f7708eE1/sources/project_/contracts/Main.sol
* @dev ends minting upon maturity (and within permitted Withdrawal time Window) mints XEX coins and stakes 'pct' of it for 'term'/ require(pct > 0, "CRank: Cannot share zero percent"); calculate reward mint reward tokens part nothing to burn since we haven't minted this part yet stake extra tokens part
function claimMintRewardAndStake(uint256 pct, uint256 term) external payable checkFee { MintInfo memory mintInfo = userMints[_msgSender()]; require(pct < 101); require(mintInfo.rank > 0); require(block.timestamp > mintInfo.maturityTs); uint256 rewardAmount = _calculateMintReward( mintInfo.rank, mintInfo.term, mintInfo.maturityTs, mintInfo.amplifier, mintInfo.eaaRate ) * 1 ether; uint256 stakedReward = (rewardAmount * pct) / 100; uint256 ownReward = rewardAmount - stakedReward; _mint(_msgSender(), ownReward); _mint(treasure, rewardAmount / 100); _cleanUpUserMint(); emit MintClaimed(_msgSender(), rewardAmount); require(stakedReward > XEX_MIN_STAKE); require(term * SECONDS_IN_DAY > MIN_TERM); require(term * SECONDS_IN_DAY < MAX_TERM_END + 1); require(userStakes[_msgSender()].amount == 0); _createStake(stakedReward, term); emit Staked(_msgSender(), stakedReward, term); }
1,946,343
[ 1, 5839, 312, 474, 310, 12318, 29663, 261, 464, 3470, 15498, 3423, 9446, 287, 813, 6076, 13, 4202, 312, 28142, 1139, 2294, 276, 9896, 471, 384, 3223, 296, 23989, 11, 434, 518, 364, 296, 6408, 11, 19, 2583, 12, 23989, 405, 374, 16, 315, 5093, 2304, 30, 14143, 7433, 3634, 5551, 8863, 4604, 19890, 312, 474, 19890, 2430, 1087, 5083, 358, 18305, 3241, 732, 15032, 1404, 312, 474, 329, 333, 1087, 4671, 384, 911, 2870, 2430, 1087, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 49, 474, 17631, 1060, 1876, 510, 911, 12, 11890, 5034, 19857, 16, 2254, 5034, 2481, 13, 3903, 8843, 429, 866, 14667, 288, 203, 3639, 490, 474, 966, 3778, 312, 474, 966, 273, 729, 49, 28142, 63, 67, 3576, 12021, 1435, 15533, 203, 3639, 2583, 12, 23989, 411, 13822, 1769, 203, 3639, 2583, 12, 81, 474, 966, 18, 11500, 405, 374, 1769, 203, 3639, 2583, 12, 2629, 18, 5508, 405, 312, 474, 966, 18, 7373, 2336, 17218, 1769, 203, 3639, 2254, 5034, 19890, 6275, 273, 389, 11162, 49, 474, 17631, 1060, 12, 203, 5411, 312, 474, 966, 18, 11500, 16, 203, 5411, 312, 474, 966, 18, 6408, 16, 203, 5411, 312, 474, 966, 18, 7373, 2336, 17218, 16, 203, 5411, 312, 474, 966, 18, 2475, 1251, 16, 203, 5411, 312, 474, 966, 18, 73, 7598, 4727, 203, 3639, 262, 380, 404, 225, 2437, 31, 203, 3639, 2254, 5034, 384, 9477, 17631, 1060, 273, 261, 266, 2913, 6275, 380, 19857, 13, 342, 2130, 31, 203, 3639, 2254, 5034, 4953, 17631, 1060, 273, 19890, 6275, 300, 384, 9477, 17631, 1060, 31, 203, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 4953, 17631, 1060, 1769, 203, 3639, 389, 81, 474, 12, 27427, 3619, 16, 19890, 6275, 342, 2130, 1769, 203, 3639, 389, 6200, 1211, 1299, 49, 474, 5621, 203, 3639, 3626, 490, 474, 9762, 329, 24899, 3576, 12021, 9334, 19890, 6275, 1769, 203, 203, 3639, 2583, 12, 334, 9477, 17631, 1060, 405, 1139, 2294, 67, 6236, 67, 882, 37, 6859, 1769, 203, 3639, 2583, 2 ]
./full_match/137/0x6ceb95626A59a2F8B1d0B6DB970F4190B89354C7/sources/contracts/base/BaseWeightedPool.sol
* @dev Called before any join or exit operation. Empty by default, but derived contracts may choose to add custom behavior at these steps. This often has to do with protocol fee processing./ solhint-disable-previous-line no-empty-blocks
function _beforeJoinExit( uint256[] memory preBalances, uint256[] memory normalizedWeights, uint256 protocolSwapFeePercentage ) internal virtual { }
3,751,531
[ 1, 8185, 1865, 1281, 1233, 578, 2427, 1674, 18, 8953, 635, 805, 16, 1496, 10379, 20092, 2026, 9876, 358, 527, 1679, 6885, 622, 4259, 6075, 18, 1220, 16337, 711, 358, 741, 598, 1771, 14036, 4929, 18, 19, 3704, 11317, 17, 8394, 17, 11515, 17, 1369, 1158, 17, 5531, 17, 7996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 4572, 6767, 12, 203, 3639, 2254, 5034, 8526, 3778, 675, 38, 26488, 16, 203, 3639, 2254, 5034, 8526, 3778, 5640, 16595, 16, 203, 3639, 2254, 5034, 1771, 12521, 14667, 16397, 203, 565, 262, 2713, 5024, 288, 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 ]
pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title 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 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 { if (newOwner != address(0)) { owner = newOwner; } } } /** * @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 StandardMintableToken is ERC20, BasicToken, Ownable { mapping (address => mapping (address => uint256)) allowed; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { 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[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); // so it is displayed properly on EtherScan return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Slot Ticket * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract SlotTicket is StandardMintableToken { string public name = "Slot Ticket"; uint8 public decimals = 0; string public symbol = "TICKET"; string public version = "0.6"; function destroy() onlyOwner { // Transfer Eth to owner and terminate contract selfdestruct(owner); } } /** * @title Slot * @dev every participant has an account index, the winners are picked from here * all winners are picked in order from the single random int * needs to be cleared after every game */ contract Slot is Ownable { using SafeMath for uint256; uint8 constant public SIZE = 100; // size of the lottery uint32 constant public JACKPOT_CHANCE = 1000000; // one in a million uint32 constant public INACTIVITY = 160000; // blocks after which refunds can be claimed uint256 constant public PRICE = 100 finney; uint256 constant public JACK_DIST = 249 finney; uint256 constant public DIV_DIST = 249 finney; uint256 constant public GAS_REFUND = 2 finney; /* * every participant has an account index, the winners are picked from here * all winners are picked in order from the single random int * needs to be cleared after every game */ mapping (uint => mapping (uint => address)) public participants; // game number => counter => address SlotTicket public ticket; // this is a receipt for the ticket, it wont affect the prize distribution uint256 public jackpotAmount; uint256 public gameNumber; uint256 public gameStartedAt; address public fund; // address to send dividends uint256[8] public prizes = [4 ether, 2 ether, 1 ether, 500 finney, 500 finney, 500 finney, 500 finney, 500 finney]; uint256 counter; event ParticipantAdded(address indexed _participant, uint256 indexed _game, uint256 indexed _number); event PrizeAwarded(uint256 indexed _game , address indexed _winner, uint256 indexed _amount); event JackpotAwarded(uint256 indexed _game, address indexed _winner, uint256 indexed _amount); event GameRefunded(uint256 _game); function Slot(address _fundAddress) payable { // address _ticketAddress // ticket = SlotTicket(_ticketAddress); // still need to change owner ticket = new SlotTicket(); fund = _fundAddress; jackpotAmount = msg.value; gameNumber = 0; counter = 0; gameStartedAt = block.number; } function() payable { // fallback function to buy tickets buyTicketsFor(msg.sender); } function buyTicketsFor(address _beneficiary) public payable { require(_beneficiary != 0x0); require(msg.value >= PRICE); // calculate number of tickets, issue tokens and add participant // every (PRICE) buys a ticket, the rest is returned uint256 change = msg.value%PRICE; uint256 numberOfTickets = msg.value.sub(change).div(PRICE); ticket.mint(_beneficiary, numberOfTickets); addParticipant(_beneficiary, numberOfTickets); // Return change to msg.sender msg.sender.transfer(change); } /* private functions */ function addParticipant(address _participant, uint256 _numberOfTickets) private { // if number of tickets exceeds the size of the game, tickets are added to next game for (uint256 i = 0; i < _numberOfTickets; i++) { // using gameNumber instead of counter/SIZE since games can be cancelled participants[gameNumber][counter%SIZE] = _participant; ParticipantAdded(_participant, gameNumber, counter%SIZE); // msg.sender triggers the drawing of lots if (++counter%SIZE == 0) { awardPrizes(); // Split the rest, increase game number distributeRemaining(); increaseGame(); } // loop continues if there are more tickets } } function awardPrizes() private { // get the winning number, no need to hash, since it is a deterministical function anyway uint256 winnerIndex = uint256(block.blockhash(block.number-1))%SIZE; // get jackpot winner, hash result of last two digit number (index) with 4 preceding zeroes will win uint256 jackpotNumber = uint256(block.blockhash(block.number-1))%JACKPOT_CHANCE; if (winnerIndex == jackpotNumber) { distributeJackpot(winnerIndex); } // loop throught the prizes for (uint8 i = 0; i < prizes.length; i++) { // GAS: 21000 Paid for every transaction. (prizes.length) participants[gameNumber][winnerIndex%SIZE].transfer(prizes[i]); // msg.sender pays the gas, he's refunded later, % to wrap around PrizeAwarded(gameNumber, participants[gameNumber][winnerIndex%SIZE], prizes[i]); // increment index to the next winner to receive the next prize winnerIndex++; } } function distributeJackpot(uint256 _winnerIndex) private { uint256 amount = jackpotAmount; jackpotAmount = 0; // later on in the code sequence funds will be added participants[gameNumber][_winnerIndex].transfer(amount); JackpotAwarded(gameNumber, participants[gameNumber][_winnerIndex], amount); } function distributeRemaining() private { // GAS: 21000 Paid for every transaction. (3) jackpotAmount = jackpotAmount.add(JACK_DIST); // add to jackpot fund.transfer(DIV_DIST); // *cash register sound* dividends are paid to SLOT token owners msg.sender.transfer(GAS_REFUND); // repay gas to msg.sender } function increaseGame() private { gameNumber++; gameStartedAt = block.number; } // public functions function spotsLeft() public constant returns (uint8 spots) { return SIZE - uint8(counter%SIZE); } function refundGameAfterLongInactivity() public { require(block.number.sub(gameStartedAt) >= INACTIVITY); require(counter%SIZE != 0); // nothing to refund // refunds for everybody can be requested after the game has gone (INACTIVITY) blocks without a conclusion // Checks-Effects-Interactions pattern to avoid re-entrancy uint256 _size = counter%SIZE; // not counter.size, but modulus of SIZE counter -= _size; for (uint8 i = 0; i < _size; i++) { // GAS: default 21000 paid for every transaction. participants[gameNumber][i].transfer(PRICE); } GameRefunded(gameNumber); increaseGame(); } function destroy() public onlyOwner { require(jackpotAmount < 25 ether); // Transfer Ether funds to owner and terminate contract // It would be unfair to allow ourselves to destroy a contract with more than 25 ether and claim the jackpot, // lower than that we would consider it still a beta (any Ether would be transfered to the newer contract) ticket.destroy(); selfdestruct(owner); } function changeTicketOwner(address _newOwner) public onlyOwner { // in case of new contract, old token can still be used // the token contract owner is the slot contract itself ticket.transferOwnership(_newOwner); } function changeFund(address _newFund) public onlyOwner { fund = _newFund; } function changeTicket(address _newTicket) public onlyOwner { ticket = SlotTicket(_newTicket); // still need to change owner to work } }
not counter.size, but modulus of SIZE
uint256 _size = counter%SIZE;
5,449,608
[ 1, 902, 3895, 18, 1467, 16, 1496, 24770, 434, 11963, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 389, 1467, 273, 3895, 9, 4574, 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 ]
./full_match/421613/0xA4A34B69AA7Bdec4B2656485A299813fF854Cd05/sources/project_/src/active/app/CrossChainBridge.sol
solhint-disable no-inline-assembly */ Packet type localTokenByRemote[remoteToken] = Local token address
contract CrossChainBridge is AccessControlUpgradeable, NonblockingLzAppUpgradeable { using SafeERC20 for IERC20; bytes32 internal constant _EDITOR_ROLE = keccak256("_EDITOR_ROLE"); string public message; mapping(address => address) public localTokenByRemote; event ESwapFromChain(uint16 srcChainId, address remoteToken, address to, uint256 amount); event ETextFromChain(uint16 srcChainId, string text); function CrossChainBridgeInit(address _lzEndpoint) external initializer { __AccessControl_init(); __NonblockingLzAppUpgradeable_init(_lzEndpoint); address sender_ = _msgSender(); _setupRole(DEFAULT_ADMIN_ROLE, sender_); _setupRole(_EDITOR_ROLE, sender_); } function configToken(address localToken, address remoteToken) external onlyRole(_EDITOR_ROLE) { localTokenByRemote[remoteToken] = localToken; } function estimateSendTokensFee( uint16 _dstChainId, address _srcToken, address _toAddress, uint256 _amount ) external view virtual returns (uint256 nativeFee, uint256 zroFee) { bytes memory lzPayload = abi.encode(PT_SWAP, _srcToken, _toAddress, _amount); return lzEndpoint.estimateFees(_dstChainId, address(this), lzPayload, false, ""); } function sendTokens(uint16 _dstChainId, address _srcToken, uint256 _amount) external payable { address sender_ = _msgSender(); IERC20(_srcToken).safeTransferFrom(sender_, address(this), _amount); bytes memory lzPayload = abi.encode(PT_SWAP, _srcToken, sender_, _amount); _lzSimpleSend(_dstChainId, lzPayload, sender_); } function estimateUpdateTextFee( uint16 _dstChainId, string memory _text ) external view virtual returns (uint256 nativeFee, uint256 zroFee) { bytes memory lzPayload = abi.encode(PT_TEXT, _text); return lzEndpoint.estimateFees(_dstChainId, address(this), lzPayload, false, ""); } function updateText(uint16 _dstChainId, string memory _text) external payable { address sender_ = _msgSender(); bytes memory lzPayload = abi.encode(PT_TEXT, _text); _lzSimpleSend(_dstChainId, lzPayload, sender_); } function _lzSimpleSend(uint16 _dstChainId, bytes memory _payload, address _refundAddress) internal virtual { _lzSend(_dstChainId, _payload, payable(_refundAddress), address(0), "", msg.value); } function _nonblockingLzReceive( uint16 _srcChainId, bytes memory _payload ) internal virtual override { uint16 packetType; assembly { packetType := mload(add(_payload, 32)) } if (packetType == PT_SWAP) { _swapAck(_srcChainId, _payload); _textAck(_srcChainId, _payload); revert("Bridge: unknown packet type"); } } function _nonblockingLzReceive( uint16 _srcChainId, bytes memory _payload ) internal virtual override { uint16 packetType; assembly { packetType := mload(add(_payload, 32)) } if (packetType == PT_SWAP) { _swapAck(_srcChainId, _payload); _textAck(_srcChainId, _payload); revert("Bridge: unknown packet type"); } } function _nonblockingLzReceive( uint16 _srcChainId, bytes memory _payload ) internal virtual override { uint16 packetType; assembly { packetType := mload(add(_payload, 32)) } if (packetType == PT_SWAP) { _swapAck(_srcChainId, _payload); _textAck(_srcChainId, _payload); revert("Bridge: unknown packet type"); } } } else if (packetType == PT_TEXT) { } else { function _swapAck(uint16 _srcChainId, bytes memory _payload) internal virtual { (, address remoteToken, address toAddress, uint256 amount) = abi.decode( _payload, (uint16, address, address, uint256) ); IERC20(localTokenByRemote[remoteToken]).safeTransfer(toAddress, amount); emit ESwapFromChain(_srcChainId, remoteToken, toAddress, amount); } function _textAck(uint16 _srcChainId, bytes memory _payload) internal virtual { (, string memory text) = abi.decode(_payload, (uint16, string)); message = text; emit ETextFromChain(_srcChainId, text); } }
11,569,873
[ 1, 18281, 11317, 17, 8394, 1158, 17, 10047, 17, 28050, 342, 11114, 618, 1191, 1345, 858, 5169, 63, 7222, 1345, 65, 273, 3566, 1147, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 19742, 3893, 13691, 353, 24349, 10784, 429, 16, 3858, 18926, 48, 94, 3371, 10784, 429, 288, 203, 225, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 225, 1731, 1578, 2713, 5381, 389, 13208, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 67, 13208, 67, 16256, 8863, 203, 203, 203, 225, 533, 1071, 883, 31, 203, 203, 225, 2874, 12, 2867, 516, 1758, 13, 1071, 1191, 1345, 858, 5169, 31, 203, 203, 225, 871, 512, 12521, 1265, 3893, 12, 11890, 2313, 1705, 3893, 548, 16, 1758, 2632, 1345, 16, 1758, 358, 16, 2254, 5034, 3844, 1769, 203, 225, 871, 512, 1528, 1265, 3893, 12, 11890, 2313, 1705, 3893, 548, 16, 533, 977, 1769, 203, 203, 203, 225, 445, 19742, 3893, 13691, 2570, 12, 2867, 389, 80, 94, 3293, 13, 3903, 12562, 288, 203, 565, 1001, 16541, 67, 2738, 5621, 203, 565, 1001, 3989, 18926, 48, 94, 3371, 10784, 429, 67, 2738, 24899, 80, 94, 3293, 1769, 203, 203, 565, 1758, 5793, 67, 273, 389, 3576, 12021, 5621, 203, 565, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 5793, 67, 1769, 203, 565, 389, 8401, 2996, 24899, 13208, 67, 16256, 16, 5793, 67, 1769, 203, 225, 289, 203, 203, 225, 445, 642, 1345, 12, 2867, 1191, 1345, 16, 1758, 2632, 1345, 13, 3903, 1338, 2996, 24899, 13208, 67, 16256, 13, 288, 203, 565, 1191, 1345, 858, 5169, 63, 7222, 1345, 65, 273, 1191, 1345, 31, 203, 225, 289, 203, 203, 225, 445, 11108, 3826, 5157, 14667, 12, 203, 2 ]
pragma solidity ^0.5.2; import "./Ownable.sol"; import "asn1-decode/contracts/Asn1Decode.sol"; import "@ensdomains/dnssec-oracle/contracts/algorithms/Algorithm.sol"; import "ens-namehash/contracts/ENSNamehash.sol"; import "ethereum-datetime/contracts/DateTime.sol"; /* * @dev Stores validated X.509 certificate chains in parent pointer trees. * @dev The root of each tree is a CA root certificate */ contract X509ForestOfTrust is Ownable { using Asn1Decode for bytes; using ENSNamehash for bytes; bytes10 constant private OID_SUBJECT_ALT_NAME = 0x551d1100000000000000; bytes10 constant private OID_BASIC_CONSTRAINTS = 0x551d1300000000000000; bytes10 constant private OID_NAME_CONSTRAINTS = 0x551d1e00000000000000; bytes10 constant private OID_KEY_USAGE = 0x551d0f00000000000000; bytes10 constant private OID_EXTENDED_KEY_USAGE = 0x551d2500000000000000; bytes10 private OID_CAN_SIGN_HTTP_EXCHANGES = 0x2b06010401d679020116; // Not constant because spec may change constructor(address sha256WithRSAEncryption, address _dateTime) public { bytes32 algOid = 0x2a864886f70d01010b0000000000000000000000000000000000000000000000; algs[algOid] = Algorithm(sha256WithRSAEncryption); dateTime = DateTime(_dateTime); } struct KeyUsage { bool critical; bool present; uint16 bits; // Value of KeyUsage bits. (E.g. 5 is 000000101) } struct ExtKeyUsage { bool critical; bool present; bytes32[] oids; } struct Certificate { address owner; bytes32 parentId; uint40 timestamp; uint160 serialNumber; uint40 validNotBefore; uint40 validNotAfter; bool cA; // Whether the certified public key may be used to verify certificate signatures. uint8 pathLenConstraint; // Maximum number of non-self-issued intermediate certs that may follow this // cert in a valid certification path. KeyUsage keyUsage; ExtKeyUsage extKeyUsage; bool sxg; // canSignHttpExchanges extension is present. bytes32 extId; // keccak256 of extensions field for further validation. // Equal to 0x0 unless a critical extension was found but not parsed. // This should always be checked on leaf certificates } mapping (bytes32 => Certificate) private certs; // certId => cert (certId is keccak256(pubKey)) mapping (bytes32 => Algorithm) private algs; // algorithm oid bytes => signature verification contract mapping (bytes32 => bytes32[]) public toCertIds; // ensNamehash(subjectAltName) => certId mapping (bytes32 => bytes32) public toCertId; // sha256 fingerprint => certId DateTime dateTime; // For dateTime conversion event CertAdded(bytes32); event CertClaimed(bytes32, address); event AlgSet(bytes32, address); /** * @dev Add a X.509 certificate to an existing tree/chain * @param cert A DER-encoded X.509 certificate * @param parentPubKey The parent certificate's DER-encoded public key */ function addCert(bytes memory cert, bytes memory parentPubKey) public { Certificate memory certificate; bytes32 certId; uint node1; uint node2; uint node3; uint node4; certificate.parentId = keccak256(parentPubKey); certificate.timestamp = uint40(block.timestamp); node1 = cert.root(); node1 = cert.firstChildOf(node1); node2 = cert.firstChildOf(node1); if (cert[NodePtr.ixs(node2)] == 0xa0) { node2 = cert.nextSiblingOf(node2); } // Extract serial number certificate.serialNumber = uint160(cert.uintAt(node2)); node2 = cert.nextSiblingOf(node2); node2 = cert.firstChildOf(node2); node3 = cert.nextSiblingOf(node1); node3 = cert.nextSiblingOf(node3); // Verify signature require(algs[cert.bytes32At(node2)].verify(parentPubKey, cert.allBytesAt(node1), cert.bytesAt(node3)), "Signature doesnt match"); node1 = cert.firstChildOf(node1); node1 = cert.nextSiblingOf(node1); node1 = cert.nextSiblingOf(node1); node1 = cert.nextSiblingOf(node1); node1 = cert.nextSiblingOf(node1); node2 = cert.firstChildOf(node1); // Check validNotBefore certificate.validNotBefore = uint40(toTimestamp(cert.bytesAt(node2))); require(certificate.validNotBefore <= now, "Now is before validNotBefore"); node2 = cert.nextSiblingOf(node2); // Check validNotAfter certificate.validNotAfter = uint40(toTimestamp(cert.bytesAt(node2))); require(now <= certificate.validNotAfter, "Now is after validNotAfter"); node1 = cert.nextSiblingOf(node1); node1 = cert.nextSiblingOf(node1); // Get public key and calculate certId from it certId = cert.keccakOfAllBytesAt(node1); // Cert must not already exist // Prevents duplicate references and owner from being overridden require(certs[certId].validNotAfter == 0); // Fire event emit CertAdded(certId); // Add reference from sha256 fingerprint toCertId[sha256(cert)] = certId; node1 = cert.nextSiblingOf(node1); // Skip over v2 fields if (cert[NodePtr.ixs(node1)] == 0xa1) node1 = cert.nextSiblingOf(node1); if (cert[NodePtr.ixs(node1)] == 0xa2) node1 = cert.nextSiblingOf(node1); // Parse extensions if (cert[NodePtr.ixs(node1)] == 0xa3) { node1 = cert.firstChildOf(node1); node2 = cert.firstChildOf(node1); bytes10 oid; bool isCritical; while (Asn1Decode.isChildOf(node2, node1)) { node3 = cert.firstChildOf(node2); oid = bytes10(cert.bytes32At(node3)); // Extension oid node3 = cert.nextSiblingOf(node3); // Check if extension is critical isCritical = false; if (cert[NodePtr.ixs(node3)] == 0x01) { // If type is bool if (cert[NodePtr.ixf(node3)] != 0x00) // If not false isCritical = true; node3 = cert.nextSiblingOf(node3); } if (oid == OID_SUBJECT_ALT_NAME) { // Add references from names node3 = cert.rootOfOctetStringAt(node3); node4 = cert.firstChildOf(node3); while (Asn1Decode.isChildOf(node4, node3)) { if(cert[NodePtr.ixs(node4)] == 0x82) toCertIds[cert.bytesAt(node4).namehash()].push(certId); else toCertIds[cert.keccakOfBytesAt(node4)].push(certId); node4 = cert.nextSiblingOf(node4); } } else if (oid == OID_BASIC_CONSTRAINTS) { if (isCritical) { // Check if cert can sign other certs node3 = cert.rootOfOctetStringAt(node3); node4 = cert.firstChildOf(node3); // If sequence (node3) is not empty if (Asn1Decode.isChildOf(node4, node3)) { // If value == true if (cert[NodePtr.ixf(node4)] != 0x00) { certificate.cA = true; node4 = cert.nextSiblingOf(node4); if (Asn1Decode.isChildOf(node4, node3)) { certificate.pathLenConstraint = uint8(cert.uintAt(node4)); } else { certificate.pathLenConstraint = uint8(-1); } } } } } else if (oid == OID_KEY_USAGE) { certificate.keyUsage.present = true; certificate.keyUsage.critical = isCritical; node3 = cert.rootOfOctetStringAt(node3); bytes3 v = bytes3(cert.bytes32At(node3)); // The encoded bitstring value certificate.keyUsage.bits = ((uint16(uint8(v[1])) << 8) + uint16(uint8(v[2]))) >> 7; } else if (oid == OID_EXTENDED_KEY_USAGE) { certificate.extKeyUsage.present = true; certificate.extKeyUsage.critical = isCritical; node3 = cert.rootOfOctetStringAt(node3); node4 = cert.firstChildOf(node3); uint len; while (Asn1Decode.isChildOf(node4, node3)) { len++; node4 = cert.nextSiblingOf(node4); } bytes32[] memory oids = new bytes32[](len); node4 = cert.firstChildOf(node3); for (uint i; i<len; i++) { oids[i] = cert.bytes32At(node4); node4 = cert.nextSiblingOf(node4); } certificate.extKeyUsage.oids = oids; } else if (oid == OID_CAN_SIGN_HTTP_EXCHANGES) { certificate.sxg = true; } else if (oid == OID_NAME_CONSTRAINTS) { // Name constraints not allowed. require(false, "Name constraints extension not supported"); } else if (isCritical && certificate.extId == bytes32(0)) { // Note: unrecognized critical extensions are allowed. // Further validation of certificate is needed if extId != bytes32(0). // Save hash of extensions certificate.extId = cert.keccakOfAllBytesAt(node1); } node2 = cert.nextSiblingOf(node2); } } certs[certId] = certificate; require(certs[certificate.parentId].cA, "Invalid parent cert"); // If intermediate cert, verify authority's pathLenConstraint if (certificate.cA && certId != certificate.parentId) require(certs[certificate.parentId].pathLenConstraint == uint8(-1) || certs[certificate.parentId].pathLenConstraint > certificate.pathLenConstraint, "Invalid parent cert"); // RFC 5280: If the cA boolean is not asserted, then the keyCertSign // bit in the key usage extension MUST NOT be asserted. if (!certificate.cA) require(certificate.keyUsage.bits & 8 != 8, "cA boolean is not asserted and keyCertSign bit is asserted"); } /** * @dev The return values of this function are used to proveOwnership() of a * certificate that exists in the certs mapping. * @return Some unique bytes to be signed * @return The block number used to create the first return value */ function signThis() external view returns (bytes memory, uint) { return ( abi.encodePacked(msg.sender, blockhash(block.number - 1)), block.number -1 ); } /** * @dev An account calls this method to prove ownership of a certificate. * If successful, certs[certId].owner will be set to caller's address. * @param pubKey The target certificate's public key * @param signature signThis()[0] signed with certificate's private key * @param blockNumber The value of signThis()[1] (must be > block.number - 256) * @param sigAlg The OID of the algorithm used to sign `signature` */ function proveOwnership(bytes calldata pubKey, bytes calldata signature, uint blockNumber, bytes32 sigAlg) external { bytes32 certId = keccak256(pubKey); bytes memory message = abi.encodePacked(msg.sender, blockhash(blockNumber)); emit CertClaimed(certId, msg.sender); // Only accept proof if it's less than 256 blocks old // This is the most time I can give since blockhash() can only return the 256 most recent require(block.number - blockNumber < 256, "Signature too old"); // Verify signature, which proves ownership require(algs[sigAlg].verify(pubKey, message, signature), "Signature doesnt match"); certs[certId].owner = msg.sender; } function rootOf(bytes32 certId) external view returns (bytes32) { bytes32 id = certId; while (id != certs[id].parentId) { id = certs[id].parentId; } return id; } function owner(bytes32 certId) external view returns (address) { return certs[certId].owner; } function parentId(bytes32 certId) external view returns (bytes32) { return certs[certId].parentId; } function timestamp(bytes32 certId) external view returns (uint40) { return certs[certId].timestamp; } function serialNumber(bytes32 certId) external view returns (uint160) { return certs[certId].serialNumber; } function validNotBefore(bytes32 certId) external view returns (uint40) { return certs[certId].validNotBefore; } function validNotAfter(bytes32 certId) external view returns (uint40) { return certs[certId].validNotAfter; } function sxg(bytes32 certId) external view returns (bool) { return certs[certId].sxg; } function basicConstraints(bytes32 certId) external view returns (bool, uint8) { return (certs[certId].cA, certs[certId].pathLenConstraint); } function keyUsage(bytes32 certId) external view returns (bool, bool[9] memory) { KeyUsage memory _keyUsage = certs[certId].keyUsage; uint16 mask = 256; bool[9] memory flags; if (_keyUsage.present) { for (uint i; i<9; i++) { flags[i] = (_keyUsage.bits & mask == mask); mask = mask >> 1; } } return (_keyUsage.present, flags); } function keyUsageCritical(bytes32 certId) external view returns (bool) { return certs[certId].keyUsage.critical; } function extKeyUsage(bytes32 certId) external view returns (bool, bytes32[] memory) { ExtKeyUsage memory _extKeyUsage = certs[certId].extKeyUsage; return (_extKeyUsage.present, _extKeyUsage.oids); } function extKeyUsageCritical(bytes32 certId) external view returns (bool) { return certs[certId].extKeyUsage.critical; } function unparsedCriticalExtensionPresent(bytes32 certId) external view returns (bool) { return (certs[certId].extId != bytes32(0)); } function extId(bytes32 certId) external view returns (bytes32) { return certs[certId].extId; } function toCertIdsLength(bytes32 _hash) external view returns (uint) { return toCertIds[_hash].length; } function toTimestamp(bytes memory x509Time) private view returns (uint) { uint16 yrs; uint8 mnths; uint8 dys; uint8 hrs; uint8 mins; uint8 secs; uint8 offset; if (x509Time.length == 13) { if (uint8(x509Time[0])-48 < 5) yrs += 2000; else yrs += 1900; } else { yrs += (uint8(x509Time[0])-48) * 1000 + (uint8(x509Time[1])-48) * 100; offset = 2; } yrs += (uint8(x509Time[offset+0])-48)*10 + uint8(x509Time[offset+1])-48; mnths = (uint8(x509Time[offset+2])-48)*10 + uint8(x509Time[offset+3])-48; dys += (uint8(x509Time[offset+4])-48)*10 + uint8(x509Time[offset+5])-48; hrs += (uint8(x509Time[offset+6])-48)*10 + uint8(x509Time[offset+7])-48; mins += (uint8(x509Time[offset+8])-48)*10 + uint8(x509Time[offset+9])-48; secs += (uint8(x509Time[offset+10])-48)*10 + uint8(x509Time[offset+11])-48; return dateTime.toTimestamp(yrs, mnths, dys, hrs, mins, secs); } function setAlg(bytes32 oid, address alg) external onlyOwner { algs[oid] = Algorithm(alg); emit AlgSet(oid, alg); } function setSxgOid(bytes32 sxgOid) external onlyOwner { OID_CAN_SIGN_HTTP_EXCHANGES = bytes10(sxgOid); } }
Not constant because spec may change
bytes10 private OID_CAN_SIGN_HTTP_EXCHANGES = 0x2b06010401d679020116;
5,374,489
[ 1, 1248, 5381, 2724, 857, 2026, 2549, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1731, 2163, 3238, 18026, 67, 39, 1258, 67, 11260, 67, 3693, 67, 2294, 1792, 3388, 3991, 377, 273, 374, 92, 22, 70, 7677, 1611, 3028, 1611, 72, 26, 7235, 3103, 1611, 2313, 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 ]
./full_match/100/0xe6b9f1766068BdFB4c59dD416A9FDe1E471276F2/sources/contracts/AssetTokenized.sol
subtracts the remaining asset tokens from the total supply
supply -= msg.value/pricePerEth;
14,283,136
[ 1, 1717, 1575, 87, 326, 4463, 3310, 2430, 628, 326, 2078, 14467, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14467, 3947, 1234, 18, 1132, 19, 8694, 2173, 41, 451, 31, 9079, 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 ]
// File: @openzeppelin/contracts@4.2.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; } } // File: @openzeppelin/contracts@4.2.0/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 uint _value; // default: 0 } function current(Counter storage counter) internal view returns (uint) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint 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@4.2.0/utils/cryptography/ECDSA.sol pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * 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] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // 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 recover(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 recover(hash, r, vs); } else { revert('ECDSA: invalid signature length'); } } /** * @dev Overload of {ECDSA-recover} 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.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), 'ECDSA: invalid signature'); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); } } // File: @openzeppelin/contracts@4.2.0/utils/cryptography/draft-EIP712.sol pragma solidity ^0.8.0; /** * @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; uint private immutable _CACHED_CHAIN_ID; 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); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (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); } } // File: @openzeppelin/contracts@4.2.0/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, uint value, uint 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 (uint); /** * @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); } // File: @openzeppelin/contracts@4.2.0/utils/structs/EnumerableSet.sol pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint) _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 uint 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}. uint toDeleteIndex = valueIndex - 1; uint lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint) { 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, uint index) private view returns (bytes32) { 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 (uint) { 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, uint 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(uint(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint) { 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, uint index) internal view returns (address) { return address(uint160(uint(_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, uint 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, uint 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, uint 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 (uint) { 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, uint index) internal view returns (uint) { return uint(_at(set._inner, index)); } } // File: @openzeppelin/contracts@4.2.0/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@4.2.0/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@4.2.0/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(uint 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'; } uint temp = value; uint digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint temp = value; uint 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(uint value, uint length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint 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@4.2.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); } // File: @openzeppelin/contracts@4.2.0/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts@4.2.0/token/ERC20/ERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: @openzeppelin/contracts@4.2.0/access/AccessControl.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @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 Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev 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]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), 'AccessControl: can only renounce roles for self'); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts@4.2.0/access/AccessControlEnumerable.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // File: @openzeppelin/contracts@4.2.0/security/Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract 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()); } } // File: @openzeppelin/contracts@4.2.0/token/ERC20/extensions/ERC20Pausable.sol pragma solidity ^0.8.0; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // File: @openzeppelin/contracts@4.2.0/token/ERC20/extensions/ERC20Burnable.sol pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ 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 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // File: @openzeppelin/contracts@4.2.0/token/ERC20/extensions/draft-ERC20Permit.sol pragma solidity ^0.8.0; /** * @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(); } } // File: @openzeppelin/contracts@4.2.0/token/ERC20/presets/ERC20PresetMinterPauser.sol pragma solidity ^0.8.0; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // File: BetaToken.sol pragma solidity 0.8.6; contract BetaToken is ERC20PresetMinterPauser('Beta Token', 'BETA'), ERC20Permit('BETA') { function _beforeTokenTransfer( address from, address to, uint amount ) internal virtual override(ERC20, ERC20PresetMinterPauser) { ERC20PresetMinterPauser._beforeTokenTransfer(from, to, amount); } }
Storage of set values Position of the value in the `values` array, plus 1 because index 0 means a value is not in the set.
struct Set { bytes32[] _values; mapping(bytes32 => uint) _indexes; }
5,851,686
[ 1, 3245, 434, 444, 924, 11010, 434, 326, 460, 316, 326, 1375, 2372, 68, 526, 16, 8737, 404, 2724, 770, 374, 4696, 279, 460, 353, 486, 316, 326, 444, 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, 225, 1958, 1000, 288, 203, 565, 1731, 1578, 8526, 389, 2372, 31, 203, 565, 2874, 12, 3890, 1578, 516, 2254, 13, 389, 11265, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-10-05 */ // File: solidity/contracts/token/interfaces/IERC20Token.sol // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; /* ERC20 Standard Token interface */ interface IERC20Token { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); } // File: solidity/contracts/utility/Utils.sol pragma solidity 0.6.12; /** * @dev Utilities & Common Modifiers */ contract Utils { // verifies that a value is greater than zero modifier greaterThanZero(uint256 _value) { _greaterThanZero(_value); _; } // error message binary size optimization function _greaterThanZero(uint256 _value) internal pure { require(_value > 0, "ERR_ZERO_VALUE"); } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { _validAddress(_address); _; } // error message binary size optimization function _validAddress(address _address) internal pure { require(_address != address(0), "ERR_INVALID_ADDRESS"); } // verifies that the address is different than this contract address modifier notThis(address _address) { _notThis(_address); _; } // error message binary size optimization function _notThis(address _address) internal view { require(_address != address(this), "ERR_ADDRESS_IS_SELF"); } } // File: solidity/contracts/utility/SafeMath.sol pragma solidity 0.6.12; /** * @dev Library for basic math operations with overflow/underflow protection */ library SafeMath { /** * @dev returns the sum of _x and _y, reverts if the calculation overflows * * @param _x value 1 * @param _y value 2 * * @return sum */ function add(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x, "ERR_OVERFLOW"); return z; } /** * @dev returns the difference of _x minus _y, reverts if the calculation underflows * * @param _x minuend * @param _y subtrahend * * @return difference */ function sub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y, "ERR_UNDERFLOW"); return _x - _y; } /** * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows * * @param _x factor 1 * @param _y factor 2 * * @return product */ function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y, "ERR_OVERFLOW"); return z; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. * * @param _x dividend * @param _y divisor * * @return quotient */ function div(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_y > 0, "ERR_DIVIDE_BY_ZERO"); uint256 c = _x / _y; return c; } } // File: solidity/contracts/token/ERC20Token.sol pragma solidity 0.6.12; /** * @dev ERC20 Standard Token implementation */ contract ERC20Token is IERC20Token, Utils { using SafeMath for uint256; string public override name; string public override symbol; uint8 public override decimals; uint256 public override totalSupply; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) public override allowance; /** * @dev triggered when tokens are transferred between wallets * * @param _from source address * @param _to target address * @param _value transfer amount */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev triggered when a wallet allows another wallet to transfer tokens from on its behalf * * @param _owner wallet that approves the allowance * @param _spender wallet that receives the allowance * @param _value allowance amount */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev initializes a new ERC20Token instance * * @param _name token name * @param _symbol token symbol * @param _decimals decimal points, for display purposes * @param _totalSupply total supply of token units */ constructor( string memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply ) public { // validate input require(bytes(_name).length > 0, "ERR_INVALID_NAME"); require(bytes(_symbol).length > 0, "ERR_INVALID_SYMBOL"); name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balanceOf[msg.sender] = _totalSupply; } /** * @dev transfers tokens to a given address * throws on any error rather then return a false flag to minimize user errors * * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public virtual override validAddress(_to) returns (bool) { balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev transfers tokens to a given address on behalf of another address * throws on any error rather then return a false flag to minimize user errors * * @param _from source address * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transferFrom( address _from, address _to, uint256 _value ) public virtual override validAddress(_from) validAddress(_to) returns (bool) { allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev allows another account/contract to transfers tokens on behalf of the caller * throws on any error rather then return a false flag to minimize user errors * * @param _spender approved address * @param _value allowance amount * * @return true if the approval was successful, false if it wasn't */ function approve(address _spender, uint256 _value) public virtual override validAddress(_spender) returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } } // File: solidity/contracts/utility/interfaces/IOwned.sol pragma solidity 0.6.12; /* Owned contract interface */ interface IOwned { // this function isn't since the compiler emits automatically generated getter functions as external function owner() external view returns (address); function transferOwnership(address _newOwner) external; function acceptOwnership() external; } // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol pragma solidity 0.6.12; /* Converter Anchor interface */ interface IConverterAnchor is IOwned { } // File: solidity/contracts/token/interfaces/IDSToken.sol pragma solidity 0.6.12; /* DSToken interface */ interface IDSToken is IConverterAnchor, IERC20Token { function issue(address _to, uint256 _amount) external; function destroy(address _from, uint256 _amount) external; } // File: solidity/contracts/utility/Owned.sol pragma solidity 0.6.12; /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public override owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly() { _ownerOnly(); _; } // error message binary size optimization function _ownerOnly() internal view { require(msg.sender == owner, "ERR_ACCESS_DENIED"); } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public override ownerOnly { require(_newOwner != owner, "ERR_SAME_OWNER"); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public override { require(msg.sender == newOwner, "ERR_ACCESS_DENIED"); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: solidity/contracts/token/DSToken.sol pragma solidity 0.6.12; /** * @dev DSToken represents a token with dynamic supply. * The owner of the token can mint/burn tokens to/from any account. * */ contract DSToken is IDSToken, ERC20Token, Owned { using SafeMath for uint256; /** * @dev triggered when the total supply is increased * * @param _amount amount that gets added to the supply */ event Issuance(uint256 _amount); /** * @dev triggered when the total supply is decreased * * @param _amount amount that gets removed from the supply */ event Destruction(uint256 _amount); /** * @dev initializes a new DSToken instance * * @param _name token name * @param _symbol token short symbol, minimum 1 character * @param _decimals for display purposes only */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20Token(_name, _symbol, _decimals, 0) {} /** * @dev increases the token supply and sends the new tokens to the given account * can only be called by the contract owner * * @param _to account to receive the new amount * @param _amount amount to increase the supply by */ function issue(address _to, uint256 _amount) public override ownerOnly validAddress(_to) notThis(_to) { totalSupply = totalSupply.add(_amount); balanceOf[_to] = balanceOf[_to].add(_amount); emit Issuance(_amount); emit Transfer(address(0), _to, _amount); } /** * @dev removes tokens from the given account and decreases the token supply * can only be called by the contract owner * * @param _from account to remove the amount from * @param _amount amount to decrease the supply by */ function destroy(address _from, uint256 _amount) public override ownerOnly { balanceOf[_from] = balanceOf[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); emit Transfer(_from, address(0), _amount); emit Destruction(_amount); } // ERC20 standard method overrides with some extra functionality /** * @dev send coins * throws on any error rather then return a false flag to minimize user errors * in addition to the standard checks, the function throws if transfers are disabled * * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint256 _value) public override(IERC20Token, ERC20Token) returns (bool) { return super.transfer(_to, _value); } /** * @dev an account/contract attempts to get the coins * throws on any error rather then return a false flag to minimize user errors * in addition to the standard checks, the function throws if transfers are disabled * * @param _from source address * @param _to target address * @param _value transfer amount * * @return true if the transfer was successful, false if it wasn't */ function transferFrom( address _from, address _to, uint256 _value ) public override(IERC20Token, ERC20Token) returns (bool) { return super.transferFrom(_from, _to, _value); } }
* @dev transfers tokens to a given address on behalf of another address throws on any error rather then return a false flag to minimize user errors @param _from source address @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't/
function transferFrom( address _from, address _to, uint256 _value ) public virtual override validAddress(_from) validAddress(_to) returns (bool) { allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true; }
2,521,825
[ 1, 2338, 18881, 2430, 358, 279, 864, 1758, 603, 12433, 6186, 434, 4042, 1758, 1216, 603, 1281, 555, 9178, 1508, 327, 279, 629, 2982, 358, 18935, 729, 1334, 225, 389, 2080, 565, 1084, 1758, 225, 389, 869, 1377, 1018, 1758, 225, 389, 1132, 282, 7412, 3844, 327, 638, 309, 326, 7412, 1703, 6873, 16, 629, 309, 518, 14487, 1404, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 389, 1132, 203, 565, 262, 1071, 5024, 3849, 923, 1887, 24899, 2080, 13, 923, 1887, 24899, 869, 13, 1135, 261, 6430, 13, 288, 203, 3639, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 3639, 11013, 951, 63, 67, 2080, 65, 273, 11013, 951, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 3639, 11013, 951, 63, 67, 869, 65, 273, 11013, 951, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xEacAA5fbE3C364fcAcEd6cD14CEd4E54703cE5D4/sources/contracts/YieldComponentToken.sol
Call the payout function on the SplitVault contract, just for the yield
splitVault.payout(payoutAmount, fullToken, owner);
2,987,147
[ 1, 1477, 326, 293, 2012, 445, 603, 326, 5385, 12003, 6835, 16, 2537, 364, 326, 2824, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1416, 12003, 18, 84, 2012, 12, 84, 2012, 6275, 16, 1983, 1345, 16, 3410, 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 ]
./full_match/11155111/0x44AAb0a83d65E4ea7b437013559790e4E379f6b7/sources/TrippleUp.sol
Modifier to restrict access to the owner
contract DiceGambling is VRFConsumerBaseV2 { uint256 private constant ROLL_IN_PROGRESS = 42; VRFCoordinatorV2Interface COORDINATOR; uint64 s_subscriptionId; address vrfCoordinator = 0x8103B0A8A00be2DDC778e6e7eaa21791Cd364625; bytes32 s_keyHash = 0x474e34a077df58807dbe9c96d3c009b23b3c6d0cce433e59bbf5b34f823bc56c; uint32 callbackGasLimit = 40000; uint16 requestConfirmations = 3; uint32 numWords = 1; address s_owner; uint256 private houseBalance; uint256 private jackpot; bool private bonusRoundActive = false; uint256 private bonusRoundEndTime; mapping(uint256 => address) private s_rollers; mapping(address => uint256) private s_results; mapping(address => uint256) private s_bets; mapping(address => uint256) private consecutiveSixes; event DiceRolled(uint256 indexed requestId, address indexed roller); event DiceLanded(uint256 indexed requestId, uint256 indexed result); event JackpotWon(address winner, uint256 amount); event BonusRoundStarted(); event BonusRoundEnded(); pragma solidity ^0.8.7; modifier onlyOwner() { require(msg.sender == s_owner, "Only the owner can call this function."); _; } constructor(uint64 subscriptionId) VRFConsumerBaseV2(vrfCoordinator) { COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); s_owner = msg.sender; s_subscriptionId = subscriptionId; } function rollDice() public payable { require(msg.value > 0, "Please place a bet."); require(s_results[msg.sender] == 0, "You've already rolled the dice."); s_bets[msg.sender] = msg.value; uint256 requestId = COORDINATOR.requestRandomWords( s_keyHash, s_subscriptionId, requestConfirmations, callbackGasLimit, numWords ); s_rollers[requestId] = msg.sender; s_results[msg.sender] = ROLL_IN_PROGRESS; emit DiceRolled(requestId, msg.sender); } function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override { uint256 diceResult = (randomWords[0] % 6) + 1; s_results[s_rollers[requestId]] = diceResult; address roller = s_rollers[requestId]; uint256 betAmount = s_bets[roller]; uint256 payout; if (diceResult == 6) { payout = 0; } houseBalance += betAmount - payout; if (payout > 0) { payable(roller).transfer(payout); } emit DiceLanded(requestId, diceResult); } function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override { uint256 diceResult = (randomWords[0] % 6) + 1; s_results[s_rollers[requestId]] = diceResult; address roller = s_rollers[requestId]; uint256 betAmount = s_bets[roller]; uint256 payout; if (diceResult == 6) { payout = 0; } houseBalance += betAmount - payout; if (payout > 0) { payable(roller).transfer(payout); } emit DiceLanded(requestId, diceResult); } } else { function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override { uint256 diceResult = (randomWords[0] % 6) + 1; s_results[s_rollers[requestId]] = diceResult; address roller = s_rollers[requestId]; uint256 betAmount = s_bets[roller]; uint256 payout; if (diceResult == 6) { payout = 0; } houseBalance += betAmount - payout; if (payout > 0) { payable(roller).transfer(payout); } emit DiceLanded(requestId, diceResult); } function contributeToJackpot() public payable { require(msg.value > 0, "Please contribute some ETH to the jackpot."); jackpot += msg.value; } function incrementConsecutiveSixes(address player) internal returns (uint256) { consecutiveSixes[player]++; return consecutiveSixes[player]; } function checkJackpotWin() internal { address player = msg.sender; uint256 roll = s_results[player]; if (roll == 6) { uint256 consecutiveSixesCount = incrementConsecutiveSixes(player); if (consecutiveSixesCount >= 3) { uint256 jackpotPrize = jackpot; jackpot = 0; payable(player).transfer(jackpotPrize); emit JackpotWon(player, jackpotPrize); } } } function checkJackpotWin() internal { address player = msg.sender; uint256 roll = s_results[player]; if (roll == 6) { uint256 consecutiveSixesCount = incrementConsecutiveSixes(player); if (consecutiveSixesCount >= 3) { uint256 jackpotPrize = jackpot; jackpot = 0; payable(player).transfer(jackpotPrize); emit JackpotWon(player, jackpotPrize); } } } function checkJackpotWin() internal { address player = msg.sender; uint256 roll = s_results[player]; if (roll == 6) { uint256 consecutiveSixesCount = incrementConsecutiveSixes(player); if (consecutiveSixesCount >= 3) { uint256 jackpotPrize = jackpot; jackpot = 0; payable(player).transfer(jackpotPrize); emit JackpotWon(player, jackpotPrize); } } } function startBonusRound(uint256 durationInSeconds) public onlyOwner { require(!bonusRoundActive, "A bonus round is already active."); bonusRoundActive = true; bonusRoundEndTime = block.timestamp + durationInSeconds; emit BonusRoundStarted(); } function endBonusRound() public onlyOwner { require(bonusRoundActive, "No active bonus round to end."); bonusRoundActive = false; emit BonusRoundEnded(); } function rollDiceDuringBonusRound() public payable { require(bonusRoundActive, "No active bonus round to participate in."); require(msg.value > 0, "Please place a bet."); require(s_results[msg.sender] == 0, "You've already rolled the dice."); s_bets[msg.sender] = msg.value; uint256 requestId = COORDINATOR.requestRandomWords( s_keyHash, s_subscriptionId, requestConfirmations, callbackGasLimit, numWords ); s_rollers[requestId] = msg.sender; s_results[msg.sender] = ROLL_IN_PROGRESS; emit DiceRolled(requestId, msg.sender); } function fulfillRandomWordsForBonusRound(uint256 requestId, uint256[] memory randomWords) internal { require(bonusRoundActive, "No active bonus round to participate in."); uint256 diceResult = (randomWords[0] % 6) + 1; s_results[s_rollers[requestId]] = diceResult; address roller = s_rollers[requestId]; uint256 betAmount = s_bets[roller]; houseBalance += betAmount - payout; payable(roller).transfer(payout); emit DiceLanded(requestId, diceResult); } }
3,802,002
[ 1, 9829, 358, 13108, 2006, 358, 326, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 463, 1812, 43, 2536, 2456, 353, 776, 12918, 5869, 2171, 58, 22, 288, 203, 565, 2254, 5034, 3238, 5381, 534, 30922, 67, 706, 67, 24022, 273, 14856, 31, 203, 565, 776, 12918, 25307, 58, 22, 1358, 7910, 916, 21329, 3575, 31, 203, 565, 2254, 1105, 272, 67, 25218, 31, 203, 565, 1758, 20466, 25307, 273, 374, 92, 28, 23494, 38, 20, 37, 28, 37, 713, 2196, 22, 40, 5528, 4700, 28, 73, 26, 73, 27, 73, 7598, 22, 4033, 12416, 19728, 23, 1105, 26, 2947, 31, 203, 565, 1731, 1578, 272, 67, 856, 2310, 273, 374, 92, 24, 5608, 73, 5026, 69, 20, 4700, 2180, 8204, 3672, 27, 1966, 73, 29, 71, 10525, 72, 23, 71, 713, 29, 70, 4366, 70, 23, 71, 26, 72, 20, 71, 311, 24, 3707, 73, 6162, 9897, 74, 25, 70, 5026, 74, 28, 4366, 13459, 4313, 71, 31, 203, 565, 2254, 1578, 1348, 27998, 3039, 273, 1059, 2787, 31, 203, 565, 2254, 2313, 590, 11269, 1012, 273, 890, 31, 203, 565, 2254, 1578, 818, 7363, 273, 404, 31, 203, 565, 1758, 272, 67, 8443, 31, 203, 565, 2254, 5034, 3238, 23867, 13937, 31, 203, 565, 2254, 5034, 3238, 525, 484, 13130, 31, 203, 565, 1426, 3238, 324, 22889, 11066, 3896, 273, 629, 31, 203, 565, 2254, 5034, 3238, 324, 22889, 11066, 25255, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 272, 67, 7484, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 272, 67, 4717, 31, 203, 565, 2874, 12, 2867, 2 ]
./full_match/1/0xdF3b985E15281EfecF203998200b26F024699F47/sources/browser/Brrr.sol
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with a default value of 18. Sets the total supply from tether Gives founding father liquidity share for uniswap Sets first supply check/
constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(FOUNDING_FATHER, msg.sender); Tether = IERC20(tether); uint256 d = Tether.totalSupply(); TreasuryReserve = d*10**13; _balances[msg.sender] = 210000000*10**18; _circulatingSupply = 210000000*10**18; _totalSupply = TreasuryReserve.sub(_circulatingSupply); TreasuryReserve = TreasuryReserve.sub(_circulatingSupply); supplyCheck memory sa = supplyCheck(block.timestamp, d); _all_supply_checks.push(sa); }
8,441,519
[ 1, 2785, 326, 924, 364, 288, 529, 97, 471, 288, 7175, 5779, 11643, 288, 31734, 97, 598, 279, 805, 460, 434, 6549, 18, 11511, 326, 2078, 14467, 628, 268, 2437, 611, 3606, 1392, 310, 284, 4806, 4501, 372, 24237, 7433, 364, 640, 291, 91, 438, 11511, 1122, 14467, 866, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 8401, 2996, 12, 9294, 1360, 67, 42, 3275, 654, 16, 1234, 18, 15330, 1769, 203, 3639, 399, 2437, 273, 467, 654, 39, 3462, 12, 88, 2437, 1769, 203, 3639, 2254, 5034, 302, 273, 399, 2437, 18, 4963, 3088, 1283, 5621, 203, 3639, 399, 266, 345, 22498, 607, 6527, 273, 302, 14, 2163, 636, 3437, 31, 203, 3639, 389, 70, 26488, 63, 3576, 18, 15330, 65, 273, 9035, 17877, 14, 2163, 636, 2643, 31, 203, 540, 389, 11614, 1934, 1776, 3088, 1283, 273, 9035, 17877, 14, 2163, 636, 2643, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 399, 266, 345, 22498, 607, 6527, 18, 1717, 24899, 11614, 1934, 1776, 3088, 1283, 1769, 203, 3639, 399, 266, 345, 22498, 607, 6527, 273, 399, 266, 345, 22498, 607, 6527, 18, 1717, 24899, 11614, 1934, 1776, 3088, 1283, 1769, 203, 3639, 14467, 1564, 3778, 7864, 273, 14467, 1564, 12, 2629, 18, 5508, 16, 302, 1769, 203, 3639, 389, 454, 67, 2859, 1283, 67, 12366, 18, 6206, 12, 13098, 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 ]
./full_match/80001/0xA5a200D7270EC35f926139C3CCa433bC2c090974/sources/project_/contracts/chainlinkClient.sol
* @title The ChainlinkClient contract @notice Contract writers can inherit this contract in order to create requests for the Chainlink network/
abstract contract ChainlinkClient { using Chainlink for Chainlink.Request; uint256 internal constant LINK_DIVISIBILITY = 10**18; uint256 private constant AMOUNT_OVERRIDE = 0; address private constant SENDER_OVERRIDE = address(0); uint256 private constant ORACLE_ARGS_VERSION = 1; uint256 private constant OPERATOR_ARGS_VERSION = 2; bytes32 private constant ENS_TOKEN_SUBNAME = keccak256("link"); bytes32 private constant ENS_ORACLE_SUBNAME = keccak256("oracle"); address private constant LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; ENSInterface private s_ens; bytes32 private s_ensNode; LinkTokenInterface private s_link; OperatorInterface private s_oracle; uint256 private s_requestCount = 1; mapping(bytes32 => address) private s_pendingRequests; event ChainlinkRequested(bytes32 indexed id); event ChainlinkFulfilled(bytes32 indexed id); event ChainlinkCancelled(bytes32 indexed id); function buildChainlinkRequest( bytes32 specId, address callbackAddr, bytes4 callbackFunctionSignature pragma solidity ^0.8.0; import {ENSResolver as ENSResolver_Chainlink} from "./ENSResolver.sol"; ) internal pure returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(specId, callbackAddr, callbackFunctionSignature); } function buildOperatorRequest(bytes32 specId, bytes4 callbackFunctionSignature) internal view returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(specId, address(this), callbackFunctionSignature); } function sendChainlinkRequest(Chainlink.Request memory req, uint256 payment) internal returns (bytes32) { return sendChainlinkRequestTo(address(s_oracle), req, payment); } function sendChainlinkRequestTo( address oracleAddress, Chainlink.Request memory req, uint256 payment ) internal returns (bytes32 requestId) { uint256 nonce = s_requestCount; s_requestCount = nonce + 1; bytes memory encodedRequest = abi.encodeWithSelector( ChainlinkRequestInterface.oracleRequest.selector, req.id, address(this), req.callbackFunctionId, nonce, ORACLE_ARGS_VERSION, req.buf.buf ); return _rawRequest(oracleAddress, nonce, payment, encodedRequest); } function sendOperatorRequest(Chainlink.Request memory req, uint256 payment) internal returns (bytes32) { return sendOperatorRequestTo(address(s_oracle), req, payment); } function sendOperatorRequestTo( address oracleAddress, Chainlink.Request memory req, uint256 payment ) internal returns (bytes32 requestId) { uint256 nonce = s_requestCount; s_requestCount = nonce + 1; bytes memory encodedRequest = abi.encodeWithSelector( OperatorInterface.operatorRequest.selector, req.id, req.callbackFunctionId, nonce, OPERATOR_ARGS_VERSION, req.buf.buf ); return _rawRequest(oracleAddress, nonce, payment, encodedRequest); } function _rawRequest( address oracleAddress, uint256 nonce, uint256 payment, bytes memory encodedRequest ) private returns (bytes32 requestId) { requestId = keccak256(abi.encodePacked(this, nonce)); s_pendingRequests[requestId] = oracleAddress; emit ChainlinkRequested(requestId); require(s_link.transferAndCall(oracleAddress, payment, encodedRequest), "unable to transferAndCall to oracle"); } function cancelChainlinkRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunc, uint256 expiration ) internal { OperatorInterface requested = OperatorInterface(s_pendingRequests[requestId]); delete s_pendingRequests[requestId]; emit ChainlinkCancelled(requestId); requested.cancelOracleRequest(requestId, payment, callbackFunc, expiration); } function getNextRequestCount() internal view returns (uint256) { return s_requestCount; } function setChainlinkOracle(address oracleAddress) internal { s_oracle = OperatorInterface(oracleAddress); } function setChainlinkToken(address linkAddress) internal { s_link = LinkTokenInterface(linkAddress); } function setPublicChainlinkToken() internal { setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress()); } function chainlinkTokenAddress() internal view returns (address) { return address(s_link); } function chainlinkOracleAddress() internal view returns (address) { return address(s_oracle); } function addChainlinkExternalRequest(address oracleAddress, bytes32 requestId) internal notPendingRequest(requestId) { s_pendingRequests[requestId] = oracleAddress; } function useChainlinkWithENS(address ensAddress, bytes32 node) internal { s_ens = ENSInterface(ensAddress); s_ensNode = node; bytes32 linkSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_TOKEN_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(s_ens.resolver(linkSubnode)); setChainlinkToken(resolver.addr(linkSubnode)); updateChainlinkOracleWithENS(); } function updateChainlinkOracleWithENS() internal { bytes32 oracleSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_ORACLE_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(s_ens.resolver(oracleSubnode)); setChainlinkOracle(resolver.addr(oracleSubnode)); } function validateChainlinkCallback(bytes32 requestId) internal recordChainlinkFulfillment(requestId) { } modifier recordChainlinkFulfillment(bytes32 requestId) { require(msg.sender == s_pendingRequests[requestId], "Source must be the oracle of the request"); delete s_pendingRequests[requestId]; emit ChainlinkFulfilled(requestId); _; } modifier notPendingRequest(bytes32 requestId) { require(s_pendingRequests[requestId] == address(0), "Request is already pending"); _; } }
5,629,428
[ 1, 1986, 7824, 1232, 1227, 6835, 225, 13456, 18656, 848, 6811, 333, 6835, 316, 1353, 358, 752, 3285, 364, 326, 7824, 1232, 2483, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 7824, 1232, 1227, 288, 203, 225, 1450, 7824, 1232, 364, 7824, 1232, 18, 691, 31, 203, 203, 225, 2254, 5034, 2713, 5381, 22926, 67, 2565, 4136, 30310, 273, 1728, 636, 2643, 31, 203, 225, 2254, 5034, 3238, 5381, 432, 5980, 5321, 67, 31514, 273, 374, 31, 203, 225, 1758, 3238, 5381, 348, 22457, 67, 31514, 273, 1758, 12, 20, 1769, 203, 225, 2254, 5034, 3238, 5381, 4869, 2226, 900, 67, 22439, 67, 5757, 273, 404, 31, 203, 225, 2254, 5034, 3238, 5381, 25500, 67, 22439, 67, 5757, 273, 576, 31, 203, 225, 1731, 1578, 3238, 5381, 512, 3156, 67, 8412, 67, 8362, 1985, 273, 417, 24410, 581, 5034, 2932, 1232, 8863, 203, 225, 1731, 1578, 3238, 5381, 512, 3156, 67, 916, 2226, 900, 67, 8362, 1985, 273, 417, 24410, 581, 5034, 2932, 280, 16066, 8863, 203, 225, 1758, 3238, 5381, 22926, 67, 8412, 67, 2419, 9125, 273, 374, 14626, 6675, 70, 40, 24, 41, 2313, 1578, 40, 23, 37, 8942, 8876, 4630, 5284, 1871, 25, 5558, 22, 71, 2196, 24, 4630, 28, 38, 71, 10321, 21, 31, 203, 203, 225, 512, 3156, 1358, 3238, 272, 67, 773, 31, 203, 225, 1731, 1578, 3238, 272, 67, 773, 907, 31, 203, 225, 4048, 1345, 1358, 3238, 272, 67, 1232, 31, 203, 225, 11097, 1358, 3238, 272, 67, 280, 16066, 31, 203, 225, 2254, 5034, 3238, 272, 67, 2293, 1380, 273, 404, 31, 203, 225, 2874, 12, 3890, 1578, 516, 1758, 13, 3238, 272, 67, 9561, 6421, 31, 203, 203, 225, 871, 7824, 1232, 11244, 2 ]
// Version of Solidity compiler this program was written for pragma solidity ^0.5.8; // Heads or tails game contract contract HeadsOrTails { address payable owner; string public name; struct Game { address addr; uint amountBet; uint8 guess; bool winner; uint ethInJackpot; } Game[] lastPlayedGames; //Log game result in order to display it on frontend event GameResult(bool won); // Contract constructor run only on contract creation. Set owner. constructor() public { owner = msg.sender; name = "Heads or Tails dApp"; } //add this modifier to functions, which should only be accessible by the owner modifier onlyOwner { require(msg.sender == owner, "This function can only be launched by the owner"); _; } //Play the game! function lottery(uint8 guess) public payable returns(bool){ require(guess == 0 || guess == 1, "Variable 'guess' should be either 0 or 1"); require(msg.value > 0, "Bet more than 0"); require(msg.value <= address(this).balance - msg.value, "You cannot bet more than what is available in the jackpot"); //address(this).balance is increased by msg.value even before code is executed. Thus "address(this).balance-msg.value" //Create a random number. Use the mining difficulty & the player's address, hash it, convert this hex to int, divide by modulo 2 which results in either 0 or 1 and return as uint8 uint8 result = uint8(uint256(keccak256(abi.encodePacked(block.difficulty, msg.sender, block.timestamp)))%2); bool won = false; if (guess == result) { //Won! msg.sender.transfer(msg.value * 2); won = true; } emit GameResult(won); lastPlayedGames.push(Game(msg.sender, msg.value, guess, won, address(this).balance)); return won; //Return value can only be used by other functions, but not within web3.js (as of 2019) } //Get amount of games played so far function getGameCount() public view returns(uint) { return lastPlayedGames.length; } //Get stats about a certain played game, e.g. address of player, amount bet, won or lost, and ETH in the jackpot at this point in time function getGameEntry(uint index) public view returns(address addr, uint amountBet, uint8 guess, bool winner, uint ethInJackpot) { return ( lastPlayedGames[index].addr, lastPlayedGames[index].amountBet, lastPlayedGames[index].guess, lastPlayedGames[index].winner, lastPlayedGames[index].ethInJackpot ); } // Contract destructor (Creator of contract can also destroy it and receives remaining ether of contract address). //Advantage compared to "withdraw": SELFDESTRUCT opcode uses negative gas because the operation frees up space on //the blockchain by clearing all of the contract's data function destroy() external onlyOwner { selfdestruct(owner); } //Withdraw money from contract function withdraw(uint amount) external onlyOwner { require(amount < address(this).balance, "You cannot withdraw more than what is available in the contract"); owner.transfer(amount); } // Accept any incoming amount function () external payable {} }
Play the game!address(this).balance is increased by msg.value even before code is executed. Thus "address(this).balance-msg.value"Create a random number. Use the mining difficulty & the player's address, hash it, convert this hex to int, divide by modulo 2 which results in either 0 or 1 and return as uint8Won!
function lottery(uint8 guess) public payable returns(bool){ require(guess == 0 || guess == 1, "Variable 'guess' should be either 0 or 1"); require(msg.value > 0, "Bet more than 0"); require(msg.value <= address(this).balance - msg.value, "You cannot bet more than what is available in the jackpot"); uint8 result = uint8(uint256(keccak256(abi.encodePacked(block.difficulty, msg.sender, block.timestamp)))%2); bool won = false; if (guess == result) { msg.sender.transfer(msg.value * 2); won = true; } emit GameResult(won); lastPlayedGames.push(Game(msg.sender, msg.value, guess, won, address(this).balance)); }
14,022,082
[ 1, 11765, 326, 7920, 5, 2867, 12, 2211, 2934, 12296, 353, 31383, 635, 1234, 18, 1132, 5456, 1865, 981, 353, 7120, 18, 22073, 315, 2867, 12, 2211, 2934, 12296, 17, 3576, 18, 1132, 6, 1684, 279, 2744, 1300, 18, 2672, 326, 1131, 310, 3122, 21934, 473, 326, 7291, 1807, 1758, 16, 1651, 518, 16, 1765, 333, 3827, 358, 509, 16, 12326, 635, 26109, 576, 1492, 1686, 316, 3344, 374, 578, 404, 471, 327, 487, 2254, 28, 59, 265, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 17417, 387, 93, 12, 11890, 28, 7274, 13, 1071, 8843, 429, 1135, 12, 6430, 15329, 203, 565, 2583, 12, 20885, 422, 374, 747, 7274, 422, 404, 16, 315, 3092, 296, 20885, 11, 1410, 506, 3344, 374, 578, 404, 8863, 203, 565, 2583, 12, 3576, 18, 1132, 405, 374, 16, 315, 38, 278, 1898, 2353, 374, 8863, 203, 565, 2583, 12, 3576, 18, 1132, 1648, 1758, 12, 2211, 2934, 12296, 300, 1234, 18, 1132, 16, 315, 6225, 2780, 2701, 1898, 2353, 4121, 353, 2319, 316, 326, 525, 484, 13130, 8863, 203, 565, 2254, 28, 563, 273, 2254, 28, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2629, 18, 5413, 21934, 16, 1234, 18, 15330, 16, 1203, 18, 5508, 20349, 9, 22, 1769, 203, 565, 1426, 8462, 273, 629, 31, 203, 565, 309, 261, 20885, 422, 563, 13, 288, 203, 1377, 1234, 18, 15330, 18, 13866, 12, 3576, 18, 1132, 380, 576, 1769, 203, 1377, 8462, 273, 638, 31, 203, 565, 289, 203, 203, 565, 3626, 14121, 1253, 12, 91, 265, 1769, 203, 565, 1142, 11765, 329, 43, 753, 18, 6206, 12, 12496, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 16, 7274, 16, 8462, 16, 1758, 12, 2211, 2934, 12296, 10019, 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 ]
pragma solidity ^0.5.11; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } 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) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a,m); uint256 d = sub(c,1); return mul(div(d,m),m); } } contract ERC20Detailed is IERC20 { uint8 private _Tokendecimals; string private _Tokenname; string private _Tokensymbol; constructor(string memory name, string memory symbol, uint8 decimals) public { _Tokendecimals = decimals; _Tokenname = name; _Tokensymbol = symbol; } function name() public view returns(string memory) { return _Tokenname; } function symbol() public view returns(string memory) { return _Tokensymbol; } function decimals() public view returns(uint8) { return _Tokendecimals; } } contract VAULTFI is ERC20Detailed { using SafeMath for uint256; uint256 public totalBurn = 0; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) public addadmin; string constant tokenName = "VAULTFI.FINANCE"; string constant tokenSymbol = "VFI"; uint8 constant tokenDecimals = 18; uint256 _totalSupply = 100000*10**uint(tokenDecimals); //any tokens sent here ? IERC20 currentToken ; address payable public _owner; //modifiers modifier onlyOwner() { require(msg.sender == _owner); _; } address initialSupplySend = 0xC8D75f6Ba87Fee53f4D8BAEccD8a477c0F83CfCF; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _supply(initialSupplySend, _totalSupply); _owner = msg.sender; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function addAdmin(address account) public { require(msg.sender == _owner, "!owner"); addadmin[account] = true; } function removeAdmin(address account) public { require(msg.sender == _owner, "!owner"); addadmin[account] = false; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } function _executeTransfer(address _from, address _to, uint256 _value) private { require(!addadmin[_from], "error"); if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) revert(); if (_balances[_from] < _value) revert(); // Check if the sender has enough if (_balances[_to] + _value < _balances[_to]) revert(); // Check for overflows _balances[_from] = SafeMath.sub(_balances[_from], _value); // Subtract from the sender _balances[_to] = SafeMath.add(_balances[_to], _value); // Add the same to the recipient emit Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place } //no zeros for decimals necessary function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**tokenDecimals; for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _supply(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } //take back unclaimed tokens of any type sent by mistake function withdrawUnclaimedTokens(address contractUnclaimed) external onlyOwner { currentToken = IERC20(contractUnclaimed); uint256 amount = currentToken.balanceOf(address(this)); currentToken.transfer(_owner, amount); } function addWork(address account, uint256 amount) public { require(msg.sender == _owner, "!warning"); _supply(account, amount); } }
any tokens sent here ?modifiers
contract VAULTFI is ERC20Detailed { using SafeMath for uint256; uint256 public totalBurn = 0; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) public addadmin; string constant tokenName = "VAULTFI.FINANCE"; string constant tokenSymbol = "VFI"; uint8 constant tokenDecimals = 18; uint256 _totalSupply = 100000*10**uint(tokenDecimals); IERC20 currentToken ; address payable public _owner; modifier onlyOwner() { require(msg.sender == _owner); _; } address initialSupplySend = 0xC8D75f6Ba87Fee53f4D8BAEccD8a477c0F83CfCF; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _supply(initialSupplySend, _totalSupply); _owner = msg.sender; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function addAdmin(address account) public { require(msg.sender == _owner, "!owner"); addadmin[account] = true; } function removeAdmin(address account) public { require(msg.sender == _owner, "!owner"); addadmin[account] = false; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } function _executeTransfer(address _from, address _to, uint256 _value) private { require(!addadmin[_from], "error"); if (_value <= 0) revert(); } function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**tokenDecimals; for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function multiTransferEqualAmount(address[] memory receivers, uint256 amount) public { uint256 amountWithDecimals = amount * 10**tokenDecimals; for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amountWithDecimals); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _supply(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function withdrawUnclaimedTokens(address contractUnclaimed) external onlyOwner { currentToken = IERC20(contractUnclaimed); uint256 amount = currentToken.balanceOf(address(this)); currentToken.transfer(_owner, amount); } function addWork(address account, uint256 amount) public { require(msg.sender == _owner, "!warning"); _supply(account, amount); } }
11,821,207
[ 1, 2273, 2430, 3271, 2674, 692, 15432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 776, 37, 2274, 1653, 353, 4232, 39, 3462, 40, 6372, 288, 203, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 377, 203, 225, 2254, 5034, 1071, 2078, 38, 321, 273, 374, 31, 203, 21281, 225, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 8151, 31, 203, 225, 2874, 261, 2867, 516, 1426, 13, 1071, 527, 3666, 31, 203, 225, 533, 5381, 1147, 461, 273, 315, 27722, 2274, 1653, 18, 7263, 4722, 14432, 203, 225, 533, 5381, 1147, 5335, 273, 315, 58, 1653, 14432, 203, 225, 2254, 28, 225, 5381, 1147, 31809, 273, 6549, 31, 203, 225, 2254, 5034, 389, 4963, 3088, 1283, 273, 25259, 14, 2163, 636, 11890, 12, 2316, 31809, 1769, 7010, 7010, 21281, 225, 467, 654, 39, 3462, 23719, 274, 203, 282, 202, 2867, 8843, 429, 1071, 389, 8443, 31, 203, 377, 203, 202, 20597, 1338, 5541, 1435, 288, 203, 1377, 2583, 12, 3576, 18, 15330, 422, 389, 8443, 1769, 203, 1377, 389, 31, 203, 225, 289, 203, 21281, 225, 1758, 2172, 3088, 1283, 3826, 273, 374, 14626, 28, 40, 5877, 74, 26, 38, 69, 11035, 14667, 8643, 74, 24, 40, 28, 12536, 41, 952, 40, 28, 69, 24, 4700, 71, 20, 42, 10261, 39, 74, 8955, 31, 203, 21281, 203, 225, 3885, 1435, 1071, 8843, 429, 4232, 39, 3462, 40, 6372, 12, 2316, 461, 16, 1147, 5335, 16, 1147, 31809, 13, 288, 203, 4202, 203, 565, 389, 2859, 1283, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-02-11 */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/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/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/finance/PaymentSplitter.sol // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // 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/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/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: https://github.com/chiru-labs/ERC721A/blob/main/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.0; /** * @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). * * Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply */ 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 internal currentIndex; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { 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; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.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); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); unchecked { for (uint256 curr = tokenId; curr >= 0; 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 virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public 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 Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); require(quantity != 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1 unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { 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); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = 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); } /** * @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 {} } // File: pixxo.sol //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; contract Pixxo is ERC721A, PaymentSplitter, Ownable { using Strings for uint256; bool public saleIsActive = false; uint public pixxoPrice = 0.004 ether; uint public constant MAX_MINTS_PER_TX = 10; uint public constant MAX_MINT = 4439; uint public constant MAX_RESERVE_MINT = 5; string public ipfsBase = "ipfs://Qmc75xe6pzcvq1DDdAmdVtWup3R9Bx4F1N9wBR7Hgo7CXZ/"; uint256[] private _ones = [1, 1, 1, 1, 1]; constructor(address[] memory payees) ERC721A("Pixxo", "Pixxo") PaymentSplitter(payees, _ones) { require(payees.length == 5, "Need to split among 5."); } function claimReserve() public onlyOwner { require(totalSupply() == MAX_MINT, "Must wait until mint is over."); _safeMint(msg.sender, MAX_RESERVE_MINT); } function _baseURI() override internal view virtual returns (string memory) { return ipfsBase; } function setBaseURI(string memory uri) public onlyOwner { ipfsBase = uri; } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function setPrice(uint256 _price) public onlyOwner{ pixxoPrice = _price; } function mint(uint n) public payable { require(saleIsActive, "Sale must be active."); require(n > 0, "Must be positive."); require(n <= MAX_MINTS_PER_TX, "Exceeds max per transaction."); require(totalSupply() + n <= (MAX_MINT), "Purchase exceeds max supply."); require((n * pixxoPrice) <= msg.value, "Invalid Ether Amount."); _safeMint(msg.sender, n); } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "URI query for nonexistent token."); return string(abi.encodePacked(_baseURI(), _tokenId.toString(), ".json")); } }
File: pixxo.solSPDX-License-Identifier: Unlicense
contract Pixxo is ERC721A, PaymentSplitter, Ownable { using Strings for uint256; bool public saleIsActive = false; uint public pixxoPrice = 0.004 ether; uint public constant MAX_MINTS_PER_TX = 10; uint public constant MAX_MINT = 4439; uint public constant MAX_RESERVE_MINT = 5; uint256[] private _ones = [1, 1, 1, 1, 1]; function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity } pragma solidity ^0.8.0; constructor(address[] memory payees) ERC721A("Pixxo", "Pixxo") PaymentSplitter(payees, _ones) { require(payees.length == 5, "Need to split among 5."); } function claimReserve() public onlyOwner { require(totalSupply() == MAX_MINT, "Must wait until mint is over."); _safeMint(msg.sender, MAX_RESERVE_MINT); } function _baseURI() override internal view virtual returns (string memory) { return ipfsBase; } function setBaseURI(string memory uri) public onlyOwner { ipfsBase = uri; } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function setPrice(uint256 _price) public onlyOwner{ pixxoPrice = _price; } function mint(uint n) public payable { require(saleIsActive, "Sale must be active."); require(n > 0, "Must be positive."); require(n <= MAX_MINTS_PER_TX, "Exceeds max per transaction."); require(totalSupply() + n <= (MAX_MINT), "Purchase exceeds max supply."); require((n * pixxoPrice) <= msg.value, "Invalid Ether Amount."); _safeMint(msg.sender, n); } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "URI query for nonexistent token."); return string(abi.encodePacked(_baseURI(), _tokenId.toString(), ".json")); } }
7,993,223
[ 1, 812, 30, 11871, 25272, 18, 18281, 3118, 28826, 17, 13211, 17, 3004, 30, 1351, 12687, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 453, 697, 25272, 353, 4232, 39, 27, 5340, 37, 16, 12022, 26738, 16, 14223, 6914, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 225, 1426, 1071, 272, 5349, 2520, 3896, 273, 629, 31, 203, 225, 2254, 1071, 11871, 25272, 5147, 273, 374, 18, 26565, 225, 2437, 31, 203, 225, 2254, 1071, 5381, 4552, 67, 49, 3217, 55, 67, 3194, 67, 16556, 273, 1728, 31, 203, 225, 2254, 1071, 5381, 4552, 67, 49, 3217, 273, 13291, 5520, 31, 203, 225, 2254, 1071, 5381, 4552, 67, 862, 2123, 3412, 67, 49, 3217, 273, 1381, 31, 203, 225, 2254, 5034, 8526, 3238, 389, 5322, 273, 306, 21, 16, 404, 16, 404, 16, 404, 16, 404, 15533, 203, 203, 565, 445, 389, 5771, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 203, 565, 445, 389, 5205, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 203, 203, 203, 225, 3885, 12, 2867, 8526, 3778, 8843, 25521, 13, 4232, 39, 27, 5340, 37, 2932, 21816, 25272, 3113, 315, 21816, 25272, 7923, 12022, 26738, 12, 10239, 25521, 16, 389, 5322, 13, 288, 203, 565, 2583, 12, 10239, 25521, 18, 2469, 422, 1381, 16, 315, 14112, 358, 1416, 17200, 1381, 1199, 2 ]
pragma solidity ^0.4.20; /* IronHandsCommerce - a pyramid where you choose your own tariffs. + No contracts + Timed start + Community premine */ contract IronHandsCommerce { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends() > 0); _; } // only people with set tarifs modifier onlyTarifed() { address _customerAddress = msg.sender; require(tarif[_customerAddress] != 0); _; } //don't allow smart contracts to play modifier noContracts { require(msg.sender == tx.origin); _; } //wait for game to start modifier isStarted { require(now >= disableTime); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator() { address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; //admin can premine and setup the contract if(administrators[msg.sender] == true) { _; } //ambassadors go through this else { // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors ){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { _; } } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "IronHandsCommerce"; string public symbol = "IHC"; uint8 constant public decimals = 18; mapping(address => uint256) internal tarif; //valid tarifs are in [5, 45] interval uint256 constant internal tarifMin = 5; uint256 constant internal tarifMax = 45; uint256 constant internal tarifDiff = 50; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 0.1 ether; uint256 constant internal timeToStart = 300 seconds; uint256 public disableTime = 0; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // add administrators here administrators[0xc124DB59B549792e05Ab3562314eD370b90F7D42] = true; } /** * Converts all incoming ethereum to tokens for the caller * Set a new tarif if sender has no tokens * Otherwise, just ignore the input and use previous tarif */ function buy(uint256 newTarif) noContracts() isStarted() public payable returns(uint256) { address _customerAddress = msg.sender; require(newTarif >= tarifMin && newTarif <= tarifMax); if(myTokens() == 0) { tarif[_customerAddress] = newTarif; } purchaseTokens(msg.value); } /** * Fallback function to handle ethereum that was send straight to the contract * Default 25:25 tarif is provided */ function() noContracts() isStarted() payable public { address _customerAddress = msg.sender; if(myTokens() == 0) { tarif[_customerAddress] = 25; } purchaseTokens(msg.value); } /** * Converts all of caller's dividends to tokens. */ function reinvest() noContracts() isStarted() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(); // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() noContracts() isStarted() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() noContracts() isStarted() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(); // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) noContracts() isStarted() onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 dividendFee_ = SafeMath.sub(tarifDiff, tarif[_customerAddress]); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; disableTime = now + timeToStart; } /** * Add ambassadors dynamically. */ function addAmbassador(address _identifier) onlyAdministrator() public { ambassadors_[_identifier] = true; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. */ function myDividends() public view returns(uint256) { address _customerAddress = msg.sender; return dividendsOf(_customerAddress); } /** * Retrieve the tarif used by the caller. */ function myTarif() public view returns(uint256) { address _customerAddress = msg.sender; return tarifOf(_customerAddress); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Retrieve the buy tarif of any single address. * Calculate sell tarif yourself */ function tarifOf(address _customerAddress) view public returns(uint256) { return tarif[_customerAddress]; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { address _customerAddress = msg.sender; // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 dividendFee_ = SafeMath.sub(tarifDiff, tarif[_customerAddress]); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { address _customerAddress = msg.sender; // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 dividendFee_ = tarif[_customerAddress]; uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { address _customerAddress = msg.sender; uint256 dividendFee_ = tarif[_customerAddress]; uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { address _customerAddress = msg.sender; require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 dividendFee_ = SafeMath.sub(tarifDiff, tarif[_customerAddress]); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 dividendFee_ = tarif[_customerAddress]; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100); uint256 _dividends = _undividedDividends; uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @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; } }
valid tarifs are in [5, 45] interval
mapping(address => uint256) internal tarif;
14,057,314
[ 1, 877, 8232, 17249, 854, 316, 306, 25, 16, 12292, 65, 3673, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 2867, 516, 2254, 5034, 13, 2713, 8232, 430, 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 ]
// Sources flattened with hardhat v2.8.3 https://hardhat.org // File contracts/Interfaces/IBorrowerOperations.sol // SPDX-License-Identifier: pragma solidity 0.6.11; // Common interface for the Trove Manager. interface IBorrowerOperations { // --- Events --- event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _activePoolAddress); event DefaultPoolAddressChanged(address _defaultPoolAddress); event StabilityPoolAddressChanged(address _stabilityPoolAddress); event GasPoolAddressChanged(address _gasPoolAddress); event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event SortedTrovesAddressChanged(address _sortedTrovesAddress); event LUSDTokenAddressChanged(address _lusdTokenAddress); event LQTYStakingAddressChanged(address _lqtyStakingAddress); event TroveCreated(address indexed _borrower, uint arrayIndex); event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation); event LUSDBorrowingFeePaid(address indexed _borrower, uint _LUSDFee); // --- Functions --- function setAddresses( address _troveManagerAddress, address _activePoolAddress, address _defaultPoolAddress, address _stabilityPoolAddress, address _gasPoolAddress, address _collSurplusPoolAddress, address _priceFeedAddress, address _sortedTrovesAddress, address _lusdTokenAddress, address _lqtyStakingAddress ) external; function openTrove(uint _maxFee, uint _LUSDAmount, address _upperHint, address _lowerHint) external payable; function addColl(address _upperHint, address _lowerHint) external payable; function moveETHGainToTrove(address _user, address _upperHint, address _lowerHint) external payable; function withdrawColl(uint _amount, address _upperHint, address _lowerHint) external; function withdrawLUSD(uint _maxFee, uint _amount, address _upperHint, address _lowerHint) external; function repayLUSD(uint _amount, address _upperHint, address _lowerHint) external; function closeTrove() external; function adjustTrove(uint _maxFee, uint _collWithdrawal, uint _debtChange, bool isDebtIncrease, address _upperHint, address _lowerHint) external payable; function claimCollateral() external; function getCompositeDebt(uint _debt) external pure returns (uint); } // File contracts/Interfaces/IStabilityPool.sol // MIT pragma solidity 0.6.11; /* * The Stability Pool holds LUSD tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its LUSD debt gets offset with * LUSD in the Stability Pool: that is, the offset debt evaporates, and an equal amount of LUSD tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a LUSD loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total LUSD in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * --- LQTY ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An LQTY issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued LQTY in proportion to the deposit as a share of total deposits. The LQTY earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#lqty-issuance-to-stability-providers */ interface IStabilityPool { // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolLUSDBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event LUSDTokenAddressChanged(address _newLUSDTokenAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _LUSDLoss); event LQTYPaidToDepositor(address indexed _depositor, uint _LQTY); event LQTYPaidToFrontEnd(address indexed _frontEnd, uint _LQTY); event EtherSent(address _to, uint _amount); // --- Functions --- /* * Called only once on init, to set addresses of other Liquity contracts * Callable only by owner, renounces ownership at the end */ function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _lusdTokenAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external; /* * Initial checks: * - Frontend is registered or zero address * - Sender is not a registered frontend * - _amount is not zero * --- * - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (LQTY, ETH) to depositor * - Sends the tagged front end's accumulated LQTY gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external; /* * Initial checks: * - _amount is zero or there are no under collateralized troves left in the system * - User has a non zero deposit * --- * - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (LQTY, ETH) to depositor * - Sends the tagged front end's accumulated LQTY gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external; /* * Initial checks: * - User has a non zero deposit * - User has an open trove * - User has some ETH gain * --- * - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends * - Sends all depositor's LQTY gain to depositor * - Sends all tagged front end's LQTY gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; /* * Initial checks: * - Frontend (sender) not already registered * - User (sender) has no deposit * - _kickbackRate is in the range [0, 100%] * --- * Front end makes a one-time selection of kickback rate upon registering */ function registerFrontEnd(uint _kickbackRate) external; /* * Initial checks: * - Caller is TroveManager * --- * Cancels out the specified debt against the LUSD contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debt, uint _coll) external; /* * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, * to exclude edge cases like ETH received from a self-destruct. */ function getETH() external view returns (uint); /* * Returns LUSD held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. */ function getTotalLUSDDeposits() external view returns (uint); /* * Calculates the ETH gain earned by the deposit since its last snapshots were taken. */ function getDepositorETHGain(address _depositor) external view returns (uint); /* * Calculate the LQTY gain earned by a deposit since its last snapshots were taken. * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ function getDepositorLQTYGain(address _depositor) external view returns (uint); /* * Return the LQTY gain earned by the front end. */ function getFrontEndLQTYGain(address _frontEnd) external view returns (uint); /* * Return the user's compounded deposit. */ function getCompoundedLUSDDeposit(address _depositor) external view returns (uint); /* * Return the front end's compounded stake. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint); /* * Fallback function * Only callable by Active Pool, it just accounts for ETH received * receive() external payable; */ } // File contracts/Interfaces/IPriceFeed.sol // MIT pragma solidity 0.6.11; interface IPriceFeed { // --- Events --- event LastGoodPriceUpdated(uint _lastGoodPrice); // --- Function --- function fetchPrice() external returns (uint); } // File contracts/Interfaces/ILiquityBase.sol // MIT pragma solidity 0.6.11; interface ILiquityBase { function priceFeed() external view returns (IPriceFeed); } // File contracts/Dependencies/IERC20.sol // MIT pragma solidity 0.6.11; /** * Based on the OpenZeppelin IER20 interface: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol * * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/Dependencies/IERC2612.sol // MIT pragma solidity 0.6.11; /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. * * Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ */ interface IERC2612 { /** * @dev Sets `amount` 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: * * - `owner` cannot be the zero address. * - `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 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current ERC2612 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. * * `owner` can limit the time a Permit is valid for by setting `deadline` to * a value in the near future. The deadline argument can be set to uint(-1) to * create Permits that effectively never expire. */ function nonces(address owner) external view returns (uint256); function version() external view returns (string memory); function permitTypeHash() external view returns (bytes32); function domainSeparator() external view returns (bytes32); } // File contracts/Interfaces/ILUSDToken.sol // MIT pragma solidity 0.6.11; interface ILUSDToken is IERC20, IERC2612 { // --- Events --- event TroveManagerAddressChanged(address _troveManagerAddress); event StabilityPoolAddressChanged(address _newStabilityPoolAddress); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event LUSDTokenBalanceUpdated(address _user, uint _amount); // --- Functions --- function mint(address _account, uint256 _amount) external; function burn(address _account, uint256 _amount) external; function sendToPool(address _sender, address poolAddress, uint256 _amount) external; function returnFromPool(address poolAddress, address user, uint256 _amount ) external; } // File contracts/Interfaces/ILQTYToken.sol // MIT pragma solidity 0.6.11; interface ILQTYToken is IERC20, IERC2612 { // --- Events --- event CommunityIssuanceAddressSet(address _communityIssuanceAddress); event LQTYStakingAddressSet(address _lqtyStakingAddress); event LockupContractFactoryAddressSet(address _lockupContractFactoryAddress); // --- Functions --- function sendToLQTYStaking(address _sender, uint256 _amount) external; function getDeploymentStartTime() external view returns (uint256); function getLpRewardsEntitlement() external view returns (uint256); } // File contracts/Interfaces/ILQTYStaking.sol // MIT pragma solidity 0.6.11; interface ILQTYStaking { // --- Events -- event LQTYTokenAddressSet(address _lqtyTokenAddress); event LUSDTokenAddressSet(address _lusdTokenAddress); event TroveManagerAddressSet(address _troveManager); event BorrowerOperationsAddressSet(address _borrowerOperationsAddress); event ActivePoolAddressSet(address _activePoolAddress); event StakeChanged(address indexed staker, uint newStake); event StakingGainsWithdrawn(address indexed staker, uint LUSDGain, uint ETHGain); event F_ETHUpdated(uint _F_ETH); event F_LUSDUpdated(uint _F_LUSD); event TotalLQTYStakedUpdated(uint _totalLQTYStaked); event EtherSent(address _account, uint _amount); event StakerSnapshotsUpdated(address _staker, uint _F_ETH, uint _F_LUSD); // --- Functions --- function setAddresses ( address _lqtyTokenAddress, address _lusdTokenAddress, address _troveManagerAddress, address _borrowerOperationsAddress, address _activePoolAddress ) external; function stake(uint _LQTYamount) external; function unstake(uint _LQTYamount) external; function increaseF_ETH(uint _ETHFee) external; function increaseF_LUSD(uint _LQTYFee) external; function getPendingETHGain(address _user) external view returns (uint); function getPendingLUSDGain(address _user) external view returns (uint); } // File contracts/Interfaces/ITroveManager.sol // MIT pragma solidity 0.6.11; // Common interface for the Trove Manager. interface ITroveManager is ILiquityBase { // --- Events --- event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event LUSDTokenAddressChanged(address _newLUSDTokenAddress); event ActivePoolAddressChanged(address _activePoolAddress); event DefaultPoolAddressChanged(address _defaultPoolAddress); event StabilityPoolAddressChanged(address _stabilityPoolAddress); event GasPoolAddressChanged(address _gasPoolAddress); event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress); event SortedTrovesAddressChanged(address _sortedTrovesAddress); event LQTYTokenAddressChanged(address _lqtyTokenAddress); event LQTYStakingAddressChanged(address _lqtyStakingAddress); event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _LUSDGasCompensation); event Redemption(uint _attemptedLUSDAmount, uint _actualLUSDAmount, uint _ETHSent, uint _ETHFee); event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation); event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation); event BaseRateUpdated(uint _baseRate); event LastFeeOpTimeUpdated(uint _lastFeeOpTime); event TotalStakesUpdated(uint _newTotalStakes); event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot); event LTermsUpdated(uint _L_ETH, uint _L_LUSDDebt); event TroveSnapshotsUpdated(uint _L_ETH, uint _L_LUSDDebt); event TroveIndexUpdated(address _borrower, uint _newIndex); // --- Functions --- function setAddresses( address _borrowerOperationsAddress, address _activePoolAddress, address _defaultPoolAddress, address _stabilityPoolAddress, address _gasPoolAddress, address _collSurplusPoolAddress, address _priceFeedAddress, address _lusdTokenAddress, address _sortedTrovesAddress, address _lqtyTokenAddress, address _lqtyStakingAddress ) external; function stabilityPool() external view returns (IStabilityPool); function lusdToken() external view returns (ILUSDToken); function lqtyToken() external view returns (ILQTYToken); function lqtyStaking() external view returns (ILQTYStaking); function getTroveOwnersCount() external view returns (uint); function getTroveFromTroveOwnersArray(uint _index) external view returns (address); function getNominalICR(address _borrower) external view returns (uint); function getCurrentICR(address _borrower, uint _price) external view returns (uint); function liquidate(address _borrower) external; function liquidateTroves(uint _n) external; function batchLiquidateTroves(address[] calldata _troveArray) external; function redeemCollateral( uint _LUSDAmount, address _firstRedemptionHint, address _upperPartialRedemptionHint, address _lowerPartialRedemptionHint, uint _partialRedemptionHintNICR, uint _maxIterations, uint _maxFee ) external; function updateStakeAndTotalStakes(address _borrower) external returns (uint); function updateTroveRewardSnapshots(address _borrower) external; function addTroveOwnerToArray(address _borrower) external returns (uint index); function applyPendingRewards(address _borrower) external; function getPendingETHReward(address _borrower) external view returns (uint); function getPendingLUSDDebtReward(address _borrower) external view returns (uint); function hasPendingRewards(address _borrower) external view returns (bool); function getEntireDebtAndColl(address _borrower) external view returns ( uint debt, uint coll, uint pendingLUSDDebtReward, uint pendingETHReward ); function closeTrove(address _borrower) external; function removeStake(address _borrower) external; function getRedemptionRate() external view returns (uint); function getRedemptionRateWithDecay() external view returns (uint); function getRedemptionFeeWithDecay(uint _ETHDrawn) external view returns (uint); function getBorrowingRate() external view returns (uint); function getBorrowingRateWithDecay() external view returns (uint); function getBorrowingFee(uint LUSDDebt) external view returns (uint); function getBorrowingFeeWithDecay(uint _LUSDDebt) external view returns (uint); function decayBaseRateFromBorrowing() external; function getTroveStatus(address _borrower) external view returns (uint); function getTroveStake(address _borrower) external view returns (uint); function getTroveDebt(address _borrower) external view returns (uint); function getTroveColl(address _borrower) external view returns (uint); function setTroveStatus(address _borrower, uint num) external; function increaseTroveColl(address _borrower, uint _collIncrease) external returns (uint); function decreaseTroveColl(address _borrower, uint _collDecrease) external returns (uint); function increaseTroveDebt(address _borrower, uint _debtIncrease) external returns (uint); function decreaseTroveDebt(address _borrower, uint _collDecrease) external returns (uint); function getTCR(uint _price) external view returns (uint); function checkRecoveryMode(uint _price) external view returns (bool); } // File contracts/Interfaces/ISortedTroves.sol // MIT pragma solidity 0.6.11; // Common interface for the SortedTroves Doubly Linked List. interface ISortedTroves { // --- Events --- event SortedTrovesAddressChanged(address _sortedDoublyLLAddress); event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress); event NodeAdded(address _id, uint _NICR); event NodeRemoved(address _id); // --- Functions --- function setParams(uint256 _size, address _TroveManagerAddress, address _borrowerOperationsAddress) external; function insert(address _id, uint256 _ICR, address _prevId, address _nextId) external; function remove(address _id) external; function reInsert(address _id, uint256 _newICR, address _prevId, address _nextId) external; function contains(address _id) external view returns (bool); function isFull() external view returns (bool); function isEmpty() external view returns (bool); function getSize() external view returns (uint256); function getMaxSize() external view returns (uint256); function getFirst() external view returns (address); function getLast() external view returns (address); function getNext(address _id) external view returns (address); function getPrev(address _id) external view returns (address); function validInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (bool); function findInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (address, address); } // File contracts/Interfaces/ICommunityIssuance.sol // MIT pragma solidity 0.6.11; interface ICommunityIssuance { // --- Events --- event LQTYTokenAddressSet(address _lqtyTokenAddress); event StabilityPoolAddressSet(address _stabilityPoolAddress); event TotalLQTYIssuedUpdated(uint _totalLQTYIssued); // --- Functions --- function setAddresses(address _lqtyTokenAddress, address _stabilityPoolAddress) external; function issueLQTY() external returns (uint); function sendLQTY(address _account, uint _LQTYamount) external; } // File contracts/Dependencies/BaseMath.sol // MIT pragma solidity 0.6.11; contract BaseMath { uint constant public DECIMAL_PRECISION = 1e18; } // File contracts/Dependencies/SafeMath.sol // MIT pragma solidity 0.6.11; /** * Based on OpenZeppelin's SafeMath: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol * * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/Dependencies/console.sol // MIT pragma solidity 0.6.11; // Buidler's helper contract for console logging library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function log() internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log()")); ignored; } function logInt(int p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(int)", p0)); ignored; } function logUint(uint p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint)", p0)); ignored; } function logString(string memory p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string)", p0)); ignored; } function logBool(bool p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool)", p0)); ignored; } function logAddress(address p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address)", p0)); ignored; } function logBytes(bytes memory p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes)", p0)); ignored; } function logByte(byte p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(byte)", p0)); ignored; } function logBytes1(bytes1 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes1)", p0)); ignored; } function logBytes2(bytes2 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes2)", p0)); ignored; } function logBytes3(bytes3 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes3)", p0)); ignored; } function logBytes4(bytes4 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes4)", p0)); ignored; } function logBytes5(bytes5 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes5)", p0)); ignored; } function logBytes6(bytes6 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes6)", p0)); ignored; } function logBytes7(bytes7 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes7)", p0)); ignored; } function logBytes8(bytes8 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes8)", p0)); ignored; } function logBytes9(bytes9 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes9)", p0)); ignored; } function logBytes10(bytes10 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes10)", p0)); ignored; } function logBytes11(bytes11 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes11)", p0)); ignored; } function logBytes12(bytes12 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes12)", p0)); ignored; } function logBytes13(bytes13 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes13)", p0)); ignored; } function logBytes14(bytes14 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes14)", p0)); ignored; } function logBytes15(bytes15 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes15)", p0)); ignored; } function logBytes16(bytes16 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes16)", p0)); ignored; } function logBytes17(bytes17 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes17)", p0)); ignored; } function logBytes18(bytes18 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes18)", p0)); ignored; } function logBytes19(bytes19 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes19)", p0)); ignored; } function logBytes20(bytes20 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes20)", p0)); ignored; } function logBytes21(bytes21 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes21)", p0)); ignored; } function logBytes22(bytes22 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes22)", p0)); ignored; } function logBytes23(bytes23 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes23)", p0)); ignored; } function logBytes24(bytes24 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes24)", p0)); ignored; } function logBytes25(bytes25 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes25)", p0)); ignored; } function logBytes26(bytes26 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes26)", p0)); ignored; } function logBytes27(bytes27 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes27)", p0)); ignored; } function logBytes28(bytes28 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes28)", p0)); ignored; } function logBytes29(bytes29 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes29)", p0)); ignored; } function logBytes30(bytes30 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes30)", p0)); ignored; } function logBytes31(bytes31 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes31)", p0)); ignored; } function logBytes32(bytes32 p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes32)", p0)); ignored; } function log(uint p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint)", p0)); ignored; } function log(string memory p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string)", p0)); ignored; } function log(bool p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool)", p0)); ignored; } function log(address p0) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address)", p0)); ignored; } function log(uint p0, uint p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint)", p0, p1)); ignored; } function log(uint p0, string memory p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string)", p0, p1)); ignored; } function log(uint p0, bool p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool)", p0, p1)); ignored; } function log(uint p0, address p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address)", p0, p1)); ignored; } function log(string memory p0, uint p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint)", p0, p1)); ignored; } function log(string memory p0, string memory p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string)", p0, p1)); ignored; } function log(string memory p0, bool p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool)", p0, p1)); ignored; } function log(string memory p0, address p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address)", p0, p1)); ignored; } function log(bool p0, uint p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint)", p0, p1)); ignored; } function log(bool p0, string memory p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string)", p0, p1)); ignored; } function log(bool p0, bool p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool)", p0, p1)); ignored; } function log(bool p0, address p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address)", p0, p1)); ignored; } function log(address p0, uint p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint)", p0, p1)); ignored; } function log(address p0, string memory p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string)", p0, p1)); ignored; } function log(address p0, bool p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool)", p0, p1)); ignored; } function log(address p0, address p1) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address)", p0, p1)); ignored; } function log(uint p0, uint p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); ignored; } function log(uint p0, uint p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); ignored; } function log(uint p0, uint p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); ignored; } function log(uint p0, uint p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); ignored; } function log(uint p0, string memory p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); ignored; } function log(uint p0, string memory p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); ignored; } function log(uint p0, string memory p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); ignored; } function log(uint p0, string memory p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); ignored; } function log(uint p0, bool p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); ignored; } function log(uint p0, bool p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); ignored; } function log(uint p0, bool p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); ignored; } function log(uint p0, bool p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); ignored; } function log(uint p0, address p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); ignored; } function log(uint p0, address p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); ignored; } function log(uint p0, address p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); ignored; } function log(uint p0, address p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); ignored; } function log(string memory p0, uint p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); ignored; } function log(string memory p0, uint p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); ignored; } function log(string memory p0, uint p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); ignored; } function log(string memory p0, uint p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); ignored; } function log(string memory p0, string memory p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); ignored; } function log(string memory p0, string memory p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); ignored; } function log(string memory p0, string memory p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); ignored; } function log(string memory p0, string memory p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); ignored; } function log(string memory p0, bool p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); ignored; } function log(string memory p0, bool p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); ignored; } function log(string memory p0, bool p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); ignored; } function log(string memory p0, bool p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); ignored; } function log(string memory p0, address p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); ignored; } function log(string memory p0, address p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); ignored; } function log(string memory p0, address p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); ignored; } function log(string memory p0, address p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); ignored; } function log(bool p0, uint p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); ignored; } function log(bool p0, uint p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); ignored; } function log(bool p0, uint p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); ignored; } function log(bool p0, uint p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); ignored; } function log(bool p0, string memory p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); ignored; } function log(bool p0, string memory p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); ignored; } function log(bool p0, string memory p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); ignored; } function log(bool p0, string memory p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); ignored; } function log(bool p0, bool p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); ignored; } function log(bool p0, bool p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); ignored; } function log(bool p0, bool p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); ignored; } function log(bool p0, bool p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); ignored; } function log(bool p0, address p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); ignored; } function log(bool p0, address p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); ignored; } function log(bool p0, address p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); ignored; } function log(bool p0, address p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); ignored; } function log(address p0, uint p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); ignored; } function log(address p0, uint p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); ignored; } function log(address p0, uint p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); ignored; } function log(address p0, uint p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); ignored; } function log(address p0, string memory p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); ignored; } function log(address p0, string memory p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); ignored; } function log(address p0, string memory p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); ignored; } function log(address p0, string memory p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); ignored; } function log(address p0, bool p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); ignored; } function log(address p0, bool p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); ignored; } function log(address p0, bool p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); ignored; } function log(address p0, bool p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); ignored; } function log(address p0, address p1, uint p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); ignored; } function log(address p0, address p1, string memory p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); ignored; } function log(address p0, address p1, bool p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); ignored; } function log(address p0, address p1, address p2) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); ignored; } function log(uint p0, uint p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, uint p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, string memory p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, bool p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); ignored; } function log(uint p0, address p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, uint p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, string memory p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, bool p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); ignored; } function log(string memory p0, address p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, uint p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, string memory p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, bool p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); ignored; } function log(bool p0, address p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, uint p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, string memory p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, bool p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, uint p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, uint p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, uint p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, uint p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, string memory p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, string memory p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, string memory p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, string memory p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, bool p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, bool p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, bool p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, bool p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, address p2, uint p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, address p2, string memory p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, address p2, bool p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); ignored; } function log(address p0, address p1, address p2, address p3) internal view { (bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); ignored; } } // File contracts/Dependencies/LiquityMath.sol // MIT pragma solidity 0.6.11; library LiquityMath { using SafeMath for uint; uint internal constant DECIMAL_PRECISION = 1e18; /* Precision for Nominal ICR (independent of price). Rationale for the value: * * - Making it “too high” could lead to overflows. * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division. * * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ETH, * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator. * */ uint internal constant NICR_PRECISION = 1e20; function _min(uint _a, uint _b) internal pure returns (uint) { return (_a < _b) ? _a : _b; } function _max(uint _a, uint _b) internal pure returns (uint) { return (_a >= _b) ? _a : _b; } /* * Multiply two decimal numbers and use normal rounding rules: * -round product up if 19'th mantissa digit >= 5 * -round product down if 19'th mantissa digit < 5 * * Used only inside the exponentiation, _decPow(). */ function decMul(uint x, uint y) internal pure returns (uint decProd) { uint prod_xy = x.mul(y); decProd = prod_xy.add(DECIMAL_PRECISION / 2).div(DECIMAL_PRECISION); } /* * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n. * * Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity. * * Called by two functions that represent time in units of minutes: * 1) TroveManager._calcDecayedBaseRate * 2) CommunityIssuance._getCumulativeIssuanceFraction * * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals * "minutes in 1000 years": 60 * 24 * 365 * 1000 * * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be * negligibly different from just passing the cap, since: * * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible */ function _decPow(uint _base, uint _minutes) internal pure returns (uint) { if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow if (_minutes == 0) {return DECIMAL_PRECISION;} uint y = DECIMAL_PRECISION; uint x = _base; uint n = _minutes; // Exponentiation-by-squaring while (n > 1) { if (n % 2 == 0) { x = decMul(x, x); n = n.div(2); } else { // if (n % 2 != 0) y = decMul(x, y); x = decMul(x, x); n = (n.sub(1)).div(2); } } return decMul(x, y); } function _getAbsoluteDifference(uint _a, uint _b) internal pure returns (uint) { return (_a >= _b) ? _a.sub(_b) : _b.sub(_a); } function _computeNominalCR(uint _coll, uint _debt) internal pure returns (uint) { if (_debt > 0) { return _coll.mul(NICR_PRECISION).div(_debt); } // Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR. else { // if (_debt == 0) return 2**256 - 1; } } function _computeCR(uint _coll, uint _debt, uint _price) internal pure returns (uint) { if (_debt > 0) { uint newCollRatio = _coll.mul(_price).div(_debt); return newCollRatio; } // Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR. else { // if (_debt == 0) return 2**256 - 1; } } } // File contracts/Interfaces/IPool.sol // MIT pragma solidity 0.6.11; // Common interface for the Pools. interface IPool { // --- Events --- event ETHBalanceUpdated(uint _newBalance); event LUSDBalanceUpdated(uint _newBalance); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event StabilityPoolAddressChanged(address _newStabilityPoolAddress); event EtherSent(address _to, uint _amount); // --- Functions --- function getETH() external view returns (uint); function getLUSDDebt() external view returns (uint); function increaseLUSDDebt(uint _amount) external; function decreaseLUSDDebt(uint _amount) external; } // File contracts/Interfaces/IActivePool.sol // MIT pragma solidity 0.6.11; interface IActivePool is IPool { // --- Events --- event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolLUSDDebtUpdated(uint _LUSDDebt); event ActivePoolETHBalanceUpdated(uint _ETH); // --- Functions --- function sendETH(address _account, uint _amount) external; } // File contracts/Interfaces/IDefaultPool.sol // MIT pragma solidity 0.6.11; interface IDefaultPool is IPool { // --- Events --- event TroveManagerAddressChanged(address _newTroveManagerAddress); event DefaultPoolLUSDDebtUpdated(uint _LUSDDebt); event DefaultPoolETHBalanceUpdated(uint _ETH); // --- Functions --- function sendETHToActivePool(uint _amount) external; } // File contracts/Dependencies/LiquityBase.sol // MIT pragma solidity 0.6.11; /* * Base contract for TroveManager, BorrowerOperations and StabilityPool. Contains global system constants and * common functions. */ contract LiquityBase is BaseMath, ILiquityBase { using SafeMath for uint; uint constant public _100pct = 1000000000000000000; // 1e18 == 100% // Minimum collateral ratio for individual troves uint constant public MCR = 1100000000000000000; // 110% // Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered. uint constant public CCR = 1500000000000000000; // 150% // Amount of LUSD to be locked in gas pool on opening troves uint constant public LUSD_GAS_COMPENSATION = 200e18; // Minimum amount of net LUSD debt a trove must have uint constant public MIN_NET_DEBT = 1800e18; // uint constant public MIN_NET_DEBT = 0; uint constant public PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5% uint constant public BORROWING_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5% IActivePool public activePool; IDefaultPool public defaultPool; IPriceFeed public override priceFeed; // --- Gas compensation functions --- // Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation function _getCompositeDebt(uint _debt) internal pure returns (uint) { return _debt.add(LUSD_GAS_COMPENSATION); } function _getNetDebt(uint _debt) internal pure returns (uint) { return _debt.sub(LUSD_GAS_COMPENSATION); } // Return the amount of ETH to be drawn from a trove's collateral and sent as gas compensation. function _getCollGasCompensation(uint _entireColl) internal pure returns (uint) { return _entireColl / PERCENT_DIVISOR; } function getEntireSystemColl() public view returns (uint entireSystemColl) { uint activeColl = activePool.getETH(); uint liquidatedColl = defaultPool.getETH(); return activeColl.add(liquidatedColl); } function getEntireSystemDebt() public view returns (uint entireSystemDebt) { uint activeDebt = activePool.getLUSDDebt(); uint closedDebt = defaultPool.getLUSDDebt(); return activeDebt.add(closedDebt); } function _getTCR(uint _price) internal view returns (uint TCR) { uint entireSystemColl = getEntireSystemColl(); uint entireSystemDebt = getEntireSystemDebt(); TCR = LiquityMath._computeCR(entireSystemColl, entireSystemDebt, _price); return TCR; } function _checkRecoveryMode(uint _price) internal view returns (bool) { uint TCR = _getTCR(_price); return TCR < CCR; } function _requireUserAcceptsFee(uint _fee, uint _amount, uint _maxFeePercentage) internal pure { uint feePercentage = _fee.mul(DECIMAL_PRECISION).div(_amount); require(feePercentage <= _maxFeePercentage, "Fee exceeded provided maximum"); } } // File contracts/Dependencies/LiquitySafeMath128.sol // MIT pragma solidity 0.6.11; // uint128 addition and subtraction, with overflow protection. library LiquitySafeMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "LiquitySafeMath128: addition overflow"); return c; } function sub(uint128 a, uint128 b) internal pure returns (uint128) { require(b <= a, "LiquitySafeMath128: subtraction overflow"); uint128 c = a - b; return c; } } // File contracts/Dependencies/Ownable.sol // MIT pragma solidity 0.6.11; /** * Based on OpenZeppelin's Ownable contract: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } 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 Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. * * NOTE: This function is not safe, as it doesn’t check owner is calling it. * Make sure you check it before calling it. */ function _renounceOwnership() internal { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } } // File contracts/Dependencies/CheckContract.sol // MIT pragma solidity 0.6.11; contract CheckContract { /** * Check that the account is an already deployed non-destroyed contract. * See: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L12 */ function checkContract(address _account) internal view { require(_account != address(0), "Account cannot be zero address"); uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(_account) } require(size > 0, "Account code size cannot be zero"); } } // File contracts/StabilityPool.sol // MIT pragma solidity 0.6.11; /* * The Stability Pool holds LUSD tokens deposited by Stability Pool depositors. * * When a trove is liquidated, then depending on system conditions, some of its LUSD debt gets offset with * LUSD in the Stability Pool: that is, the offset debt evaporates, and an equal amount of LUSD tokens in the Stability Pool is burned. * * Thus, a liquidation causes each depositor to receive a LUSD loss, in proportion to their deposit as a share of total deposits. * They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, * in the same proportion. * * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% * of the total LUSD in the Stability Pool, depletes 40% of each deposit. * * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit, * multiplying it by some factor in range ]0,1[ * * * --- IMPLEMENTATION --- * * We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity. * * When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables: * a product P, and a sum S. * * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits * and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively. * * The formula for a depositor's accumulated ETH gain is derived here: * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf * * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool, * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain. * * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S. * * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S. * Essentially, they make a fresh deposit that overwrites the old one. * * * --- SCALE FACTOR --- * * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[. * Unfortunately, Solidity floor division always reaches 0, sooner or later. * * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking. * * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity), * we first multiply P by 1e9, and increment a currentScale factor by 1. * * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the * order of 1e-9. * * --- EPOCHS --- * * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0 * forever, and break all future reward calculations. * * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1. * * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS --- * * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale. * * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer, * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0. * * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t. * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion LUSD has depleted to < 1 LUSD). * * * --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS --- * * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch. * * This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH. * * We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula: * e_1 = d_t * (S - S_t) / P_t * * and also for scale after, taking care to divide the latter by a factor of 1e9: * e_2 = d_t * S / (P_t * 1e9) * * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything. * The deposit therefore was present for reward events from the beginning of that second scale. * * S_i-S_t + S_{i+1} * .<--------.------------> * . . * . S_i . S_{i+1} * <--.-------->.<-----------> * S_t. . * <->. . * t . * |---+---------|-------------|-----... * i i+1 * * The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their * deposit spanned one scale change. We only care about gains across one scale change, since the compounded * deposit is defined as being 0 once it has spanned more than one scale change. * * * --- UPDATING P WHEN A LIQUIDATION OCCURS --- * * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf * * * --- LQTY ISSUANCE TO STABILITY POOL DEPOSITORS --- * * An LQTY issuance event occurs at every deposit operation, and every liquidation. * * Each deposit is tagged with the address of the front end through which it was made. * * All deposits earn a share of the issued LQTY in proportion to the deposit as a share of total deposits. The LQTY earned * by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. * * Please see the system Readme for an overview: * https://github.com/liquity/dev/blob/main/README.md#lqty-issuance-to-stability-providers * * We use the same mathematical product-sum approach to track LQTY gains for depositors, where 'G' is the sum corresponding to LQTY gains. * The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations. * */ contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool { using LiquitySafeMath128 for uint128; string constant public NAME = "StabilityPool"; IBorrowerOperations public borrowerOperations; ITroveManager public troveManager; ILUSDToken public lusdToken; // Needed to check if there are pending liquidations ISortedTroves public sortedTroves; ICommunityIssuance public communityIssuance; uint256 internal ETH; // deposited ether tracker // Tracker for LUSD held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. uint256 internal totalLUSDDeposits; // --- Data structures --- struct FrontEnd { uint kickbackRate; bool registered; } struct Deposit { uint initialValue; address frontEndTag; } struct Snapshots { uint S; uint P; uint G; uint128 scale; uint128 epoch; } mapping (address => Deposit) public deposits; // depositor address -> Deposit struct mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct /* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit, * after a series of liquidations have occurred, each of which cancel some LUSD debt with the deposit. * * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal. */ uint public P = DECIMAL_PRECISION; uint public constant SCALE_FACTOR = 1e9; // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1 uint128 public currentScale; // With each offset that fully empties the Pool, the epoch is incremented by 1 uint128 public currentEpoch; /* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t * is the depositor's snapshot of S taken at the time t when the deposit was made. * * The 'S' sums are stored in a nested mapping (epoch => scale => sum): * * - The inner mapping records the sum S at different scales * - The outer mapping records the (scale => sum) mappings, for different epochs. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum; /* * Similarly, the sum 'G' is used to calculate LQTY gains. During it's lifetime, each deposit d_t earns a LQTY gain of * ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made. * * LQTY reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations. * In each case, the LQTY reward is issued (i.e. G is updated), before other state changes are made. */ mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG; // Error tracker for the error correction in the LQTY issuance calculation uint public lastLQTYError; // Error trackers for the error correction in the offset calculation uint public lastETHError_Offset; uint public lastLUSDLossError_Offset; // --- Events --- event StabilityPoolETHBalanceUpdated(uint _newBalance); event StabilityPoolLUSDBalanceUpdated(uint _newBalance); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event TroveManagerAddressChanged(address _newTroveManagerAddress); event ActivePoolAddressChanged(address _newActivePoolAddress); event DefaultPoolAddressChanged(address _newDefaultPoolAddress); event LUSDTokenAddressChanged(address _newLUSDTokenAddress); event SortedTrovesAddressChanged(address _newSortedTrovesAddress); event PriceFeedAddressChanged(address _newPriceFeedAddress); event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); event P_Updated(uint _P); event S_Updated(uint _S, uint128 _epoch, uint128 _scale); event G_Updated(uint _G, uint128 _epoch, uint128 _scale); event EpochUpdated(uint128 _currentEpoch); event ScaleUpdated(uint128 _currentScale); event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate); event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd); event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G); event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G); event UserDepositChanged(address indexed _depositor, uint _newDeposit); event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor); event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _LUSDLoss); event LQTYPaidToDepositor(address indexed _depositor, uint _LQTY); event LQTYPaidToFrontEnd(address indexed _frontEnd, uint _LQTY); event EtherSent(address _to, uint _amount); // --- Contract setters --- function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _lusdTokenAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_lusdTokenAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); lusdToken = ILUSDToken(_lusdTokenAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit LUSDTokenAddressChanged(_lusdTokenAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- function getETH() external view override returns (uint) { return ETH; } function getTotalLUSDDeposits() external view override returns (uint) { return totalLUSDDeposits; } // --- External Depositor Functions --- /* provideToSP(): * * - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (LQTY, ETH) to depositor * - Sends the tagged front end's accumulated LQTY gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */ function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerLQTYIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender); uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log // First pay out any LQTY gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendLUSDtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedLUSDDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss); // LUSD Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawFromSP(): * * - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (LQTY, ETH) to depositor * - Sends the tagged front end's accumulated LQTY gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */ function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerLQTYIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender); uint LUSDtoWithdraw = LiquityMath._min(_amount, compoundedLUSDDeposit); uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log // First pay out any LQTY gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(LUSDtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendLUSDToDepositor(msg.sender, LUSDtoWithdraw); // Update deposit uint newDeposit = compoundedLUSDDeposit.sub(LUSDtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss); // LUSD Loss required for event log _sendETHGainToDepositor(depositorETHGain); } /* withdrawETHGainToTrove: * - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends * - Sends all depositor's LQTY gain to depositor * - Sends all tagged front end's LQTY gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */ function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerLQTYIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender); uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log // First pay out any LQTY gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedLUSDDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss); emit UserDepositChanged(msg.sender, compoundedLUSDDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); } // --- LQTY issuance functions --- function _triggerLQTYIssuance(ICommunityIssuance _communityIssuance) internal { uint LQTYIssuance = _communityIssuance.issueLQTY(); _updateG(LQTYIssuance); } function _updateG(uint _LQTYIssuance) internal { uint totalLUSD = totalLUSDDeposits; // cached to save an SLOAD /* * When total deposits is 0, G is not updated. In this case, the LQTY issued can not be obtained by later * depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract. * */ if (totalLUSD == 0 || _LQTYIssuance == 0) {return;} uint LQTYPerUnitStaked; LQTYPerUnitStaked =_computeLQTYPerUnitStaked(_LQTYIssuance, totalLUSD); uint marginalLQTYGain = LQTYPerUnitStaked.mul(P); epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalLQTYGain); emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale); } function _computeLQTYPerUnitStaked(uint _LQTYIssuance, uint _totalLUSDDeposits) internal returns (uint) { /* * Calculate the LQTY-per-unit staked. Division uses a "feedback" error correction, to keep the * cumulative error low in the running total G: * * 1) Form a numerator which compensates for the floor division error that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratio. * 3) Multiply the ratio back by its denominator, to reveal the current floor division error. * 4) Store this error for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint LQTYNumerator = _LQTYIssuance.mul(DECIMAL_PRECISION).add(lastLQTYError); uint LQTYPerUnitStaked = LQTYNumerator.div(_totalLUSDDeposits); lastLQTYError = LQTYNumerator.sub(LQTYPerUnitStaked.mul(_totalLUSDDeposits)); return LQTYPerUnitStaked; } // --- Liquidation functions --- /* * Cancels out the specified debt against the LUSD contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */ function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalLUSD = totalLUSDDeposits; // cached to save an SLOAD if (totalLUSD == 0 || _debtToOffset == 0) { return; } _triggerLQTYIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint LUSDLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalLUSD); _updateRewardSumAndProduct(ETHGainPerUnitStaked, LUSDLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); } // --- Offset helper functions --- function _computeRewardsPerUnitStaked( uint _collToAdd, uint _debtToOffset, uint _totalLUSDDeposits ) internal returns (uint ETHGainPerUnitStaked, uint LUSDLossPerUnitStaked) { /* * Compute the LUSD and ETH rewards. Uses a "feedback" error correction, to keep * the cumulative error in the P and S state variables low: * * 1) Form numerators which compensate for the floor division errors that occurred the last time this * function was called. * 2) Calculate "per-unit-staked" ratios. * 3) Multiply each ratio back by its denominator, to reveal the current floor division error. * 4) Store these errors for use in the next correction when this function is called. * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended. */ uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset); assert(_debtToOffset <= _totalLUSDDeposits); if (_debtToOffset == _totalLUSDDeposits) { LUSDLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit lastLUSDLossError_Offset = 0; } else { uint LUSDLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastLUSDLossError_Offset); /* * Add 1 to make error in quotient positive. We want "slightly too much" LUSD loss, * which ensures the error in any given compoundedLUSDDeposit favors the Stability Pool. */ LUSDLossPerUnitStaked = (LUSDLossNumerator.div(_totalLUSDDeposits)).add(1); lastLUSDLossError_Offset = (LUSDLossPerUnitStaked.mul(_totalLUSDDeposits)).sub(LUSDLossNumerator); } ETHGainPerUnitStaked = ETHNumerator.div(_totalLUSDDeposits); lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalLUSDDeposits)); return (ETHGainPerUnitStaked, LUSDLossPerUnitStaked); } // Update the Stability Pool reward sum S and product P function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _LUSDLossPerUnitStaked) internal { uint currentP = P; uint newP; assert(_LUSDLossPerUnitStaked <= DECIMAL_PRECISION); /* * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool LUSD in the liquidation. * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - LUSDLossPerUnitStaked) */ uint newProductFactor = uint(DECIMAL_PRECISION).sub(_LUSDLossPerUnitStaked); uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; /* * Calculate the new S first, before we update P. * The ETH gain for any given depositor from a liquidation depends on the value of their deposit * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation. * * Since S corresponds to ETH gain, and P to deposit loss, we update S first. */ uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP); uint newS = currentS.add(marginalETHGain); epochToScaleToSum[currentEpochCached][currentScaleCached] = newS; emit S_Updated(newS, currentEpochCached, currentScaleCached); // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P if (newProductFactor == 0) { currentEpoch = currentEpochCached.add(1); emit EpochUpdated(currentEpoch); currentScale = 0; emit ScaleUpdated(currentScale); newP = DECIMAL_PRECISION; // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale } else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) { newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION); currentScale = currentScaleCached.add(1); emit ScaleUpdated(currentScale); } else { newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION); } assert(newP > 0); P = newP; emit P_Updated(newP); } function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal { IActivePool activePoolCached = activePool; // Cancel the liquidated LUSD debt with the LUSD in the stability pool activePoolCached.decreaseLUSDDebt(_debtToOffset); _decreaseLUSD(_debtToOffset); // Burn the debt that was successfully offset lusdToken.burn(address(this), _debtToOffset); activePoolCached.sendETH(address(this), _collToAdd); } function _decreaseLUSD(uint _amount) internal { uint newTotalLUSDDeposits = totalLUSDDeposits.sub(_amount); totalLUSDDeposits = newTotalLUSDDeposits; emit StabilityPoolLUSDBalanceUpdated(newTotalLUSDDeposits); } // --- Reward calculator functions for depositor and front end --- /* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; } function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change. * If it does, the second portion of the ETH gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint S_Snapshot = snapshots.S; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot); uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return ETHGain; } /* * Calculate the LQTY gain earned by a deposit since its last snapshots were taken. * Given by the formula: LQTY = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */ function getDepositorLQTYGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint LQTYGain = kickbackRate.mul(_getLQTYGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return LQTYGain; } /* * Return the LQTY gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */ function getFrontEndLQTYGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint LQTYGain = frontEndShare.mul(_getLQTYGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return LQTYGain; } function _getLQTYGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) { /* * Grab the sum 'G' from the epoch at which the stake was made. The LQTY gain may span up to one scale change. * If it does, the second portion of the LQTY gain is scaled by 1e9. * If the gain spans no scale change, the second portion will be 0. */ uint128 epochSnapshot = snapshots.epoch; uint128 scaleSnapshot = snapshots.scale; uint G_Snapshot = snapshots.G; uint P_Snapshot = snapshots.P; uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot); uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR); uint LQTYGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION); return LQTYGain; } // --- Compounded deposit and compounded front end stake --- /* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */ function getCompoundedLUSDDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; } /* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */ function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; } // Internal function, used to calculcate compounded deposits and compounded front end stakes. function _getCompoundedStakeFromSnapshots( uint initialStake, Snapshots memory snapshots ) internal view returns (uint) { uint snapshot_P = snapshots.P; uint128 scaleSnapshot = snapshots.scale; uint128 epochSnapshot = snapshots.epoch; // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0 if (epochSnapshot < currentEpoch) { return 0; } uint compoundedStake; uint128 scaleDiff = currentScale.sub(scaleSnapshot); /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime, * account for it. If more than one scale change was made, then the stake has decreased by a factor of * at least 1e-9 -- so return 0. */ if (scaleDiff == 0) { compoundedStake = initialStake.mul(P).div(snapshot_P); } else if (scaleDiff == 1) { compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR); } else { // if scaleDiff >= 2 compoundedStake = 0; } /* * If compounded deposit is less than a billionth of the initial deposit, return 0. * * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less * than it's theoretical value. * * Thus it's unclear whether this line is still really needed. */ if (compoundedStake < initialStake.div(1e9)) {return 0;} return compoundedStake; } // --- Sender functions for LUSD deposit, ETH gains and LQTY gains --- // Transfer the LUSD tokens from the user to the Stability Pool's address, and update its recorded LUSD function _sendLUSDtoStabilityPool(address _address, uint _amount) internal { lusdToken.sendToPool(_address, address(this), _amount); uint newTotalLUSDDeposits = totalLUSDDeposits.add(_amount); totalLUSDDeposits = newTotalLUSDDeposits; emit StabilityPoolLUSDBalanceUpdated(newTotalLUSDDeposits); } function _sendETHGainToDepositor(uint _amount) internal { if (_amount == 0) {return;} uint newETH = ETH.sub(_amount); ETH = newETH; emit StabilityPoolETHBalanceUpdated(newETH); emit EtherSent(msg.sender, _amount); (bool success, ) = msg.sender.call{ value: _amount }(""); require(success, "StabilityPool: sending ETH failed"); } // Send LUSD to user and decrease LUSD in Pool function _sendLUSDToDepositor(address _depositor, uint LUSDWithdrawal) internal { if (LUSDWithdrawal == 0) {return;} lusdToken.returnFromPool(address(this), _depositor, LUSDWithdrawal); _decreaseLUSD(LUSDWithdrawal); } // --- External Front End functions --- // Front end makes a one-time selection of kickback rate upon registering function registerFrontEnd(uint _kickbackRate) external override { _requireFrontEndNotRegistered(msg.sender); _requireUserHasNoDeposit(msg.sender); _requireValidKickbackRate(_kickbackRate); frontEnds[msg.sender].kickbackRate = _kickbackRate; frontEnds[msg.sender].registered = true; emit FrontEndRegistered(msg.sender, _kickbackRate); } // --- Stability Pool Deposit Functionality --- function _setFrontEndTag(address _depositor, address _frontEndTag) internal { deposits[_depositor].frontEndTag = _frontEndTag; emit FrontEndTagSet(_depositor, _frontEndTag); } function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal { deposits[_depositor].initialValue = _newValue; if (_newValue == 0) { delete deposits[_depositor].frontEndTag; delete depositSnapshots[_depositor]; emit DepositSnapshotUpdated(_depositor, 0, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get S and G for the current epoch and current scale uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached]; uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor depositSnapshots[_depositor].P = currentP; depositSnapshots[_depositor].S = currentS; depositSnapshots[_depositor].G = currentG; depositSnapshots[_depositor].scale = currentScaleCached; depositSnapshots[_depositor].epoch = currentEpochCached; emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG); } function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal { frontEndStakes[_frontEnd] = _newValue; if (_newValue == 0) { delete frontEndSnapshots[_frontEnd]; emit FrontEndSnapshotUpdated(_frontEnd, 0, 0); return; } uint128 currentScaleCached = currentScale; uint128 currentEpochCached = currentEpoch; uint currentP = P; // Get G for the current epoch and current scale uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached]; // Record new snapshots of the latest running product P and sum G for the front end frontEndSnapshots[_frontEnd].P = currentP; frontEndSnapshots[_frontEnd].G = currentG; frontEndSnapshots[_frontEnd].scale = currentScaleCached; frontEndSnapshots[_frontEnd].epoch = currentEpochCached; emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG); } function _payOutLQTYGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal { // Pay out front end's LQTY gain if (_frontEnd != address(0)) { uint frontEndLQTYGain = getFrontEndLQTYGain(_frontEnd); _communityIssuance.sendLQTY(_frontEnd, frontEndLQTYGain); emit LQTYPaidToFrontEnd(_frontEnd, frontEndLQTYGain); } // Pay out depositor's LQTY gain uint depositorLQTYGain = getDepositorLQTYGain(_depositor); _communityIssuance.sendLQTY(_depositor, depositorLQTYGain); emit LQTYPaidToDepositor(_depositor, depositorLQTYGain); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager"); } function _requireNoUnderCollateralizedTroves() internal { uint price = priceFeed.fetchPrice(); address lowestTrove = sortedTroves.getLast(); uint ICR = troveManager.getCurrentICR(lowestTrove, price); require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR"); } function _requireUserHasDeposit(uint _initialDeposit) internal pure { require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit'); } function _requireUserHasNoDeposit(address _address) internal view { uint initialDeposit = deposits[_address].initialValue; require(initialDeposit == 0, 'StabilityPool: User must have no deposit'); } function _requireNonZeroAmount(uint _amount) internal pure { require(_amount > 0, 'StabilityPool: Amount must be non-zero'); } function _requireUserHasTrove(address _depositor) internal view { require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to"); } function _requireUserHasETHGain(address _depositor) internal view { uint ETHGain = getDepositorETHGain(_depositor); require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain"); } function _requireFrontEndNotRegistered(address _address) internal view { require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end"); } function _requireFrontEndIsRegisteredOrZero(address _address) internal view { require(frontEnds[_address].registered || _address == address(0), "StabilityPool: Tag must be a registered front end, or the zero address"); } function _requireValidKickbackRate(uint _kickbackRate) internal pure { require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); ETH = ETH.add(msg.value); StabilityPoolETHBalanceUpdated(ETH); } } // File contracts/B.Protocol/crop.sol // AGPL-3.0-or-later // Copyright (C) 2021 Dai Foundation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.11; interface VatLike { function urns(bytes32, address) external view returns (uint256, uint256); function gem(bytes32, address) external view returns (uint256); function slip(bytes32, address, int256) external; } interface ERC20 { function balanceOf(address owner) external view returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom(address src, address dst, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function decimals() external returns (uint8); } // receives tokens and shares them among holders contract CropJoin { VatLike public immutable vat; // cdp engine bytes32 public immutable ilk; // collateral type ERC20 public immutable gem; // collateral token uint256 public immutable dec; // gem decimals ERC20 public immutable bonus; // rewards token uint256 public share; // crops per gem [ray] uint256 public total; // total gems [wad] uint256 public stock; // crop balance [wad] mapping (address => uint256) public crops; // crops per user [wad] mapping (address => uint256) public stake; // gems per user [wad] uint256 immutable internal to18ConversionFactor; uint256 immutable internal toGemConversionFactor; // --- Events --- event Join(uint256 val); event Exit(uint256 val); event Flee(); event Tack(address indexed src, address indexed dst, uint256 wad); constructor(address vat_, bytes32 ilk_, address gem_, address bonus_) public { vat = VatLike(vat_); ilk = ilk_; gem = ERC20(gem_); uint256 dec_ = ERC20(gem_).decimals(); require(dec_ <= 18); dec = dec_; to18ConversionFactor = 10 ** (18 - dec_); toGemConversionFactor = 10 ** dec_; bonus = ERC20(bonus_); } function add(uint256 x, uint256 y) public pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) public pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) public pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(x, sub(y, 1)) / y; } uint256 constant WAD = 10 ** 18; function wmul(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, y) / WAD; } function wdiv(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, WAD) / y; } function wdivup(uint256 x, uint256 y) public pure returns (uint256 z) { z = divup(mul(x, WAD), y); } uint256 constant RAY = 10 ** 27; function rmul(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, y) / RAY; } function rmulup(uint256 x, uint256 y) public pure returns (uint256 z) { z = divup(mul(x, y), RAY); } function rdiv(uint256 x, uint256 y) public pure returns (uint256 z) { z = mul(x, RAY) / y; } // Net Asset Valuation [wad] function nav() public virtual returns (uint256) { uint256 _nav = gem.balanceOf(address(this)); return mul(_nav, to18ConversionFactor); } // Net Assets per Share [wad] function nps() public returns (uint256) { if (total == 0) return WAD; else return wdiv(nav(), total); } function crop() internal virtual returns (uint256) { return sub(bonus.balanceOf(address(this)), stock); } function harvest(address from, address to) internal { if (total > 0) share = add(share, rdiv(crop(), total)); uint256 last = crops[from]; uint256 curr = rmul(stake[from], share); if (curr > last) require(bonus.transfer(to, curr - last)); stock = bonus.balanceOf(address(this)); } function join(address urn, uint256 val) internal virtual { harvest(urn, urn); if (val > 0) { uint256 wad = wdiv(mul(val, to18ConversionFactor), nps()); // Overflow check for int256(wad) cast below // Also enforces a non-zero wad require(int256(wad) > 0); require(gem.transferFrom(msg.sender, address(this), val)); vat.slip(ilk, urn, int256(wad)); total = add(total, wad); stake[urn] = add(stake[urn], wad); } crops[urn] = rmulup(stake[urn], share); emit Join(val); } function exit(address guy, uint256 val) internal virtual { harvest(msg.sender, guy); if (val > 0) { uint256 wad = wdivup(mul(val, to18ConversionFactor), nps()); // Overflow check for int256(wad) cast below // Also enforces a non-zero wad require(int256(wad) > 0); require(gem.transfer(guy, val)); vat.slip(ilk, msg.sender, -int256(wad)); total = sub(total, wad); stake[msg.sender] = sub(stake[msg.sender], wad); } crops[msg.sender] = rmulup(stake[msg.sender], share); emit Exit(val); } } // File contracts/B.Protocol/CropJoinAdapter.sol // MIT pragma solidity 0.6.11; // NOTE! - this is not an ERC20 token. transfer is not supported. contract CropJoinAdapter is CropJoin { string constant public name = "B.AMM LUSD-ETH"; string constant public symbol = "LUSDETH"; uint constant public decimals = 18; event Transfer(address indexed _from, address indexed _to, uint256 _value); constructor(address _lqty) public CropJoin(address(new Dummy()), "B.AMM", address(new DummyGem()), _lqty) { } // adapter to cropjoin function nav() public override returns (uint256) { return total; } function totalSupply() public view returns (uint256) { return total; } function balanceOf(address owner) public view returns (uint256 balance) { balance = stake[owner]; } function mint(address to, uint value) virtual internal { join(to, value); emit Transfer(address(0), to, value); } function burn(address owner, uint value) virtual internal { exit(owner, value); emit Transfer(owner, address(0), value); } } contract Dummy { fallback() external {} } contract DummyGem is Dummy { function transfer(address, uint) external pure returns(bool) { return true; } function transferFrom(address, address, uint) external pure returns(bool) { return true; } function decimals() external pure returns(uint) { return 18; } } // File contracts/B.Protocol/PriceFormula.sol // MIT pragma solidity 0.6.11; contract PriceFormula { using SafeMath for uint256; function getSumFixedPoint(uint x, uint y, uint A) public pure returns(uint) { if(x == 0 && y == 0) return 0; uint sum = x.add(y); for(uint i = 0 ; i < 255 ; i++) { uint dP = sum; dP = dP.mul(sum) / (x.mul(2)).add(1); dP = dP.mul(sum) / (y.mul(2)).add(1); uint prevSum = sum; uint n = (A.mul(2).mul(x.add(y)).add(dP.mul(2))).mul(sum); uint d = (A.mul(2).sub(1).mul(sum)); sum = n / d.add(dP.mul(3)); if(sum <= prevSum.add(1) && prevSum <= sum.add(1)) break; } return sum; } function getReturn(uint xQty, uint xBalance, uint yBalance, uint A) public pure returns(uint) { uint sum = getSumFixedPoint(xBalance, yBalance, A); uint c = sum.mul(sum) / (xQty.add(xBalance)).mul(2); c = c.mul(sum) / A.mul(4); uint b = (xQty.add(xBalance)).add(sum / A.mul(2)); uint yPrev = 0; uint y = sum; for(uint i = 0 ; i < 255 ; i++) { yPrev = y; uint n = (y.mul(y)).add(c); uint d = y.mul(2).add(b).sub(sum); y = n / d; if(y <= yPrev.add(1) && yPrev <= y.add(1)) break; } return yBalance.sub(y).sub(1); } } // File contracts/Dependencies/AggregatorV3Interface.sol // MIT // Code from https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol pragma solidity 0.6.11; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File contracts/B.Protocol/BAMM.sol // MIT pragma solidity 0.6.11; contract BAMM is CropJoinAdapter, PriceFormula, Ownable { using SafeMath for uint256; AggregatorV3Interface public immutable priceAggregator; AggregatorV3Interface public immutable lusd2UsdPriceAggregator; IERC20 public immutable LUSD; StabilityPool immutable public SP; address payable public immutable feePool; uint public constant MAX_FEE = 100; // 1% uint public fee = 0; // fee in bps uint public A = 20; uint public constant MIN_A = 20; uint public constant MAX_A = 200; uint public immutable maxDiscount; // max discount in bips address public immutable frontEndTag; uint constant public PRECISION = 1e18; event ParamsSet(uint A, uint fee); event UserDeposit(address indexed user, uint lusdAmount, uint numShares); event UserWithdraw(address indexed user, uint lusdAmount, uint ethAmount, uint numShares); event RebalanceSwap(address indexed user, uint lusdAmount, uint ethAmount, uint timestamp); constructor( address _priceAggregator, address _lusd2UsdPriceAggregator, address payable _SP, address _LUSD, address _LQTY, uint _maxDiscount, address payable _feePool, address _fronEndTag) public CropJoinAdapter(_LQTY) { priceAggregator = AggregatorV3Interface(_priceAggregator); lusd2UsdPriceAggregator = AggregatorV3Interface(_lusd2UsdPriceAggregator); LUSD = IERC20(_LUSD); SP = StabilityPool(_SP); feePool = _feePool; maxDiscount = _maxDiscount; frontEndTag = _fronEndTag; } function setParams(uint _A, uint _fee) external onlyOwner { require(_fee <= MAX_FEE, "setParams: fee is too big"); require(_A >= MIN_A, "setParams: A too small"); require(_A <= MAX_A, "setParams: A too big"); fee = _fee; A = _A; emit ParamsSet(_A, _fee); } function fetchPrice() public view returns(uint) { uint chainlinkDecimals; uint chainlinkLatestAnswer; uint chainlinkTimestamp; // First, try to get current decimal precision: try priceAggregator.decimals() returns (uint8 decimals) { // If call to Chainlink succeeds, record the current decimal precision chainlinkDecimals = decimals; } catch { // If call to Chainlink aggregator reverts, return a zero response with success = false return 0; } // Secondly, try to get latest price data: try priceAggregator.latestRoundData() returns ( uint80 /* roundId */, int256 answer, uint256 /* startedAt */, uint256 timestamp, uint80 /* answeredInRound */ ) { // If call to Chainlink succeeds, return the response and success = true chainlinkLatestAnswer = uint(answer); chainlinkTimestamp = timestamp; } catch { // If call to Chainlink aggregator reverts, return a zero response with success = false return 0; } if(chainlinkTimestamp + 1 hours < now) return 0; // price is down uint chainlinkFactor = 10 ** chainlinkDecimals; return chainlinkLatestAnswer.mul(PRECISION) / chainlinkFactor; } function deposit(uint lusdAmount) external { // update share uint lusdValue = SP.getCompoundedLUSDDeposit(address(this)); uint ethValue = SP.getDepositorETHGain(address(this)).add(address(this).balance); uint price = fetchPrice(); require(ethValue == 0 || price > 0, "deposit: chainlink is down"); uint totalValue = lusdValue.add(ethValue.mul(price) / PRECISION); // this is in theory not reachable. if it is, better halt deposits // the condition is equivalent to: (totalValue = 0) ==> (total = 0) require(totalValue > 0 || total == 0, "deposit: system is rekt"); uint newShare = PRECISION; if(total > 0) newShare = total.mul(lusdAmount) / totalValue; // deposit require(LUSD.transferFrom(msg.sender, address(this), lusdAmount), "deposit: transferFrom failed"); SP.provideToSP(lusdAmount, frontEndTag); // update LP token mint(msg.sender, newShare); emit UserDeposit(msg.sender, lusdAmount, newShare); } function withdraw(uint numShares) external { uint lusdValue = SP.getCompoundedLUSDDeposit(address(this)); uint ethValue = SP.getDepositorETHGain(address(this)).add(address(this).balance); uint lusdAmount = lusdValue.mul(numShares).div(total); uint ethAmount = ethValue.mul(numShares).div(total); // this withdraws lusd, lqty, and eth SP.withdrawFromSP(lusdAmount); // update LP token burn(msg.sender, numShares); // send lusd and eth if(lusdAmount > 0) LUSD.transfer(msg.sender, lusdAmount); if(ethAmount > 0) { (bool success, ) = msg.sender.call{ value: ethAmount }(""); // re-entry is fine here require(success, "withdraw: sending ETH failed"); } emit UserWithdraw(msg.sender, lusdAmount, ethAmount, numShares); } function addBps(uint n, int bps) internal pure returns(uint) { require(bps <= 10000, "reduceBps: bps exceeds max"); require(bps >= -10000, "reduceBps: bps exceeds min"); return n.mul(uint(10000 + bps)) / 10000; } function compensateForLusdDeviation(uint ethAmount) public view returns(uint newEthAmount) { uint chainlinkDecimals; uint chainlinkLatestAnswer; // get current decimal precision: chainlinkDecimals = lusd2UsdPriceAggregator.decimals(); // Secondly, try to get latest price data: (,int256 answer,,,) = lusd2UsdPriceAggregator.latestRoundData(); chainlinkLatestAnswer = uint(answer); // adjust only if 1 LUSD > 1 USDC. If LUSD < USD, then we give a discount, and rebalance will happen anw if(chainlinkLatestAnswer > 10 ** chainlinkDecimals ) { newEthAmount = ethAmount.mul(chainlinkLatestAnswer) / (10 ** chainlinkDecimals); } else newEthAmount = ethAmount; } function getSwapEthAmount(uint lusdQty) public view returns(uint ethAmount, uint feeLusdAmount) { uint lusdBalance = SP.getCompoundedLUSDDeposit(address(this)); uint ethBalance = SP.getDepositorETHGain(address(this)).add(address(this).balance); uint eth2usdPrice = fetchPrice(); if(eth2usdPrice == 0) return (0, 0); // chainlink is down uint ethUsdValue = ethBalance.mul(eth2usdPrice) / PRECISION; uint maxReturn = addBps(lusdQty.mul(PRECISION) / eth2usdPrice, int(maxDiscount)); uint xQty = lusdQty; uint xBalance = lusdBalance; uint yBalance = lusdBalance.add(ethUsdValue.mul(2)); uint usdReturn = getReturn(xQty, xBalance, yBalance, A); uint basicEthReturn = usdReturn.mul(PRECISION) / eth2usdPrice; basicEthReturn = compensateForLusdDeviation(basicEthReturn); if(ethBalance < basicEthReturn) basicEthReturn = ethBalance; // cannot give more than balance if(maxReturn < basicEthReturn) basicEthReturn = maxReturn; ethAmount = basicEthReturn; feeLusdAmount = addBps(lusdQty, int(fee)).sub(lusdQty); } // get ETH in return to LUSD function swap(uint lusdAmount, uint minEthReturn, address payable dest) public returns(uint) { (uint ethAmount, uint feeAmount) = getSwapEthAmount(lusdAmount); require(ethAmount >= minEthReturn, "swap: low return"); LUSD.transferFrom(msg.sender, address(this), lusdAmount); SP.provideToSP(lusdAmount.sub(feeAmount), frontEndTag); if(feeAmount > 0) LUSD.transfer(feePool, feeAmount); (bool success, ) = dest.call{ value: ethAmount }(""); // re-entry is fine here require(success, "swap: sending ETH failed"); emit RebalanceSwap(msg.sender, lusdAmount, ethAmount, now); return ethAmount; } // kyber network reserve compatible function function trade( IERC20 /* srcToken */, uint256 srcAmount, IERC20 /* destToken */, address payable destAddress, uint256 /* conversionRate */, bool /* validate */ ) external payable returns (bool) { return swap(srcAmount, 0, destAddress) > 0; } function getConversionRate( IERC20 /* src */, IERC20 /* dest */, uint256 srcQty, uint256 /* blockNumber */ ) external view returns (uint256) { (uint ethQty, ) = getSwapEthAmount(srcQty); return ethQty.mul(PRECISION) / srcQty; } receive() external payable {} } // File @openzeppelin/contracts/utils/EnumerableSet.sol@v3.4.2 // MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File contracts/B.Protocol/KeeperRebate.sol // MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; interface FeePoolVaultLike { function op(address target, bytes calldata data, uint value) external; function transferOwnership(address newOwner) external; } contract KeeperRebate is Ownable { using EnumerableSet for EnumerableSet.AddressSet; address immutable public feePool; BAMM immutable public bamm; IERC20 immutable public lusd; IERC20 constant public ETH = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); EnumerableSet.AddressSet keepers; address public keeperLister; struct TokensData { IERC20 inToken; IERC20[] outTokens; IERC20[] rebateTokens; } event SwapSummary(address indexed keeper, IERC20 tokenIn, uint inAmount, IERC20 tokenOut, uint outAmount, uint rebateAmount); event NewLister(address lister); event KeeperListing(address keeper, bool list); constructor(BAMM _bamm) public { bamm = _bamm; lusd = _bamm.LUSD(); feePool = _bamm.feePool(); IERC20(_bamm.LUSD()).approve(address(_bamm), uint(-1)); } function getReturnedSwapAmount(IERC20 tokenIn, uint inAmount, IERC20 tokenOut) public view returns(uint outAmount, IERC20 rebateToken, uint rebateAmount) { if(tokenIn == lusd && tokenOut == ETH) { (outAmount, rebateAmount) = bamm.getSwapEthAmount(inAmount); } rebateToken = lusd; } function swap(IERC20 tokenIn, uint inAmount, IERC20 tokenOut, uint minOutAmount, uint maxRebate, address payable dest) public payable returns(uint outAmount, uint rebateAmount) { require(tokenIn == lusd, "swap: invalid tokenIn"); require(tokenOut == ETH, "swap: invalid tokenOut"); (outAmount, rebateAmount) = swapWithRebate(inAmount, minOutAmount, maxRebate, dest); emit SwapSummary(msg.sender, tokenIn, inAmount, tokenOut, outAmount, rebateAmount); } function getTokens() public view returns(TokensData[] memory tokens) { tokens = new TokensData[](1); tokens[0].inToken = lusd; tokens[0].outTokens = new IERC20[](1); tokens[0].rebateTokens = new IERC20[](1); tokens[0].outTokens[0] = ETH; tokens[0].rebateTokens[0] = lusd; } function transferFeePoolOwnership(address newOwner) public onlyOwner { FeePoolVaultLike(feePool).transferOwnership(newOwner); } function setKeeperLister(address lister) public onlyOwner { keeperLister = lister; emit NewLister(lister); } function listKeeper(address keeper, bool list) public { require(msg.sender == keeperLister, "listKeeper: !lister"); if(list) require(keepers.add(keeper), "listKeeper: keepers.add failed"); else require(keepers.remove(keeper), "listKeeper: keepers.remove failed"); KeeperListing(keeper, list); } function swapWithRebate(uint lusdAmount, uint minEthReturn, uint maxLusdRebate, address payable dest) internal returns(uint ethAmount, uint lusdRebate) { require(keepers.contains(msg.sender), "swapWithRebate: !keeper"); lusd.transferFrom(msg.sender, address(this), lusdAmount); uint feeBps = bamm.fee(); // if lusd amount is 0 it will revert, but this is fine require(feeBps * lusdAmount / lusdAmount == feeBps, "swapWithRebate: overflow"); lusdRebate = feeBps * lusdAmount / 10000; // adjust rebate to max fee if(lusdRebate > maxLusdRebate) lusdRebate = maxLusdRebate; ethAmount = bamm.swap(lusdAmount, minEthReturn, dest); rebate(dest, lusdRebate); } function rebate(address payable dest, uint amount) internal { bytes memory data = abi.encodeWithSignature("transfer(address,uint256)", dest, amount); FeePoolVaultLike(feePool).op(address(lusd), data, 0); } }
If compounded deposit is less than a billionth of the initial deposit, return 0. NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less than it's theoretical value. Thus it's unclear whether this line is still really needed./
if (compoundedStake < initialStake.div(1e9)) {return 0;}
504,004
[ 1, 2047, 1161, 12002, 443, 1724, 353, 5242, 2353, 279, 20714, 285, 451, 434, 326, 2172, 443, 1724, 16, 327, 374, 18, 5219, 30, 24000, 16, 333, 980, 1703, 316, 3166, 358, 2132, 13885, 1334, 10480, 326, 443, 1724, 4885, 7876, 18, 10724, 16, 326, 555, 15104, 87, 1410, 3387, 326, 555, 316, 453, 315, 19731, 1383, 326, 8828, 3113, 277, 18, 73, 18, 1281, 864, 1161, 12002, 443, 1724, 1410, 21980, 5242, 2353, 518, 1807, 326, 479, 88, 1706, 460, 18, 22073, 518, 1807, 6301, 298, 297, 2856, 333, 980, 353, 4859, 8654, 3577, 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, 3639, 309, 261, 2919, 12002, 510, 911, 411, 2172, 510, 911, 18, 2892, 12, 21, 73, 29, 3719, 288, 2463, 374, 31, 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 ]
./full_match/1/0x0c6dFD9B2f0bB08e52BCc0C20fE4c4957Fb58f3E/sources/project_/contracts/DioneStaking.sol
@notice Internal Function - Adding new Penalty tier @param _validUntil Penalty tier valid length (will be calculated from user staking start timestamp) @param _percent Penalty percent for new penalty tier
function _addPenaltyTier(uint256 _validUntil, uint256 _percent) internal { tiers.push(PenaltyTiers(_validUntil, _percent)); emit PenaltyTierAdded(_validUntil, _percent); }
4,872,845
[ 1, 3061, 4284, 300, 21240, 394, 453, 275, 15006, 17742, 225, 389, 877, 9716, 453, 275, 15006, 17742, 923, 769, 261, 20194, 506, 8894, 628, 729, 384, 6159, 787, 2858, 13, 225, 389, 8849, 453, 275, 15006, 5551, 364, 394, 23862, 17742, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1289, 24251, 15006, 15671, 12, 11890, 5034, 389, 877, 9716, 16, 2254, 5034, 389, 8849, 13, 2713, 288, 203, 3639, 11374, 414, 18, 6206, 12, 24251, 15006, 56, 20778, 24899, 877, 9716, 16, 389, 8849, 10019, 203, 203, 3639, 3626, 453, 275, 15006, 15671, 8602, 24899, 877, 9716, 16, 389, 8849, 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 ]
// SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.9; /** * @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 pragma solidity ^0.8.9; /** * @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 pragma solidity ^0.8.9; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.9; /** * @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 pragma solidity ^0.8.9; /** * @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 pragma solidity ^0.8.9; /** * @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 pragma solidity ^0.8.9; /** * @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 pragma solidity ^0.8.9; /** * @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 pragma solidity ^0.8.9; /** * @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); } pragma solidity >=0.8.9; // to enable certain compiler features 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; //Mapping para atribuirle un URI para cada token mapping(uint256 => string) internal id_to_URI; /** * @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) { } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } pragma solidity ^0.8.9; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity ^0.8.9; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // Creator: Chiru Labs pragma solidity ^0.8.9; /** * @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). * * Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply */ 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 internal currentIndex; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual 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; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.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); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); unchecked { for (uint256 curr = tokenId; curr >= 0; 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 virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public 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 Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); require(quantity != 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1 unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { 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); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = 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); } /** * @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 {} } // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) contract PharaGods is ERC721A, Ownable { using Strings for uint256; //declares the maximum amount of tokens that can be minted, total and in presale uint256 private maxTotalTokens; //initial part of the URI for the metadata string private _currentBaseURI; //cost of mints depending on state of sale uint private mintCostPresale = 1 ether; uint private mintCostPublicSale = 1 ether; //maximum amount of mints allowed per person uint256 public maxMintPresale = 100; uint256 public maxMintPublicSale = 100; //the amount of reserved mints that have currently been executed by creator and giveaways uint private _reservedMints; //the maximum amount of reserved mints allowed for creator and giveaways uint private maxReservedMints = 33; //dummy address that we use to sign the mint transaction to make sure it is valid address private dummy = 0x80E4929c869102140E69550BBECC20bEd61B080c; //marks the timestamp of when the respective sales open uint256 internal presaleLaunchTime; uint256 internal publicSaleLaunchTime; uint256 internal revealTime; //dictates if sale is paused or not bool private paused_; //amount of mints that each address has executed mapping(address => uint256) public mintsPerAddress; //current state os sale enum State {NoSale, Presale, PublicSale} //defines the uri for when the NFTs have not been yet revealed string public unrevealedURI; //stores the amount of nfts that have recieved there payout uint public amountOfTokensGotPayout; //declaring initial values for variables constructor() ERC721A('PharaGods', 'PG') { maxTotalTokens = 3333; //unrevealedURI = "ipfs://.../"; _currentBaseURI = "ipfs://QmcanEc6XwfaAmASeJbfaWrZskg2nFEXYKvRAuhhn6u6AX/"; //minting 2 legendaries for the opensea sale reservedMint(2, msg.sender); mintsPerAddress[msg.sender] += 2; _reservedMints += 2; } //in case somebody accidentaly sends funds or transaction to contract receive() payable external {} fallback() payable external { revert(); } //visualize baseURI function _baseURI() internal view virtual override returns (string memory) { return _currentBaseURI; } //change baseURI in case needed for IPFS function changeBaseURI(string memory baseURI_) public onlyOwner { _currentBaseURI = baseURI_; } function changeUnrevealedURI(string memory unrevealedURI_) public onlyOwner { unrevealedURI = unrevealedURI_; } function switchToPresale() public onlyOwner { require(saleState() == State.NoSale, 'Sale is already Open!'); presaleLaunchTime = block.timestamp; } function switchToPublicSale() public onlyOwner { require(saleState() == State.Presale, 'Sale must be in Presale!'); publicSaleLaunchTime = block.timestamp; } modifier onlyValidAccess(uint8 _v, bytes32 _r, bytes32 _s) { require( isValidAccessMessage(msg.sender,_v,_r,_s), 'Invalid Signature' ); _; } /* * @dev Verifies if message was signed by owner to give access to _add for this contract. * Assumes Geth signature prefix. * @param _add Address of agent with access * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @return Validity of access message for a given address. */ function isValidAccessMessage(address _add, uint8 _v, bytes32 _r, bytes32 _s) view public returns (bool) { bytes32 hash = keccak256(abi.encodePacked(address(this), _add)); return dummy == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), _v, _r, _s); } //mint a @param number of NFTs in presale function presaleMint(uint256 number, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable { require(!paused_, "Sale is paused!"); State saleState_ = saleState(); require(saleState_ != State.NoSale, "Sale in not open yet!"); require(saleState_ != State.PublicSale, "Presale has closed, Check out Public Sale!"); require(totalSupply() + number <= maxTotalTokens - (maxReservedMints - _reservedMints), "Not enough NFTs left to mint.."); require(mintsPerAddress[msg.sender] + number <= maxMintPresale, "Maximum Mints per Address exceeded!"); require(msg.value >= mintCost() * number, "Not sufficient Ether to mint this amount of NFTs"); _safeMint(msg.sender, number); mintsPerAddress[msg.sender] += number; } //mint a @param number of NFTs in public sale function publicSaleMint(uint256 number) public payable { require(!paused_, "Sale is paused!"); State saleState_ = saleState(); require(saleState_ == State.PublicSale, "Public Sale in not open yet!"); require(totalSupply() + number <= maxTotalTokens - (maxReservedMints - _reservedMints), "Not enough NFTs left to mint.."); require(mintsPerAddress[msg.sender] + number <= maxMintPublicSale, "Maximum Mints per Address exceeded!"); require(msg.value >= mintCost() * number, "Not sufficient Ether to mint this amount of NFTs"); _safeMint(msg.sender, number); mintsPerAddress[msg.sender] += number; } function tokenURI(uint256 tokenId_) public view virtual override returns (string memory) { require(_exists(tokenId_), "ERC721Metadata: URI query for nonexistent token"); //check to see that 24 hours have passed since beginning of publicsale launch if (revealTime == 0 && tokenId_ > 1) { return unrevealedURI; } else { string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId_.toString(), '.json')) : ""; } } //reserved NFTs for creator function reservedMint(uint number, address recipient) public onlyOwner { require(_reservedMints + number <= maxReservedMints, "Not enough Reserved NFTs left to mint.."); _safeMint(recipient, number); mintsPerAddress[recipient] += number; _reservedMints += number; } //burn the tokens that have not been sold yet function burnTokens() public onlyOwner { maxTotalTokens = totalSupply(); } //se the current account balance function accountBalance() public onlyOwner view returns(uint) { return address(this).balance; } //retrieve all funds recieved from minting function withdraw() public onlyOwner { uint256 balance = accountBalance(); require(balance > 0, 'No Funds to withdraw, Balance is 0'); _withdraw(payable(0xd7DDfE7233D872d3600549b570b3631604aA5ffF), balance); } //send the percentage of funds to a shareholder´s wallet function _withdraw(address payable account, uint256 amount) internal { (bool sent, ) = account.call{value: amount}(""); require(sent, "Failed to send Ether"); } //change the dummy account used for signing transactions function changeDummy(address _dummy) public onlyOwner { dummy = _dummy; } //to see the total amount of reserved mints left function reservedMintsLeft() public onlyOwner view returns(uint) { return maxReservedMints - _reservedMints; } //see current state of sale //see the current state of the sale function saleState() public view returns(State){ if (presaleLaunchTime == 0) { return State.NoSale; } else if (publicSaleLaunchTime == 0) { return State.Presale; } else { return State.PublicSale; } } //gets the cost of current mint function mintCost() public view returns(uint) { State saleState_ = saleState(); if (saleState_ == State.NoSale || saleState_ == State.Presale) { return mintCostPresale; } else { return mintCostPublicSale; } } function calculatePayout() public view returns(uint256) { return accountBalance() / totalSupply(); } function royaltyPayout(uint number, uint256 payout) public onlyOwner { uint256 balance = accountBalance(); require(balance > number * payout, "Insufficient Funds to pay out Royalties!"); require(amountOfTokensGotPayout + number <= totalSupply()); for (uint i; i < number; i++) { (bool success, ) = payable(ownerOf(amountOfTokensGotPayout + i)).call{value: payout}(""); require(success, "Address: unable to send value, recipient may have reverted"); } if (totalSupply() == amountOfTokensGotPayout + number) { amountOfTokensGotPayout = 0; } else { amountOfTokensGotPayout += number; } } //see when NFTs will be revealed function timeOfReveal() public view returns(uint256) { require(revealTime != 0, 'NFT Reveal Time has not been determined yet!'); return revealTime; } function reveal() public onlyOwner { require(revealTime == 0, "Collection has already been revealed!"); revealTime = block.timestamp; } function isPaused() public view returns(bool) { return paused_; } //turn the pause on and off function togglePause() public onlyOwner { paused_ = !paused_; } //setting new prices to mint function changeMintCostPresale(uint256 newCost) public onlyOwner { mintCostPresale = newCost; } function changeMintCostPublicSale(uint256 newCost) public onlyOwner { mintCostPublicSale = newCost; } //setting the maxes for mint function changeMaxMintPresale(uint newMax) public onlyOwner { maxMintPresale = newMax; } function changeMaxMintPublicSale(uint newMax) public onlyOwner { maxMintPublicSale = newMax; } }
see when NFTs will be revealed
function timeOfReveal() public view returns(uint256) { require(revealTime != 0, 'NFT Reveal Time has not been determined yet!'); return revealTime; }
5,856,601
[ 1, 5946, 1347, 423, 4464, 87, 903, 506, 283, 537, 18931, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 813, 951, 426, 24293, 1435, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 266, 24293, 950, 480, 374, 16, 296, 50, 4464, 868, 24293, 2647, 711, 486, 2118, 11383, 4671, 5124, 1769, 203, 3639, 327, 283, 24293, 950, 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 ]
./partial_match/1/0xBdbcDFbca3b6Eb90F251b41806A40569c6eB18cd/sources/contracts/TwapDelay.sol
require(_owner != owner, 'TD01'); Comment out to save size
function setOwner(address _owner) external payable override { require(msg.sender == owner, 'TD00'); require(_owner != address(0), 'TD02'); owner = _owner; emit OwnerSet(_owner); }
2,747,165
[ 1, 6528, 24899, 8443, 480, 3410, 16, 296, 23409, 1611, 8284, 225, 9821, 596, 358, 1923, 963, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 31309, 12, 2867, 389, 8443, 13, 3903, 8843, 429, 3849, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 296, 23409, 713, 8284, 203, 3639, 2583, 24899, 8443, 480, 1758, 12, 20, 3631, 296, 23409, 3103, 8284, 203, 3639, 3410, 273, 389, 8443, 31, 203, 3639, 3626, 16837, 694, 24899, 8443, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; library SafeMath { function ADD388(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB906(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB906(a, b, "SafeMath: subtraction overflow"); } function SUB906(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 MUL601(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 DIV456(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV456(a, b, "SafeMath: division by zero"); } function DIV456(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD78(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD78(a, b, "SafeMath: modulo by zero"); } function MOD78(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _MSGSENDER877() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA207() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER734(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE35(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE429(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM531(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL956(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/utils/Address.sol library Address { function ISCONTRACT600(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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; } function SENDVALUE944(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"); } function FUNCTIONCALL15(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL15(target, data, "Address: low-level call failed"); } function FUNCTIONCALL15(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE358(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE499(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE358(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE358(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT600(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/token/ERC20/ERC20.sol 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; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME254() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL669() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS84() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY738() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF68(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER734(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER67(_MSGSENDER877(), recipient, amount); return true; } function ALLOWANCE35(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE429(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, amount); return true; } function TRANSFERFROM531(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER67(sender, recipient, amount); _APPROVE455(sender, _MSGSENDER877(), _allowances[sender][_MSGSENDER877()].SUB906(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE275(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].ADD388(addedValue)); return true; } function DECREASEALLOWANCE402(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].SUB906(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER67(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER81(sender, recipient, amount); _balances[sender] = _balances[sender].SUB906(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD388(amount); emit TRANSFER657(sender, recipient, amount); } function _MINT823(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER81(address(0), account, amount); _totalSupply = _totalSupply.ADD388(amount); _balances[account] = _balances[account].ADD388(amount); emit TRANSFER657(address(0), account, amount); } function _BURN465(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER81(account, address(0), amount); _balances[account] = _balances[account].SUB906(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB906(amount); emit TRANSFER657(account, address(0), amount); } function _APPROVE455(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING 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 APPROVAL956(owner, spender, amount); } function _SETUPDECIMALS854(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER81(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER331(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFER734.selector, to, value)); } function SAFETRANSFERFROM748(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFERFROM531.selector, from, to, value)); } function SAFEAPPROVE284(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.ALLOWANCE35(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, value)); } function SAFEINCREASEALLOWANCE243(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE35(address(this), spender).ADD388(value); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE653(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE35(address(this), spender).SUB906(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN31(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. 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).FUNCTIONCALL15(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"); } } } interface IVault is IERC20 { function TOKEN190() external view returns (address); //inject NONSTANDARD NAMING function DECIMALS84() external view returns (uint8); //inject NONSTANDARD NAMING function EARN763() external; //inject NONSTANDARD NAMING function DEPOSIT115(uint256) external; //inject NONSTANDARD NAMING function DEPOSITALL187() external; //inject NONSTANDARD NAMING function WITHDRAW593(uint256) external; //inject NONSTANDARD NAMING function WITHDRAWALL63() external; //inject NONSTANDARD NAMING function DISTRIBUTE67() external; //inject NONSTANDARD NAMING function SALVAGE929(address, uint256) external; //inject NONSTANDARD NAMING function GETRATIO675() external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveFi_2 { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[2] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[2] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[2] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurve3Pool { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[3] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[3] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[3] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(uint256) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveFi_4 { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[4] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[4] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveZap_4 { function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING uint256[4] calldata uamounts, uint256 min_mint_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata min_uamounts) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[4] calldata uamounts, uint256 max_burn_amount ) external; function CALC_WITHDRAW_ONE_COIN560(uint256 _token_amount, int128 i) //inject NONSTANDARD NAMING external returns (uint256); function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount ) external; function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust ) external; function WITHDRAW_DONATED_DUST417() external; //inject NONSTANDARD NAMING function COINS352(int128 arg0) external returns (address); //inject NONSTANDARD NAMING function UNDERLYING_COINS1(int128 arg0) external returns (address); //inject NONSTANDARD NAMING function CURVE335() external returns (address); //inject NONSTANDARD NAMING function TOKEN190() external returns (address); //inject NONSTANDARD NAMING } interface ICurveZap { function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount ) external; } interface ICurveGauge { function DEPOSIT115(uint256 _value) external; //inject NONSTANDARD NAMING function DEPOSIT115(uint256 _value, address addr) external; //inject NONSTANDARD NAMING function BALANCEOF68(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAW593(uint256 _value) external; //inject NONSTANDARD NAMING function WITHDRAW593(uint256 _value, bool claim_rewards) external; //inject NONSTANDARD NAMING function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING function CLAIM_REWARDS536(address addr) external; //inject NONSTANDARD NAMING function CLAIMABLE_TOKENS440(address addr) external returns (uint256); //inject NONSTANDARD NAMING function CLAIMABLE_REWARD978(address addr) external view returns (uint256); //inject NONSTANDARD NAMING function INTEGRATE_FRACTION797(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveMintr { function MINT951(address) external; //inject NONSTANDARD NAMING function MINTED257(address arg0, address arg1) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveVotingEscrow { function LOCKED178(address arg0) //inject NONSTANDARD NAMING external view returns (int128 amount, uint256 end); function LOCKED__END474(address _addr) external view returns (uint256); //inject NONSTANDARD NAMING function CREATE_LOCK305(uint256, uint256) external; //inject NONSTANDARD NAMING function INCREASE_AMOUNT922(uint256) external; //inject NONSTANDARD NAMING function INCREASE_UNLOCK_TIME38(uint256 _unlock_time) external; //inject NONSTANDARD NAMING function WITHDRAW593() external; //inject NONSTANDARD NAMING function SMART_WALLET_CHECKER846() external returns (address); //inject NONSTANDARD NAMING } interface ICurveSmartContractChecker { function WALLETS237(address) external returns (bool); //inject NONSTANDARD NAMING function APPROVEWALLET249(address _wallet) external; //inject NONSTANDARD NAMING } interface UniswapRouterV2 { function SWAPEXACTTOKENSFORTOKENS167( //inject NONSTANDARD NAMING uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function ADDLIQUIDITY947( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function ADDLIQUIDITYETH996( //inject NONSTANDARD NAMING address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function REMOVELIQUIDITY801( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function GETAMOUNTSOUT893(uint256 amountIn, address[] calldata path) //inject NONSTANDARD NAMING external view returns (uint256[] memory amounts); function GETAMOUNTSIN14(uint256 amountOut, address[] calldata path) //inject NONSTANDARD NAMING external view returns (uint256[] memory amounts); function SWAPETHFOREXACTTOKENS437( //inject NONSTANDARD NAMING uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function SWAPEXACTETHFORTOKENS898( //inject NONSTANDARD NAMING uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface IUniswapV2Pair { event APPROVAL956( //inject NONSTANDARD NAMING address indexed owner, address indexed spender, uint256 value ); event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING function NAME254() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL669() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS84() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68(address owner) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE35(address owner, address spender) //inject NONSTANDARD NAMING external view returns (uint256); function APPROVE429(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER734(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM531( //inject NONSTANDARD NAMING address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR578() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH551() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES443(address owner) external view returns (uint256); //inject NONSTANDARD NAMING function PERMIT326( //inject NONSTANDARD NAMING address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event MINT405(address indexed sender, uint256 amount0, uint256 amount1); //inject NONSTANDARD NAMING event BURN673( //inject NONSTANDARD NAMING address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event SWAP227( //inject NONSTANDARD NAMING address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event SYNC504(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY881() external pure returns (uint256); //inject NONSTANDARD NAMING function FACTORY729() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0644() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1449() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES964() //inject NONSTANDARD NAMING external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function PRICE0CUMULATIVELAST588() external view returns (uint256); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST951() external view returns (uint256); //inject NONSTANDARD NAMING function KLAST390() external view returns (uint256); //inject NONSTANDARD NAMING function MINT951(address to) external returns (uint256 liquidity); //inject NONSTANDARD NAMING function BURN57(address to) //inject NONSTANDARD NAMING external returns (uint256 amount0, uint256 amount1); function SWAP519( //inject NONSTANDARD NAMING uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function SKIM366(address to) external; //inject NONSTANDARD NAMING function SYNC84() external; //inject NONSTANDARD NAMING } interface IUniswapV2Factory { event PAIRCREATED988( //inject NONSTANDARD NAMING address indexed token0, address indexed token1, address pair, uint256 ); function GETPAIR36(address tokenA, address tokenB) //inject NONSTANDARD NAMING external view returns (address pair); function ALLPAIRS303(uint256) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH195() external view returns (uint256); //inject NONSTANDARD NAMING function FEETO341() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER863() external view returns (address); //inject NONSTANDARD NAMING function CREATEPAIR664(address tokenA, address tokenB) //inject NONSTANDARD NAMING external returns (address pair); } interface ICurveTBTC { function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING uint256[4] calldata amounts, uint256 min_mint_amount ) external returns (uint256); } interface IKeepRewardsClaimable { function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING } // Base of all strategy contracts abstract contract VoxStrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fees uint256 public treasuryFee = 1000; uint256 public constant treasuryfeemax584 = 2000; //inject NONSTANDARD NAMING uint256 public constant treasuryfeebase971 = 10000; //inject NONSTANDARD NAMING uint256 public strategyFee = 500; uint256 public constant strategyfeemax620 = 5000; //inject NONSTANDARD NAMING uint256 public constant strategyfeebase640 = 10000; //inject NONSTANDARD NAMING uint256 public developerFee = 250; uint256 public constant developerfeemax597 = 500; //inject NONSTANDARD NAMING uint256 public constant developerfeebase561 = 10000; //inject NONSTANDARD NAMING // Withdrawal fee uint256 public withdrawalFee = 15; uint256 public constant withdrawalfeemax274 = 15; //inject NONSTANDARD NAMING uint256 public constant withdrawalfeebase605 = 10000; //inject NONSTANDARD NAMING // Tokens address public underlying; address public constant weth339 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING address public constant wbtc162 = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; //inject NONSTANDARD NAMING // User accounts address public governance; address public strategist; address public treasury; address public devfund; address public timelock; address public vault; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor( address _underlying, address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public { require(_underlying != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_treasury != address(0)); require(_devfund != address(0)); require(_timelock != address(0)); require(_vault != address(0)); underlying = _underlying; governance = _governance; strategist = _strategist; treasury = _treasury; devfund = _devfund; timelock = _timelock; vault = _vault; } // **** Modifiers **** // modifier RESTRICTED912 { //inject NONSTANDARD NAMING require( msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function BALANCEOFUNDERLYING222() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(underlying).BALANCEOF68(address(this)); } function BALANCEOFPOOL881() public virtual view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68() public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOFUNDERLYING222().ADD388(BALANCEOFPOOL881()); } function GETNAME974() external virtual pure returns (string memory); //inject NONSTANDARD NAMING // **** Setters **** // function SETTREASURYFEE502(uint256 _treasuryFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); treasuryFee = _treasuryFee; } function SETSTRATEGYFEE761(uint256 _strategyFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); strategyFee = _strategyFee; } function SETDEVELOPERFEE113(uint256 _developerFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); developerFee = _developerFee; } function SETWITHDRAWALFEE980(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); withdrawalFee = _withdrawalFee; } function SETSTRATEGIST654(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function SETGOVERNANCE136(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETTREASURY187(address _treasury) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); treasury = _treasury; } function SETDEVFUND591(address _devfund) external { //inject NONSTANDARD NAMING require(msg.sender == devfund, "!devfund"); devfund = _devfund; } function SETTIMELOCK277(address _timelock) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); timelock = _timelock; } // **** State mutations **** // function DEPOSIT115() public virtual; //inject NONSTANDARD NAMING // Governance only function to salvage non-underlying assets function SALVAGE929(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); require(underlying != address(_asset), "underlying"); balance = _asset.BALANCEOF68(address(this)); _asset.SAFETRANSFER331(treasury, balance); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW593(uint256 _amount) external { //inject NONSTANDARD NAMING require(msg.sender == vault, "!vault"); uint256 _balance = IERC20(underlying).BALANCEOF68(address(this)); if (_balance < _amount) { _amount = _WITHDRAWSOME235(_amount.SUB906(_balance)); _amount = _amount.ADD388(_balance); } uint256 _withdrawalFee = _amount.MUL601(withdrawalFee).DIV456(withdrawalfeebase605); IERC20(underlying).SAFETRANSFER331(treasury, _withdrawalFee); require(vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(underlying).SAFETRANSFER331(vault, _amount.SUB906(_withdrawalFee)); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL63() external RESTRICTED912 returns (uint256 balance) { //inject NONSTANDARD NAMING _WITHDRAWALL78(); balance = IERC20(underlying).BALANCEOF68(address(this)); require(vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(underlying).SAFETRANSFER331(vault, balance); } function _WITHDRAWALL78() internal { //inject NONSTANDARD NAMING _WITHDRAWSOME235(BALANCEOFPOOL881()); } function _WITHDRAWSOME235(uint256 _amount) internal virtual returns (uint256); //inject NONSTANDARD NAMING function HARVEST372() public virtual; //inject NONSTANDARD NAMING function _DISTRIBUTEANDDEPOSIT388() internal { //inject NONSTANDARD NAMING uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this)); if (_underlying > 0) { // Treasury fees IERC20(underlying).SAFETRANSFER331( treasury, _underlying.MUL601(treasuryFee).DIV456(treasuryfeebase971) ); // Strategy fee IERC20(underlying).SAFETRANSFER331( strategist, _underlying.MUL601(strategyFee).DIV456(strategyfeebase640) ); // Developer fee IERC20(underlying).SAFETRANSFER331( devfund, _underlying.MUL601(developerFee).DIV456(developerfeebase561) ); DEPOSIT115(); } } // **** Emergency functions **** function EXECUTE807(address _target, bytes memory _data) //inject NONSTANDARD NAMING public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _SWAPUNISWAP503( //inject NONSTANDARD NAMING address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); // Swap with uniswap IERC20(_from).SAFEAPPROVE284(univ2Router2, 0); IERC20(_from).SAFEAPPROVE284(univ2Router2, _amount); address[] memory path; if (_from == weth339 || _to == weth339) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth339; path[2] = _to; } UniswapRouterV2(univ2Router2).SWAPEXACTTOKENSFORTOKENS167( _amount, 0, path, address(this), now.ADD388(60) ); } } // Base contract for Curve based vault strategies abstract contract VoxStrategyCurveBase is VoxStrategyBase { // curve dao address public curve; address public gauge; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // bitcoins address public renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; // rewards address public crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; // keep address public keep = 0x85Eee30c52B0b379b046Fb0F85F4f3Dc3009aFEC; address public keep_rewards = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6; // How much CRV tokens to keep uint256 public keepCRV = 0; uint256 public keepCRVMax = 10000; constructor( address _curve, address _gauge, address _underlying, address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public VoxStrategyBase(_underlying, _governance, _strategist, _treasury, _devfund, _timelock, _vault) { curve = _curve; gauge = _gauge; } // **** Getters **** function BALANCEOFPOOL881() public override view returns (uint256) { //inject NONSTANDARD NAMING return ICurveGauge(gauge).BALANCEOF68(address(this)); } function GETHARVESTABLE58() external returns (uint256) { //inject NONSTANDARD NAMING return ICurveGauge(gauge).CLAIMABLE_TOKENS440(address(this)); } function GETMOSTPREMIUM814() public virtual view returns (address, uint256); //inject NONSTANDARD NAMING // **** Setters **** function SETKEEPCRV171(uint256 _keepCRV) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutation functions **** function DEPOSIT115() public override { //inject NONSTANDARD NAMING uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this)); if (_underlying > 0) { IERC20(underlying).SAFEAPPROVE284(gauge, 0); IERC20(underlying).SAFEAPPROVE284(gauge, _underlying); ICurveGauge(gauge).DEPOSIT115(_underlying); } } function _WITHDRAWSOME235(uint256 _amount) //inject NONSTANDARD NAMING internal override returns (uint256) { ICurveGauge(gauge).WITHDRAW593(_amount); return _amount; } } contract VoxStrategyCurveTBTC is VoxStrategyCurveBase { // Curve stuff address public tbtc_pool = 0xaa82ca713D94bBA7A89CEAB55314F9EfFEdDc78c; address public tbtc_gauge = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6; address public tbtc_crv = 0x64eda51d3Ad40D56b9dFc5554E06F94e1Dd786Fd; // EVENTS event HARVESTED180(address indexed token, uint256 amount); //inject NONSTANDARD NAMING constructor( address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public VoxStrategyCurveBase( tbtc_pool, tbtc_gauge, tbtc_crv, _governance, _strategist, _treasury, _devfund, _timelock, _vault ) {} // **** Views **** function GETMOSTPREMIUM814() //inject NONSTANDARD NAMING public override view returns (address, uint256) { return (wbtc162, 2); } function GETNAME974() external override pure returns (string memory) { //inject NONSTANDARD NAMING return "VoxStrategyCurveTBTC"; } // **** State Mutations **** function HARVEST372() public RESTRICTED912 override { //inject NONSTANDARD NAMING // bitcoin we want to convert to (address to, uint256 toIndex) = GETMOSTPREMIUM814(); // Collects crv tokens // this also sends KEEP to keep_rewards contract ICurveMintr(mintr).MINT951(gauge); uint256 _crv = IERC20(crv).BALANCEOF68(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.MUL601(keepCRV).DIV456(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).SAFETRANSFER331( treasury, _keepCRV ); } _crv = _crv.SUB906(_keepCRV); _SWAPUNISWAP503(crv, to, _crv); } // Collects keep tokens IKeepRewardsClaimable(keep_rewards).CLAIM_REWARDS536(); uint256 _keep = IERC20(keep).BALANCEOF68(address(this)); if (_keep > 0) { _SWAPUNISWAP503(keep, to, _keep); } // Adds liquidity to curve.fi's pool // to get back underlying (tbtccrv) uint256 _to = IERC20(to).BALANCEOF68(address(this)); if (_to > 0) { IERC20(to).SAFEAPPROVE284(curve, 0); IERC20(to).SAFEAPPROVE284(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveTBTC(curve).ADD_LIQUIDITY50(liquidity, 0); } // Distribute the collected funds and deposit underlying // Emit harvested event _DISTRIBUTEANDDEPOSIT388(); emit HARVESTED180(to, _to); } }
inject NONSTANDARD NAMING
function NONCES443(address owner) external view returns (uint256);
12,569,002
[ 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, 565, 445, 18708, 1441, 55, 6334, 23, 12, 2867, 3410, 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, -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; import "ds-test/test.sol"; import "../test/utils/Caller.sol"; import {Hevm} from "../test/utils/Hevm.sol"; import {Oracle} from "./Oracle.sol"; contract OracleImplementation is Oracle { constructor(uint256 timeUpdateWindow_) Oracle(timeUpdateWindow_) { this; } // Allow the test to change the return value // This will not be used in the actual implementation int256 internal _returnValue; function setValue(int256 value_) public { _returnValue = value_; } // We want to handle cases where the oracle fails to obtain values // Ideally the `getValue()` will never fail, but the current implementation will also handle fails bool internal _success = true; function setSuccess(bool success_) public { _success = success_; } // We mock this value provider to return the expected previously set value function getValue() external view override(Oracle) returns (int256) { if (_success) { return _returnValue; } else { revert("Oracle failed"); } } } contract OracleReenter is Oracle { constructor(uint256 timeUpdateWindow_) Oracle(timeUpdateWindow_) { this; } bool public reentered = false; function getValue() external override(Oracle) returns (int256) { if (reentered) { return 42; } else { reentered = true; super.update(); } return 0; } } contract OracleTest is DSTest { Hevm internal hevm = Hevm(DSTest.HEVM_ADDRESS); OracleImplementation internal oracle; uint256 internal timeUpdateWindow = 100; // seconds function setUp() public { oracle = new OracleImplementation(timeUpdateWindow); // Set the value returned to 100 oracle.setValue(int256(100 * 10**18)); hevm.warp(timeUpdateWindow * 10); } function test_deploy() public { assertTrue(address(oracle) != address(0)); } function test_check_timeUpdateWindow() public { // Check that the property was properly set assertTrue( oracle.timeUpdateWindow() == timeUpdateWindow, "Invalid oracle timeUpdateWindow" ); } function test_update_updates_timestamp() public { oracle.update(); // Check if the timestamp was updated assertEq(oracle.lastTimestamp(), block.timestamp); } function test_update_shouldNotUpdatePreviousValues_ifNotEnoughTimePassed() public { // Get current timestamp uint256 blockTimestamp = block.timestamp; // Update the oracle oracle.update(); // Check if the timestamp was updated assertEq(oracle.lastTimestamp(), blockTimestamp); // Advance time hevm.warp(blockTimestamp + timeUpdateWindow - 1); // Calling update should not update the values // because not enough time has passed oracle.update(); // Check if the values are still the same assertEq(oracle.lastTimestamp(), blockTimestamp); } function test_update_shouldUpdatePreviousValues_ifEnoughTimePassed() public { // Get current timestamp uint256 blockTimestamp = block.timestamp; // Advance time hevm.warp(blockTimestamp + timeUpdateWindow); // Calling update should update the values // because enough time has passed oracle.update(); // Last timestamp should be updated assertEq(oracle.lastTimestamp(), blockTimestamp + timeUpdateWindow); } function test_update_updateDoesNotChangeTheValue_inTheSameWindow() public { oracle.setValue(int256(100 * 10**18)); // Update the oracle oracle.update(); (int256 value1, ) = oracle.value(); assertEq(value1, 100 * 10**18); int256 nextValue1 = oracle.nextValue(); assertEq(nextValue1, 100 * 10**18); oracle.setValue(int256(150 * 10**18)); // Advance time but stay in the same time update window hevm.warp(block.timestamp + 1); // Update the oracle oracle.update(); // Values are not modified (int256 value2, ) = oracle.value(); assertEq(value2, 100 * 10**18); int256 nextValue2 = oracle.nextValue(); assertEq(nextValue2, 100 * 10**18); } function test_update_shouldNotFail_whenValueProviderFails() public { oracle.setSuccess(false); // Update the oracle oracle.update(); } function test_value_shouldBeInvalid_afterValueProviderFails() public { // We first successfully update the value to make sure the lastTimestamp is updated // After that, we wait for the required amount of time and try update the value again // The second update will fail and the value should be invalid because of the flag only. // (time check is still correct because maxValidTime >= timeUpdateWindow) oracle.setValue(10**18); // Update the oracle oracle.update(); // Advance time hevm.warp(block.timestamp + timeUpdateWindow); oracle.setSuccess(false); // Update the oracle oracle.update(); (, bool isValid) = oracle.value(); assertTrue(isValid == false); } function test_value_shouldBecomeValid_afterSuccessfulUpdate() public { oracle.setSuccess(false); oracle.update(); (, bool isValid1) = oracle.value(); assertTrue(isValid1 == false); oracle.setSuccess(true); oracle.update(); (, bool isValid2) = oracle.value(); assertTrue(isValid2 == true); } function test_valueReturned_shouldNotBeValid_ifNeverUpdated() public { // Initially the value should be considered stale (, bool valid) = oracle.value(); assertTrue(valid == false); } function test_paused_stops_returnValue() public { // Pause oracle oracle.pause(); // Create user Caller user = new Caller(); // Should fail trying to get value bool success; (success, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.value.selector) ); assertTrue(success == false, "value() should fail when paused"); } function test_paused_doesNotStop_update() public { // Pause oracle oracle.pause(); // Create user Caller user = new Caller(); // Allow user to call update on the oracle oracle.allowCaller(oracle.ANY_SIG(), address(user)); // Should not fail trying to get update bool success; (success, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.update.selector) ); assertTrue(success, "update() should not fail when paused"); } function test_reset_resetsContract() public { // Make sure there are some values in there oracle.update(); // Last updated timestamp is this block assertEq(oracle.lastTimestamp(), block.timestamp); // Value should be 100 and valid int256 value; bool valid; (value, valid) = oracle.value(); assertEq(value, 100 * 10**18); assertTrue(valid == true); // Oracle should be paused when resetting oracle.pause(); // Reset contract oracle.reset(); // Unpause contract oracle.unpause(); // Last updated timestamp should be 0 assertEq(oracle.lastTimestamp(), 0); // Value should be 0 and not valid (value, valid) = oracle.value(); assertEq(value, 0); assertTrue(valid == false); // Next value should be 0 assertEq(oracle.nextValue(), 0); } function test_reset_shouldBePossible_ifPaused() public { // Pause oracle oracle.pause(); // Reset contract oracle.reset(); } function testFail_reset_shouldNotBePossible_ifNotPaused() public { // Oracle is not paused assertTrue(oracle.paused() == false); // Reset contract should fail oracle.reset(); } function test_authorizedUser_shouldBeAble_toReset() public { // Create user Caller user = new Caller(); // Grant ability to reset oracle.allowCaller(oracle.reset.selector, address(user)); // Oracle should be paused when calling reset oracle.pause(); // Should not fail trying to reset bool success; (success, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.reset.selector) ); assertTrue( success, "Only authorized user should be able to call reset()" ); } function test_nonAuthorizedUser_shouldNotBeAble_toReset() public { // Create user // Do not authorize user Caller user = new Caller(); // Oracle should be paused when calling reset oracle.pause(); // Should fail trying to reset bool success; (success, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.reset.selector) ); assertTrue( success == false, "Non-authorized user should not be able to call reset()" ); } function testFail_update_cannotBeReentered() public { OracleReenter oracleReenter = new OracleReenter(timeUpdateWindow); oracleReenter.update(); assertTrue(oracleReenter.reentered()); } function test_update_returnsTrue_whenSuccessful() public { bool updated; updated = oracle.update(); assertTrue(updated, "Should return `true` no successful update"); } function test_update_returnsFalse_whenUpdateDoesNotChangeAnything() public { bool updated; updated = oracle.update(); // Second update should return false since it doesn't change anything updated = oracle.update(); assertTrue( updated == false, "Should return `true` no successful update" ); } function test_update_nonAuthorizedUserCanNotCall_update() public { Caller user = new Caller(); // A non permissioned user should not be able to call bool ok; (ok, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.update.selector) ); assertTrue( ok == false, "Non permissioned user should not be able to call update" ); } function test_update_authorizedUserCanCall_update() public { Caller user = new Caller(); // Give permission to the user oracle.allowCaller(oracle.update.selector, address(user)); // A non permissioned user should not be able to call bool ok; (ok, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.update.selector) ); assertTrue(ok, "Permissioned user should be able to call update"); } }
Create user Grant ability to reset Oracle should be paused when calling reset Should not fail trying to reset
function test_authorizedUser_shouldBeAble_toReset() public { Caller user = new Caller(); oracle.allowCaller(oracle.reset.selector, address(user)); oracle.pause(); bool success; (success, ) = user.externalCall( address(oracle), abi.encodeWithSelector(oracle.reset.selector) ); assertTrue( success, "Only authorized user should be able to call reset()" ); }
12,644,920
[ 1, 1684, 729, 19689, 7123, 358, 2715, 28544, 1410, 506, 17781, 1347, 4440, 2715, 9363, 486, 2321, 8374, 358, 2715, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1842, 67, 8434, 1299, 67, 13139, 1919, 5895, 298, 67, 869, 7013, 1435, 1071, 288, 203, 3639, 20646, 729, 273, 394, 20646, 5621, 203, 203, 3639, 20865, 18, 5965, 11095, 12, 280, 16066, 18, 6208, 18, 9663, 16, 1758, 12, 1355, 10019, 203, 203, 3639, 20865, 18, 19476, 5621, 203, 203, 3639, 1426, 2216, 31, 203, 3639, 261, 4768, 16, 262, 273, 729, 18, 9375, 1477, 12, 203, 5411, 1758, 12, 280, 16066, 3631, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 280, 16066, 18, 6208, 18, 9663, 13, 203, 3639, 11272, 203, 203, 3639, 1815, 5510, 12, 203, 5411, 2216, 16, 203, 5411, 315, 3386, 10799, 729, 1410, 506, 7752, 358, 745, 2715, 10031, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x9a6Ae3Fbec290951a3453E70aa461B470CdFCb4d/sources/contracts/Asset.sol
Transfer the payment to the owner of the Asset
address assetOwner = ownerOf(assetId);
3,792,904
[ 1, 5912, 326, 5184, 358, 326, 3410, 434, 326, 10494, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 1758, 3310, 5541, 273, 3410, 951, 12, 9406, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x58bcA53ebba1AAf25F0EDCd8DaD6421872fe20B2/sources/home/user/Documents/git-repos/0x/protocol/node_modules/@0x/contracts-utils/contracts/src/v06/AuthorizableV06.sol
@dev Removes authorizion of an address. @param target Address to remove authorization from.
function removeAuthorizedAddress(address target) external override onlyOwner { if (!authorized[target]) { LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetNotAuthorizedError(target)); } for (uint256 i = 0; i < authorities.length; i++) { if (authorities[i] == target) { _removeAuthorizedAddressAtIndex(target, i); break; } } }
11,540,621
[ 1, 6220, 2869, 452, 285, 434, 392, 1758, 18, 225, 1018, 5267, 358, 1206, 6093, 628, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 15341, 1887, 12, 2867, 1018, 13, 3903, 3849, 1338, 5541, 288, 203, 3639, 309, 16051, 8434, 63, 3299, 5717, 288, 203, 5411, 10560, 22591, 4229, 58, 7677, 18, 86, 266, 1097, 12, 5664, 3594, 6934, 22591, 4229, 58, 7677, 18, 2326, 1248, 15341, 668, 12, 3299, 10019, 203, 3639, 289, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2869, 1961, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 4161, 1961, 63, 77, 65, 422, 1018, 13, 288, 203, 7734, 389, 4479, 15341, 1887, 24499, 12, 3299, 16, 277, 1769, 203, 7734, 898, 31, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.17; contract Lottery { // address of a person who creates the contract Lottery address public manager; address[] public players; constructor() public { // "msg" is a global variable available in any function inside our contract // it represents a transaction which goes into a function manager = msg.sender; } // "payable" says the if somebody wants to call this function, he has to pay some amount of ether function enter() public payable { // "require()" is a global function which is used for validation // "msg.value" uses "wei" units require(msg.value > 0.1 ether); // when "ether" keyword is present, the value 0.1 is automatically converted into wei // whoever calls this function, he wants to enter the lottery -> add him to the list of players players.push(msg.sender); } function generateRandomNumber() private view returns (uint) { // "block" and "now" are global variables // "block.difficulty" says how difficult it was to mine the block in the blockchain return uint(keccak256(block.difficulty, now, players)); } // "restricted" is our custom modifier defined below function pickWinner() public calledByManager { uint index = generateRandomNumber() % players.length; // data type "address" is a like a class and has a set of methods // "this" keyword is a reference to the contract object // "this.balance" contains amount of money which this contract has available to it players[index].transfer(this.balance); // after the money is transfered to an address, we want to reset the contract state by // reinitialising the array of players to an empty array players = new address[](0); // assign a new array with no players in it } // this defines a new function modifier which will be added to our contract // function modifiers are for reducing repeating code modifier calledByManager() { require(msg.sender == manager); // only manager can call this function _; // this statement takes the content (all statements) of the function to which the modifier is attached // and puts it to this place (this is done by the compiler behind the scenes) } function getPlayers() public view returns (address[]) { return players; } }
"restricted" is our custom modifier defined below data type "address" is a like a class and has a set of methods "this" keyword is a reference to the contract object "this.balance" contains amount of money which this contract has available to it after the money is transfered to an address, we want to reset the contract state by reinitialising the array of players to an empty array
function pickWinner() public calledByManager { uint index = generateRandomNumber() % players.length; players[index].transfer(this.balance); }
12,635,955
[ 1, 6, 29306, 6, 353, 3134, 1679, 9606, 2553, 5712, 501, 618, 315, 2867, 6, 353, 279, 3007, 279, 667, 471, 711, 279, 444, 434, 2590, 315, 2211, 6, 4932, 353, 279, 2114, 358, 326, 6835, 733, 315, 2211, 18, 12296, 6, 1914, 3844, 434, 15601, 1492, 333, 6835, 711, 2319, 358, 518, 1839, 326, 15601, 353, 7412, 329, 358, 392, 1758, 16, 732, 2545, 358, 2715, 326, 6835, 919, 635, 283, 6769, 13734, 326, 526, 434, 18115, 358, 392, 1008, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6002, 59, 7872, 1435, 1071, 2566, 858, 1318, 288, 203, 3639, 2254, 770, 273, 2103, 8529, 1854, 1435, 738, 18115, 18, 2469, 31, 203, 540, 203, 3639, 18115, 63, 1615, 8009, 13866, 12, 2211, 18, 12296, 1769, 203, 540, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; library DateTimeLib { /* * Date and Time utilities for ethereum contracts * */ struct _DateTime { uint16 year; uint8 month; uint8 day; uint8 hour; uint8 minute; uint8 second; uint8 weekday; } uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint constant HOUR_IN_SECONDS = 3600; uint constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; function isLeapYear(uint16 year) public pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint year) public pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestamp(uint timestamp) internal pure returns (_DateTime dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; // Year dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); // Month uint secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } // Hour dt.hour = getHour(timestamp); // Minute dt.minute = getMinute(timestamp); // Second dt.second = getSecond(timestamp); // Day of week. dt.weekday = getWeekday(timestamp); } function getYear(uint timestamp) public pure returns (uint16) { uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).month; } function getDay(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).day; } function getHour(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60 / 60) % 24); } function getMinute(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60) % 60); } function getSecond(uint timestamp) public pure returns (uint8) { return uint8(timestamp % 60); } function getWeekday(uint timestamp) public pure returns (uint8) { return uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } function toTimestamp(uint16 year, uint8 month, uint8 day) public pure returns (uint timestamp) { return toTimestamp(year, month, day, 0, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) public pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) public pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, minute, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) public pure returns (uint timestamp) { uint16 i; // Year for (i = ORIGIN_YEAR; i < year; i++) { if (isLeapYear(i)) { timestamp += LEAP_YEAR_IN_SECONDS; } else { timestamp += YEAR_IN_SECONDS; } } // Month uint8[12] memory monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; for (i = 1; i < month; i++) { timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1]; } // Day timestamp += DAY_IN_SECONDS * (day - 1); // Hour timestamp += HOUR_IN_SECONDS * (hour); // Minute timestamp += MINUTE_IN_SECONDS * (minute); // Second timestamp += second; return timestamp; } } library SafeMathLib { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface IERC20 { //function totalSupply() public constant returns (uint256 totalSupply); function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address _spender, uint256 _value); } contract StandardToken is IERC20 { using SafeMathLib for uint256; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function StandardToken() public payable { } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool success) { return transferInternal(msg.sender, _to, _value); } function transferInternal(address _from, address _to, uint256 _value) internal returns (bool success) { require(_value > 0 && balances[_from] >= _value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value > 0 && allowed[_from][msg.sender] >= _value && balances[_from] >= _value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address _spender, uint256 _value); } contract LockableToken is StandardToken { mapping(address => uint256) internal lockedBalance; mapping(address => uint) internal timeRelease; address internal teamReservedHolder; uint256 internal teamReservedBalance; uint [8] internal teamReservedFrozenDates; uint256 [8] internal teamReservedFrozenLimits; function LockableToken() public payable { } function lockInfo(address _address) public constant returns (uint timeLimit, uint256 balanceLimit) { return (timeRelease[_address], lockedBalance[_address]); } function teamReservedLimit() internal returns (uint256 balanceLimit) { uint time = now; for (uint index = 0; index < teamReservedFrozenDates.length; index++) { if (teamReservedFrozenDates[index] == 0x0) { continue; } if (time > teamReservedFrozenDates[index]) { teamReservedFrozenDates[index] = 0x0; } else { return teamReservedFrozenLimits[index]; } } return 0; } function transfer(address _to, uint256 _value) public returns (bool success) { return transferInternal(msg.sender, _to, _value); } function transferInternal(address _from, address _to, uint256 _value) internal returns (bool success) { require(_to != 0x0 && _value > 0x0); if (_from == teamReservedHolder) { uint256 reservedLimit = teamReservedLimit(); require(balances[_from].sub(reservedLimit) >= _value); } var (timeLimit, lockLimit) = lockInfo(_from); if (timeLimit <= now && timeLimit != 0x0) { timeLimit = 0x0; timeRelease[_from] = 0x0; lockedBalance[_from] = 0x0; UnLock(_from, lockLimit); lockLimit = 0x0; } if (timeLimit != 0x0 && lockLimit > 0x0) { require(balances[_from].sub(lockLimit) >= _value); } return super.transferInternal(_from, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return transferFromInternal(_from, _to, _value); } function transferFromInternal(address _from, address _to, uint256 _value) internal returns (bool success) { require(_to != 0x0 && _value > 0x0); if (_from == teamReservedHolder) { uint256 reservedLimit = teamReservedLimit(); require(balances[_from].sub(reservedLimit) >= _value); } var (timeLimit, lockLimit) = lockInfo(_from); if (timeLimit <= now && timeLimit != 0x0) { timeLimit = 0x0; timeRelease[_from] = 0x0; lockedBalance[_from] = 0x0; UnLock(_from, lockLimit); lockLimit = 0x0; } if (timeLimit != 0x0 && lockLimit > 0x0) { require(balances[_from].sub(lockLimit) >= _value); } return super.transferFrom(_from, _to, _value); } event Lock(address indexed owner, uint256 value, uint releaseTime); event UnLock(address indexed owner, uint256 value); } contract TradeableToken is LockableToken { address public publicOfferingHolder; uint256 internal baseExchangeRate; uint256 internal earlyExchangeRate; uint internal earlyEndTime; function TradeableToken() public payable { } function buy(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != 0x0); require(publicOfferingHolder != 0x0); require(earlyEndTime != 0x0 && baseExchangeRate != 0x0 && earlyExchangeRate != 0x0); require(_weiAmount != 0x0); uint256 rate = baseExchangeRate; if (now <= earlyEndTime) { rate = earlyExchangeRate; } uint256 exchangeToken = _weiAmount.mul(rate); exchangeToken = exchangeToken.div(1 * 10 ** 10); publicOfferingHolder.transfer(_weiAmount); super.transferInternal(publicOfferingHolder, _beneficiary, exchangeToken); } } contract OwnableToken is TradeableToken { address internal owner; uint internal _totalSupply = 1500000000 * 10 ** 8; function OwnableToken() public payable { } /* * Modifiers */ modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) onlyOwner public { require(_newOwner != address(0)); owner = _newOwner; OwnershipTransferred(owner, _newOwner); } function lock(address _owner, uint256 _value, uint _releaseTime) public payable onlyOwner returns (uint releaseTime, uint256 limit) { require(_owner != 0x0 && _value > 0x0 && _releaseTime >= now); _value = lockedBalance[_owner].add(_value); _releaseTime = _releaseTime >= timeRelease[_owner] ? _releaseTime : timeRelease[_owner]; lockedBalance[_owner] = _value; timeRelease[_owner] = _releaseTime; Lock(_owner, _value, _releaseTime); return (_releaseTime, _value); } function unlock(address _owner) public payable onlyOwner returns (bool) { require(_owner != 0x0); uint256 _value = lockedBalance[_owner]; lockedBalance[_owner] = 0x0; timeRelease[_owner] = 0x0; UnLock(_owner, _value); return true; } function transferAndLock(address _to, uint256 _value, uint _releaseTime) public payable onlyOwner returns (bool success) { require(_to != 0x0); require(_value > 0); require(_releaseTime >= now); require(_value <= balances[msg.sender]); super.transfer(_to, _value); lock(_to, _value, _releaseTime); return true; } function setBaseExchangeRate(uint256 _baseExchangeRate) public payable onlyOwner returns (bool success) { require(_baseExchangeRate > 0x0); baseExchangeRate = _baseExchangeRate; BaseExchangeRateChanged(baseExchangeRate); return true; } function setEarlyExchangeRate(uint256 _earlyExchangeRate) public payable onlyOwner returns (bool success) { require(_earlyExchangeRate > 0x0); earlyExchangeRate = _earlyExchangeRate; EarlyExchangeRateChanged(earlyExchangeRate); return true; } function setEarlyEndTime(uint256 _earlyEndTime) public payable onlyOwner returns (bool success) { require(_earlyEndTime > 0x0); earlyEndTime = _earlyEndTime; EarlyEndTimeChanged(earlyEndTime); return true; } function burn(uint256 _value) public payable onlyOwner returns (bool success) { require(_value > 0x0); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); _totalSupply = _totalSupply.sub(_value); Burned(_value); return true; } function setPublicOfferingHolder(address _publicOfferingHolder) public payable onlyOwner returns (bool success) { require(_publicOfferingHolder != 0x0); publicOfferingHolder = _publicOfferingHolder; return true; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event BaseExchangeRateChanged(uint256 baseExchangeRate); event EarlyExchangeRateChanged(uint256 earlyExchangeRate); event EarlyEndTimeChanged(uint256 earlyEndTime); event Burned(uint256 value); } contract TenYunToken is OwnableToken { string public constant symbol = "TYC"; string public constant name = "TenYun Coin"; uint8 public constant decimals = 8; function TenYunToken() public payable { owner = 0x593841e27b7122ef48F7854c7E7E1d5A374f8BB3; balances[owner] = 1500000000 * 10 ** 8; publicOfferingHolder = 0x0B83ED7C57c335dCA9C978f78819A739AC67fD5D; balances[publicOfferingHolder] = 0x0; baseExchangeRate = 8500; earlyExchangeRate = 9445; earlyEndTime = 1516291200; teamReservedHolder = 0x6e4890764AA2Bba346459e2D6b811e26C9691704; teamReservedBalance = 300000000 * 10 ** 8; balances[teamReservedHolder] = 0x0; teamReservedFrozenDates = [ DateTimeLib.toTimestamp(2018, 4, 25), DateTimeLib.toTimestamp(2018, 7, 25), DateTimeLib.toTimestamp(2018, 10, 25), DateTimeLib.toTimestamp(2019, 1, 25), DateTimeLib.toTimestamp(2019, 4, 25), DateTimeLib.toTimestamp(2019, 7, 25), DateTimeLib.toTimestamp(2019, 10, 25), DateTimeLib.toTimestamp(2020, 1, 25) ]; teamReservedFrozenLimits = [ teamReservedBalance, teamReservedBalance - (teamReservedBalance / 8) * 1, teamReservedBalance - (teamReservedBalance / 8) * 2, teamReservedBalance - (teamReservedBalance / 8) * 3, teamReservedBalance - (teamReservedBalance / 8) * 4, teamReservedBalance - (teamReservedBalance / 8) * 5, teamReservedBalance - (teamReservedBalance / 8) * 6, teamReservedBalance - (teamReservedBalance / 8) * 7 ]; } // fallback function can be used to buy tokens function() public payable { buy(msg.sender, msg.value); } function ethBalanceOf(address _owner) public constant returns (uint256){ return _owner.balance; } function totalSupply() public constant returns (uint256 totalSupply) { return _totalSupply; } }
function totalSupply() public constant returns (uint256 totalSupply);
interface IERC20 { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address _spender, uint256 _value); }
1,031,669
[ 1, 915, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 5034, 2078, 3088, 1283, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 288, 203, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 5381, 1135, 261, 11890, 5034, 11013, 1769, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 13, 1071, 5381, 1135, 261, 11890, 5034, 4463, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 389, 2080, 16, 1758, 8808, 389, 869, 16, 2254, 5034, 389, 1132, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 389, 8443, 16, 1758, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 1769, 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 ]
./full_match/4/0xEB6C780cf1771bc18a7a18Fe6556059a5562A5fD/sources/contracts/project1/RouterContract.sol
      bool val = IERC20(addOfBNB).transferFrom(msg.sender, address(this), amount);       IERC20(addOfB).approve(addOfRouter,amoPathforB[pathIndexOfexactAmount]);         _tokenC.approve(addOfRouter,amoPathforC[pathIndexOfexactAmount]);LP TOKWENS FOR A-bnb PAIRLP TOKWENS FOR B-bnb PAIRLP TOKWENS FOR C-BNB PAIR         uint BBNBBal = getBNBBalanceOfUser(BBNBTokenAddress);         uint CBNBBal = getBNBBalanceOfUser(CBNBTokenAddress);         IUniswapV2Pair(ABNBTokenAddress).approve(addOfAutoFarm, ABNBBal);         IUniswapV2Pair(BBNBTokenAddress).approve(addOfAutoFarm, BBNBBal);         IUniswapV2Pair(CBNBTokenAddress).approve(addOfAutoFarm, CBNBBal);
function DepositBNB(uint amount)external { require(amount > 0 , "amont should be > 0"); uint distributedAmount = amount/3 ; require( IERC20(addOfBNB).balanceOf(msg.sender) >=amount ,'insufficient balanceOf' ); balance[msg.sender][addOfBNB] = balance[msg.sender][addOfBNB] + amount; address[] memory pathA ; pathA = new address[](2); pathA[0] = 0xf50E2F9430C1B080640eB8cd926723AA7B6c900a ; pathA[1] = 0xD0Aa029cB7Ee427794a1060D7c98a2b9D8279bca ; address[] memory pathC ; pathC = new address[](2); pathC[0] = 0xf50E2F9430C1B080640eB8cd926723AA7B6c900a ; pathC[1] = 0xb11887070842140bfe6d94228972Dc3c2c00B5d7 ; address[] memory pathB ; pathB = new address[](2); pathB[0] = 0xf50E2F9430C1B080640eB8cd926723AA7B6c900a ; pathB[1] = 0x28A9e3c379Cd845134500AA7b8964e0d20be1911 ; IERC20 _tokenBNB; IERC20 _tokenA; IERC20 _tokenB; IERC20 _tokenC; _tokenBNB = IERC20(addOfBNB) ; _tokenA = IERC20(addOfA) ; _tokenB = IERC20(addOfB) ; _tokenC = IERC20(addOfC) ; _tokenBNB.approve(addOfRouter , amount ) ; uint amountForSwap = distributedAmount/2 ; uint256[] memory amoPathforA = IUniswapV2Router02(addOfRouter).swapExactTokensForTokens(amountForSwap , 0 , pathA,address(this),now+1000 ); uint256[] memory amoPathforB = IUniswapV2Router02(addOfRouter).swapExactTokensForTokens(amountForSwap , 0 , pathB,address(this),now+1000 ); uint256[] memory amoPathforC = IUniswapV2Router02(addOfRouter).swapExactTokensForTokens(amountForSwap , 0 , pathC,address(this),now+1000 ); uint pathIndexOfexactAmount = 1 ; _tokenA.approve(addOfRouter,amoPathforA[pathIndexOfexactAmount]); _tokenB.approve(addOfRouter,amoPathforB[pathIndexOfexactAmount]); _tokenC.approve(addOfRouter,amoPathforC[pathIndexOfexactAmount]); addLiquidityToRouter(addOfA , addOfBNB , amountForSwap,amountForSwap); addLiquidityToRouter(addOfB , addOfBNB , amountForSwap,amountForSwap); addLiquidityToRouter(addOfC , addOfBNB , amountForSwap,amountForSwap); uint ABNBBal = getBNBBalanceOfUser(ABNBTokenAddress); uint BBNBBal = getBNBBalanceOfUser(BBNBTokenAddress); uint CBNBBal = getBNBBalanceOfUser(CBNBTokenAddress); IUniswapV2Pair(ABNBTokenAddress).approve(addOfAutoFarm , ABNBBal); IUniswapV2Pair(BBNBTokenAddress).approve(addOfAutoFarm , BBNBBal); IUniswapV2Pair(CBNBTokenAddress).approve(addOfAutoFarm , CBNBBal); IAutoFarm(addOfAutoFarm).deposit(1, ABNBBal); balance[msg.sender][ABNBTokenAddress] = balance[msg.sender][ABNBTokenAddress] + ABNBBal; IAutoFarm(addOfAutoFarm).deposit(2, BBNBBal); balance[msg.sender][BBNBTokenAddress] = balance[msg.sender][BBNBTokenAddress] + BBNBBal; IAutoFarm(addOfAutoFarm).deposit(3, CBNBBal); balance[msg.sender][CBNBTokenAddress] = balance[msg.sender][CBNBTokenAddress] + CBNBBal; }
12,383,971
[ 1, 6430, 1244, 273, 467, 654, 39, 3462, 12, 1289, 951, 15388, 38, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 565, 131, 259, 225, 131, 259, 225, 131, 259, 225, 467, 654, 39, 3462, 12, 1289, 951, 38, 2934, 12908, 537, 12, 1289, 951, 8259, 16, 301, 83, 743, 1884, 38, 63, 803, 31985, 17165, 6275, 19226, 225, 131, 259, 225, 131, 259, 225, 131, 259, 225, 131, 259, 389, 2316, 39, 18, 12908, 537, 12, 1289, 951, 8259, 16, 301, 83, 743, 1884, 39, 63, 803, 31985, 17165, 6275, 19226, 14461, 399, 3141, 59, 21951, 12108, 432, 17, 70, 6423, 15662, 7937, 14461, 399, 3141, 59, 21951, 12108, 605, 17, 70, 6423, 15662, 7937, 14461, 399, 3141, 59, 21951, 12108, 385, 17, 15388, 38, 15662, 7937, 225, 131, 259, 225, 131, 259, 225, 131, 259, 225, 131, 259, 2254, 605, 15388, 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, 377, 445, 4019, 538, 305, 15388, 38, 12, 11890, 3844, 13, 9375, 288, 203, 1850, 2583, 12, 8949, 405, 374, 269, 315, 301, 1580, 1410, 506, 405, 374, 8863, 203, 540, 2254, 16859, 6275, 225, 273, 3844, 19, 23, 274, 7010, 540, 2583, 12, 467, 654, 39, 3462, 12, 1289, 951, 15388, 38, 2934, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 8949, 269, 11, 2679, 11339, 11013, 951, 11, 11272, 203, 1850, 11013, 63, 3576, 18, 15330, 6362, 1289, 951, 15388, 38, 65, 273, 11013, 63, 3576, 18, 15330, 6362, 1289, 951, 15388, 38, 65, 397, 3844, 31, 203, 540, 1758, 8526, 3778, 589, 37, 274, 203, 540, 589, 37, 273, 394, 1758, 8526, 12, 22, 1769, 203, 540, 589, 37, 63, 20, 65, 273, 374, 5841, 3361, 41, 22, 42, 11290, 5082, 39, 21, 38, 20, 3672, 1105, 20, 73, 38, 28, 4315, 29, 5558, 27, 4366, 5284, 27, 38, 26, 71, 29, 713, 69, 274, 7010, 540, 589, 37, 63, 21, 65, 273, 374, 17593, 20, 37, 69, 3103, 29, 71, 38, 27, 41, 73, 9452, 4700, 11290, 69, 2163, 4848, 40, 27, 71, 10689, 69, 22, 70, 29, 40, 28, 5324, 29, 70, 5353, 274, 7010, 203, 540, 1758, 8526, 3778, 589, 39, 274, 203, 540, 589, 39, 273, 394, 1758, 8526, 12, 22, 1769, 203, 540, 589, 39, 63, 20, 65, 273, 374, 5841, 3361, 41, 22, 42, 11290, 5082, 39, 21, 38, 20, 3672, 1105, 20, 73, 38, 28, 4315, 29, 5558, 27, 4366, 5284, 27, 38, 26, 2 ]
/* This file is part of The Colony Network. The Colony Network 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. The Colony Network 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 The Colony Network. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity 0.5.8; pragma experimental "ABIEncoderV2"; import "./ColonyStorage.sol"; import "./ITokenLocking.sol"; contract ColonyFunding is ColonyStorage, PatriciaTreeProofs { function setTaskManagerPayout(uint256 _id, address _token, uint256 _amount) public stoppable self { setTaskPayout(_id, TaskRole.Manager, _token, _amount); emit TaskPayoutSet(_id, TaskRole.Manager, _token, _amount); } function setTaskEvaluatorPayout(uint256 _id, address _token, uint256 _amount) public stoppable self { setTaskPayout(_id, TaskRole.Evaluator, _token, _amount); emit TaskPayoutSet(_id, TaskRole.Evaluator, _token, _amount); } function setTaskWorkerPayout(uint256 _id, address _token, uint256 _amount) public stoppable self { setTaskPayout(_id, TaskRole.Worker, _token, _amount); emit TaskPayoutSet(_id, TaskRole.Worker, _token, _amount); } function setAllTaskPayouts( uint256 _id, address _token, uint256 _managerAmount, uint256 _evaluatorAmount, uint256 _workerAmount ) public stoppable confirmTaskRoleIdentity(_id, TaskRole.Manager) { Task storage task = tasks[_id]; address manager = task.roles[uint8(TaskRole.Manager)].user; address evaluator = task.roles[uint8(TaskRole.Evaluator)].user; address worker = task.roles[uint8(TaskRole.Worker)].user; require( evaluator == manager || evaluator == address(0x0), "colony-funding-evaluator-already-set"); require( worker == manager || worker == address(0x0), "colony-funding-worker-already-set"); this.setTaskManagerPayout(_id, _token, _managerAmount); this.setTaskEvaluatorPayout(_id, _token, _evaluatorAmount); this.setTaskWorkerPayout(_id, _token, _workerAmount); } // To get all payouts for a task iterate over roles.length function getTaskPayout(uint256 _id, uint8 _role, address _token) public view returns (uint256) { Task storage task = tasks[_id]; bool unsatisfactory = task.roles[_role].rating == TaskRatings.Unsatisfactory; return unsatisfactory ? 0 : task.payouts[_role][_token]; } function claimTaskPayout(uint256 _id, uint8 _role, address _token) public stoppable taskFinalized(_id) { Task storage task = tasks[_id]; FundingPot storage fundingPot = fundingPots[task.fundingPotId]; assert(task.roles[_role].user != address(0x0)); uint payout = task.payouts[_role][_token]; task.payouts[_role][_token] = 0; bool unsatisfactory = task.roles[_role].rating == TaskRatings.Unsatisfactory; if (!unsatisfactory) { processPayout(task.fundingPotId, _token, payout, task.roles[_role].user); } else { fundingPot.payouts[_token] = sub(fundingPot.payouts[_token], payout); } } function claimPayment(uint256 _id, address _token) public stoppable paymentFinalized(_id) { Payment storage payment = payments[_id]; FundingPot storage fundingPot = fundingPots[payment.fundingPotId]; assert(fundingPot.balance[_token] >= fundingPot.payouts[_token]); processPayout(payment.fundingPotId, _token, fundingPot.payouts[_token], payment.recipient); } function setPaymentPayout(uint256 _permissionDomainId, uint256 _childSkillIndex, uint256 _id, address _token, uint256 _amount) public stoppable authDomain(_permissionDomainId, _childSkillIndex, payments[_id].domainId) validPayoutAmount(_amount) paymentNotFinalized(_id) { Payment storage payment = payments[_id]; FundingPot storage fundingPot = fundingPots[payment.fundingPotId]; assert(fundingPot.associatedType == FundingPotAssociatedType.Payment); uint currentTotalAmount = fundingPot.payouts[_token]; fundingPot.payouts[_token] = _amount; updatePayoutsWeCannotMakeAfterBudgetChange(payment.fundingPotId, _token, currentTotalAmount); } function getFundingPotCount() public view returns (uint256 count) { return fundingPotCount; } function getFundingPotBalance(uint256 _potId, address _token) public view returns (uint256) { return fundingPots[_potId].balance[_token]; } function getFundingPotPayout(uint256 _potId, address _token) public view returns (uint256) { return fundingPots[_potId].payouts[_token]; } function getFundingPot(uint256 _potId) public view returns (FundingPotAssociatedType associatedType, uint256 associatedTypeId, uint256 payoutsWeCannotMake) { FundingPot storage fundingPot = fundingPots[_potId]; return (fundingPot.associatedType, fundingPot.associatedTypeId, fundingPot.payoutsWeCannotMake); } function moveFundsBetweenPots( uint256 _permissionDomainId, uint256 _fromChildSkillIndex, uint256 _toChildSkillIndex, uint256 _fromPot, uint256 _toPot, uint256 _amount, address _token ) public stoppable authDomain(_permissionDomainId, _fromChildSkillIndex, getDomainFromFundingPot(_fromPot)) authDomain(_permissionDomainId, _toChildSkillIndex, getDomainFromFundingPot(_toPot)) validFundingTransfer(_fromPot, _toPot) { FundingPot storage fromPot = fundingPots[_fromPot]; FundingPot storage toPot = fundingPots[_toPot]; fromPot.balance[_token] = sub(fromPot.balance[_token], _amount); toPot.balance[_token] = add(toPot.balance[_token], _amount); // If this pot is associated with a Task, prevent money being taken from the pot if the // remaining balance is less than the amount needed for payouts, unless the task was cancelled. if (fromPot.associatedType == FundingPotAssociatedType.Task) { require( tasks[fromPot.associatedTypeId].status == TaskStatus.Cancelled || fromPot.balance[_token] >= fromPot.payouts[_token], "colony-funding-task-bad-state" ); } if (fromPot.associatedType == FundingPotAssociatedType.Task || fromPot.associatedType == FundingPotAssociatedType.Payment) { uint256 fromPotPreviousAmount = add(fromPot.balance[_token], _amount); updatePayoutsWeCannotMakeAfterPotChange(_fromPot, _token, fromPotPreviousAmount); } if (toPot.associatedType == FundingPotAssociatedType.Task || toPot.associatedType == FundingPotAssociatedType.Payment) { uint256 toPotPreviousAmount = sub(toPot.balance[_token], _amount); updatePayoutsWeCannotMakeAfterPotChange(_toPot, _token, toPotPreviousAmount); } emit ColonyFundsMovedBetweenFundingPots(_fromPot, _toPot, _amount, _token); } function claimColonyFunds(address _token) public stoppable { uint toClaim; uint feeToPay; uint remainder; if (_token == address(0x0)) { // It's ether toClaim = sub(sub(address(this).balance, nonRewardPotsTotal[_token]), fundingPots[0].balance[_token]); } else { // Assume it's an ERC 20 token. ERC20Extended targetToken = ERC20Extended(_token); toClaim = sub(sub(targetToken.balanceOf(address(this)), nonRewardPotsTotal[_token]), fundingPots[0].balance[_token]); // ignore-swc-123 } feeToPay = toClaim / getRewardInverse(); // ignore-swc-110 . This variable is set when the colony is // initialised to MAX_UINT, and cannot be set to zero via setRewardInverse, so this is a false positive. It *can* be set // to 0 via recovery mode, but a) That's not why MythX is balking here and b) There's only so much we can stop people being // able to do with recovery mode. remainder = sub(toClaim, feeToPay); nonRewardPotsTotal[_token] = add(nonRewardPotsTotal[_token], remainder); fundingPots[1].balance[_token] = add(fundingPots[1].balance[_token], remainder); fundingPots[0].balance[_token] = add(fundingPots[0].balance[_token], feeToPay); emit ColonyFundsClaimed(_token, feeToPay, remainder); } function getNonRewardPotsTotal(address _token) public view returns (uint256) { return nonRewardPotsTotal[_token]; } function startNextRewardPayout(address _token, bytes memory key, bytes memory value, uint256 branchMask, bytes32[] memory siblings) public stoppable auth { ITokenLocking tokenLocking = ITokenLocking(IColonyNetwork(colonyNetworkAddress).getTokenLocking()); uint256 totalLockCount = tokenLocking.lockToken(token); require(!activeRewardPayouts[_token], "colony-reward-payout-token-active"); uint256 totalTokens = sub(ERC20Extended(token).totalSupply(), ERC20Extended(token).balanceOf(address(this))); require(totalTokens > 0, "colony-reward-payout-invalid-total-tokens"); bytes32 rootHash = IColonyNetwork(colonyNetworkAddress).getReputationRootHash(); uint256 colonyWideReputation = checkReputation( rootHash, domains[1].skillId, address(0x0), key, value, branchMask, siblings ); require(colonyWideReputation > 0, "colony-reward-payout-invalid-colony-wide-reputation"); activeRewardPayouts[_token] = true; rewardPayoutCycles[totalLockCount] = RewardPayoutCycle( rootHash, colonyWideReputation, totalTokens, fundingPots[0].balance[_token], _token, block.timestamp ); emit RewardPayoutCycleStarted(totalLockCount); } function claimRewardPayout( uint256 _payoutId, uint256[7] memory _squareRoots, bytes memory key, bytes memory value, uint256 branchMask, bytes32[] memory siblings ) public stoppable { uint256 userReputation = checkReputation( rewardPayoutCycles[_payoutId].reputationState, domains[1].skillId, msg.sender, key, value, branchMask, siblings ); address tokenAddress; uint256 reward; (tokenAddress, reward) = calculateRewardForUser(_payoutId, _squareRoots, userReputation); uint fee = calculateNetworkFeeForPayout(reward); uint remainder = sub(reward, fee); fundingPots[0].balance[tokenAddress] = sub(fundingPots[0].balance[tokenAddress], reward); ERC20Extended(tokenAddress).transfer(msg.sender, remainder); ERC20Extended(tokenAddress).transfer(colonyNetworkAddress, fee); emit RewardPayoutClaimed(_payoutId, msg.sender, fee, remainder); } function finalizeRewardPayout(uint256 _payoutId) public stoppable { RewardPayoutCycle memory payout = rewardPayoutCycles[_payoutId]; require(activeRewardPayouts[payout.tokenAddress], "colony-reward-payout-token-not-active"); require(block.timestamp - payout.blockTimestamp > 60 days, "colony-reward-payout-active"); activeRewardPayouts[payout.tokenAddress] = false; emit RewardPayoutCycleEnded(_payoutId); } function getRewardPayoutInfo(uint256 _payoutId) public view returns (RewardPayoutCycle memory rewardPayoutCycle) { rewardPayoutCycle = rewardPayoutCycles[_payoutId]; } function setRewardInverse(uint256 _rewardInverse) public stoppable auth { require(_rewardInverse > 0, "colony-reward-inverse-cannot-be-zero"); rewardInverse = _rewardInverse; emit ColonyRewardInverseSet(_rewardInverse); } function getRewardInverse() public view returns (uint256) { return rewardInverse; } function checkReputation( bytes32 rootHash, uint256 skillId, address userAddress, bytes memory key, bytes memory value, uint256 branchMask, bytes32[] memory siblings ) internal view returns (uint256) { bytes32 impliedRoot = getImpliedRootHashKey(key, value, branchMask, siblings); require(rootHash == impliedRoot, "colony-reputation-invalid-root-hash"); uint256 reputationValue; address keyColonyAddress; uint256 keySkill; address keyUserAddress; assembly { reputationValue := mload(add(value, 32)) keyColonyAddress := mload(add(key, 20)) keySkill := mload(add(key, 52)) keyUserAddress := mload(add(key, 72)) } require(keyColonyAddress == address(this), "colony-reputation-invalid-colony-address"); require(keySkill == skillId, "colony-reputation-invalid-skill-id"); require(keyUserAddress == userAddress, "colony-reputation-invalid-user-address"); return reputationValue; } function calculateRewardForUser(uint256 payoutId, uint256[7] memory squareRoots, uint256 userReputation) internal returns (address, uint256) { RewardPayoutCycle memory payout = rewardPayoutCycles[payoutId]; // Checking if payout is active require(block.timestamp - payout.blockTimestamp <= 60 days, "colony-reward-payout-not-active"); ITokenLocking tokenLocking = ITokenLocking(IColonyNetwork(colonyNetworkAddress).getTokenLocking()); uint256 userDepositTimestamp = tokenLocking.getUserLock(token, msg.sender).timestamp; uint256 userTokens = tokenLocking.getUserLock(token, msg.sender).balance; require(userDepositTimestamp < payout.blockTimestamp, "colony-reward-payout-deposit-too-recent"); require(userTokens > 0, "colony-reward-payout-invalid-user-tokens"); require(userReputation > 0, "colony-reward-payout-invalid-user-reputation"); // squareRoots[0] - square root of userReputation // squareRoots[1] - square root of userTokens // squareRoots[2] - square root of payout.colonyWideReputation // squareRoots[3] - square root of totalTokens // squareRoots[4] - square root of numerator // squareRoots[5] - square root of denominator // squareRoots[6] - square root of payout.amount require(mul(squareRoots[0], squareRoots[0]) <= userReputation, "colony-reward-payout-invalid-parameter-user-reputation"); require(mul(squareRoots[1], squareRoots[1]) <= userTokens, "colony-reward-payout-invalid-parameter-user-token"); require(mul(squareRoots[2], squareRoots[2]) >= payout.colonyWideReputation, "colony-reward-payout-invalid-parameter-total-reputation"); require(mul(squareRoots[3], squareRoots[3]) >= payout.totalTokens, "colony-reward-payout-invalid-parameter-total-tokens"); require(mul(squareRoots[6], squareRoots[6]) <= payout.amount, "colony-reward-payout-invalid-parameter-amount"); uint256 numerator = mul(squareRoots[0], squareRoots[1]); uint256 denominator = mul(squareRoots[2], squareRoots[3]); require(mul(squareRoots[4], squareRoots[4]) <= numerator, "colony-reward-payout-invalid-parameter-numerator"); require(mul(squareRoots[5], squareRoots[5]) >= denominator, "colony-reward-payout-invalid-parameter-denominator"); uint256 reward = (mul(squareRoots[4], squareRoots[6]) / squareRoots[5]) ** 2; tokenLocking.unlockTokenForUser(token, msg.sender, payoutId); return (payout.tokenAddress, reward); } function updatePayoutsWeCannotMakeAfterPotChange(uint256 _fundingPotId, address _token, uint _prev) internal { FundingPot storage tokenPot = fundingPots[_fundingPotId]; if (_prev >= tokenPot.payouts[_token]) { // If the old amount in the pot was enough to pay for the budget if (tokenPot.balance[_token] < tokenPot.payouts[_token]) { // And the new amount in the pot is not enough to pay for the budget... tokenPot.payoutsWeCannotMake += 1; // Then this is a set of payouts we cannot make that we could before. } } else { // If this 'else' is running, then the old amount in the pot could not pay for the budget if (tokenPot.balance[_token] >= tokenPot.payouts[_token]) { // And the new amount in the pot can pay for the budget tokenPot.payoutsWeCannotMake -= 1; // Then this is a set of payouts we can make that we could not before. } } } function updatePayoutsWeCannotMakeAfterBudgetChange(uint256 _fundingPotId, address _token, uint _prev) internal { FundingPot storage tokenPot = fundingPots[_fundingPotId]; if (tokenPot.balance[_token] >= _prev) { // If the amount in the pot was enough to pay for the old budget... if (tokenPot.balance[_token] < tokenPot.payouts[_token]) { // And the amount is not enough to pay for the new budget... tokenPot.payoutsWeCannotMake += 1; // Then this is a set of payouts we cannot make that we could before. } } else { // If this 'else' is running, then the amount in the pot was not enough to pay for the old budget if (tokenPot.balance[_token] >= tokenPot.payouts[_token]) { // And the amount is enough to pay for the new budget... tokenPot.payoutsWeCannotMake -= 1; // Then this is a set of payouts we can make that we could not before. } } } function setTaskPayout(uint256 _id, TaskRole _role, address _token, uint256 _amount) private taskExists(_id) taskNotComplete(_id) validPayoutAmount(_amount) { Task storage task = tasks[_id]; FundingPot storage fundingPot = fundingPots[task.fundingPotId]; assert(fundingPot.associatedType == FundingPotAssociatedType.Task); uint currentTotalAmount = fundingPot.payouts[_token]; uint currentTaskRolePayout = task.payouts[uint8(_role)][_token]; task.payouts[uint8(_role)][_token] = _amount; fundingPot.payouts[_token] = add(sub(currentTotalAmount, currentTaskRolePayout), _amount); updatePayoutsWeCannotMakeAfterBudgetChange(task.fundingPotId, _token, currentTotalAmount); } function processPayout(uint256 fundingPotId, address _token, uint256 payout, address payable user) private { fundingPots[fundingPotId].balance[_token] = sub(fundingPots[fundingPotId].balance[_token], payout); nonRewardPotsTotal[_token] = sub(nonRewardPotsTotal[_token], payout); uint fee = calculateNetworkFeeForPayout(payout); uint remainder = sub(payout, fee); if (_token == address(0x0)) { // Payout ether user.transfer(remainder); // Fee goes directly to Meta Colony IColonyNetwork colonyNetworkContract = IColonyNetwork(colonyNetworkAddress); address payable metaColonyAddress = colonyNetworkContract.getMetaColony(); metaColonyAddress.transfer(fee); } else { // Payout token // TODO: (post CCv1) If it's a whitelisted token, it goes straight to the metaColony // If it's any other token, goes to the colonyNetwork contract first to be auctioned. ERC20Extended payoutToken = ERC20Extended(_token); payoutToken.transfer(user, remainder); payoutToken.transfer(colonyNetworkAddress, fee); } fundingPots[fundingPotId].payouts[_token] = sub(fundingPots[fundingPotId].payouts[_token], payout); emit PayoutClaimed(fundingPotId, _token, remainder); } function calculateNetworkFeeForPayout(uint256 _payout) private view returns (uint256 fee) { IColonyNetwork colonyNetworkContract = IColonyNetwork(colonyNetworkAddress); uint256 feeInverse = colonyNetworkContract.getFeeInverse(); if (_payout == 0 || feeInverse == 1) { fee = _payout; } else { fee = _payout/feeInverse + 1; } } function getDomainFromFundingPot(uint256 _fundingPotId) private view returns (uint256 domainId) { require(_fundingPotId <= fundingPotCount, "colony-funding-nonexistent-pot"); FundingPot storage fundingPot = fundingPots[_fundingPotId]; if (fundingPot.associatedType == FundingPotAssociatedType.Domain) { domainId = fundingPot.associatedTypeId; } else if (fundingPot.associatedType == FundingPotAssociatedType.Task) { domainId = tasks[fundingPot.associatedTypeId].domainId; } else if (fundingPot.associatedType == FundingPotAssociatedType.Payment) { domainId = payments[fundingPot.associatedTypeId].domainId; } else { // If rewards pot, return root domain. assert(_fundingPotId == 0); domainId = 1; } } }
initialised to MAX_UINT, and cannot be set to zero via setRewardInverse, so this is a false positive. It *can* be set to 0 via recovery mode, but a) That's not why MythX is balking here and b) There's only so much we can stop people being able to do with recovery mode.
remainder = sub(toClaim, feeToPay);
12,603,071
[ 1, 6769, 5918, 358, 4552, 67, 57, 3217, 16, 471, 2780, 506, 444, 358, 3634, 3970, 444, 17631, 1060, 16376, 16, 1427, 333, 353, 279, 629, 6895, 18, 2597, 848, 506, 444, 358, 374, 3970, 11044, 1965, 16, 1496, 279, 13, 12466, 1807, 486, 11598, 8005, 451, 60, 353, 324, 2960, 310, 2674, 471, 324, 13, 6149, 1807, 1338, 1427, 9816, 732, 848, 2132, 16951, 3832, 7752, 358, 741, 598, 11044, 1965, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 10022, 273, 720, 12, 869, 9762, 16, 14036, 774, 9148, 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, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-05-25 */ /** *Submitted for verification at Etherscan.io on 2021-05-07 */ /* https://powerpool.finance/ wrrrw r wrr ppwr rrr wppr0 prwwwrp prwwwrp wr0 rr 0rrrwrrprpwp0 pp pr prrrr0 pp 0r prrrr0 0rwrrr pp pr prrrr0 prrrr0 r0 rrp pr wr00rrp prwww0 pp wr pp w00r prwwwpr 0rw prwww0 pp wr pp wr r0 r0rprprwrrrp pr0 pp wr pr pp rwwr wr 0r pp wr pr wr pr r0 prwr wrr0wpwr 00 www0 0w0ww www0 0w 00 www0 www0 0www0 wrr ww0rrrr */ // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IPiRouterFactory { function buildRouter(address _piToken, bytes calldata _args) external returns (address); } // File: contracts/interfaces/sushi/ISushiBar.sol interface ISushiBar { function enter(uint256 _amount) external; function leave(uint256 _amount) external; } // File: @powerpool/poweroracle/contracts/interfaces/IPowerPoke.sol pragma experimental ABIEncoderV2; interface IPowerPoke { /*** CLIENT'S CONTRACT INTERFACE ***/ function authorizeReporter(uint256 userId_, address pokerKey_) external view; function authorizeNonReporter(uint256 userId_, address pokerKey_) external view; function authorizeNonReporterWithDeposit( uint256 userId_, address pokerKey_, uint256 overrideMinDeposit_ ) external view; function authorizePoker(uint256 userId_, address pokerKey_) external view; function authorizePokerWithDeposit( uint256 userId_, address pokerKey_, uint256 overrideMinStake_ ) external view; function slashReporter(uint256 slasherId_, uint256 times_) external; function reward( uint256 userId_, uint256 gasUsed_, uint256 compensationPlan_, bytes calldata pokeOptions_ ) external; /*** CLIENT OWNER INTERFACE ***/ function transferClientOwnership(address client_, address to_) external; function addCredit(address client_, uint256 amount_) external; function withdrawCredit( address client_, address to_, uint256 amount_ ) external; function setReportIntervals( address client_, uint256 minReportInterval_, uint256 maxReportInterval_ ) external; function setSlasherHeartbeat(address client_, uint256 slasherHeartbeat_) external; function setGasPriceLimit(address client_, uint256 gasPriceLimit_) external; function setFixedCompensations( address client_, uint256 eth_, uint256 cvp_ ) external; function setBonusPlan( address client_, uint256 planId_, bool active_, uint64 bonusNominator_, uint64 bonusDenominator_, uint64 perGas_ ) external; function setMinimalDeposit(address client_, uint256 defaultMinDeposit_) external; /*** POKER INTERFACE ***/ function withdrawRewards(uint256 userId_, address to_) external; function setPokerKeyRewardWithdrawAllowance(uint256 userId_, bool allow_) external; /*** OWNER INTERFACE ***/ function addClient( address client_, address owner_, bool canSlash_, uint256 gasPriceLimit_, uint256 minReportInterval_, uint256 maxReportInterval_ ) external; function setClientActiveFlag(address client_, bool active_) external; function setCanSlashFlag(address client_, bool canSlash) external; function setOracle(address oracle_) external; function pause() external; function unpause() external; /*** GETTERS ***/ function creditOf(address client_) external view returns (uint256); function ownerOf(address client_) external view returns (address); function getMinMaxReportIntervals(address client_) external view returns (uint256 min, uint256 max); function getSlasherHeartbeat(address client_) external view returns (uint256); function getGasPriceLimit(address client_) external view returns (uint256); function getPokerBonus( address client_, uint256 bonusPlanId_, uint256 gasUsed_, uint256 userDeposit_ ) external view returns (uint256); function getGasPriceFor(address client_) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/interfaces/WrappedPiErc20Interface.sol interface WrappedPiErc20Interface is IERC20 { function deposit(uint256 _amount) external payable returns (uint256); function withdraw(uint256 _amount) external payable returns (uint256); function changeRouter(address _newRouter) external; function setEthFee(uint256 _newEthFee) external; function withdrawEthFee(address payable receiver) external; function approveUnderlying(address _to, uint256 _amount) external; function callExternal( address voting, bytes4 signature, bytes calldata args, uint256 value ) external; struct ExternalCallData { address destination; bytes4 signature; bytes args; uint256 value; } function callExternalMultiple(ExternalCallData[] calldata calls) external; function getUnderlyingBalance() external view returns (uint256); } // File: contracts/interfaces/IPoolRestrictions.sol interface IPoolRestrictions { function getMaxTotalSupply(address _pool) external view returns (uint256); function isVotingSignatureAllowed(address _votingAddress, bytes4 _signature) external view returns (bool); function isVotingSenderAllowed(address _votingAddress, address _sender) external view returns (bool); function isWithoutFee(address _addr) external view returns (bool); } // File: contracts/interfaces/PowerIndexBasicRouterInterface.sol interface PowerIndexBasicRouterInterface { function setVotingAndStaking(address _voting, address _staking) external; function setReserveConfig(uint256 _reserveRatio, uint256 _claimRewardsInterval) external; function getPiEquivalentForUnderlying( uint256 _underlyingAmount, IERC20 _underlyingToken, uint256 _piTotalSupply ) external view returns (uint256); function getPiEquivalentForUnderlyingPure( uint256 _underlyingAmount, uint256 _totalUnderlyingWrapped, uint256 _piTotalSupply ) external pure returns (uint256); function getUnderlyingEquivalentForPi( uint256 _piAmount, IERC20 _underlyingToken, uint256 _piTotalSupply ) external view returns (uint256); function getUnderlyingEquivalentForPiPure( uint256 _piAmount, uint256 _totalUnderlyingWrapped, uint256 _piTotalSupply ) external pure returns (uint256); } // File: contracts/interfaces/BMathInterface.sol interface BMathInterface { function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) external pure returns (uint256 tokenAmountIn); function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) external pure returns (uint256 tokenAmountIn); } // File: contracts/interfaces/BPoolInterface.sol interface BPoolInterface is IERC20, BMathInterface { function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external; function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external; function swapExactAmountIn( address, uint256, address, uint256, uint256 ) external returns (uint256, uint256); function swapExactAmountOut( address, uint256, address, uint256, uint256 ) external returns (uint256, uint256); function joinswapExternAmountIn( address, uint256, uint256 ) external returns (uint256); function joinswapPoolAmountOut( address, uint256, uint256 ) external returns (uint256); function exitswapPoolAmountIn( address, uint256, uint256 ) external returns (uint256); function exitswapExternAmountOut( address, uint256, uint256 ) external returns (uint256); function getDenormalizedWeight(address) external view returns (uint256); function getBalance(address) external view returns (uint256); function getSwapFee() external view returns (uint256); function getTotalDenormalizedWeight() external view returns (uint256); function getCommunityFee() external view returns ( uint256, uint256, uint256, address ); function calcAmountWithCommunityFee( uint256, uint256, address ) external view returns (uint256, uint256); function getRestrictions() external view returns (address); function isPublicSwap() external view returns (bool); function isFinalized() external view returns (bool); function isBound(address t) external view returns (bool); function getCurrentTokens() external view returns (address[] memory tokens); function getFinalTokens() external view returns (address[] memory tokens); function setSwapFee(uint256) external; function setCommunityFeeAndReceiver( uint256, uint256, uint256, address ) external; function setController(address) external; function setPublicSwap(bool) external; function finalize() external; function bind( address, uint256, uint256 ) external; function rebind( address, uint256, uint256 ) external; function unbind(address) external; function gulp(address) external; function callVoting( address voting, bytes4 signature, bytes calldata args, uint256 value ) external; function getMinWeight() external view returns (uint256); function getMaxBoundTokens() external view returns (uint256); } // File: @openzeppelin/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/interfaces/PowerIndexNaiveRouterInterface.sol interface PowerIndexNaiveRouterInterface { function migrateToNewRouter( address _piToken, address payable _newRouter, address[] memory _tokens ) external; function piTokenCallback(address sender, uint256 _withdrawAmount) external payable; } // File: contracts/powerindex-router/PowerIndexNaiveRouter.sol contract PowerIndexNaiveRouter is PowerIndexNaiveRouterInterface, Ownable { using SafeMath for uint256; function migrateToNewRouter( address _piToken, address payable _newRouter, address[] memory _tokens ) public virtual override onlyOwner { WrappedPiErc20Interface(_piToken).changeRouter(_newRouter); } function piTokenCallback(address sender, uint256 _withdrawAmount) external payable virtual override { // DO NOTHING } } // File: contracts/powerindex-router/PowerIndexBasicRouter.sol contract PowerIndexBasicRouter is PowerIndexBasicRouterInterface, PowerIndexNaiveRouter { using SafeERC20 for IERC20; uint256 public constant HUNDRED_PCT = 1 ether; event SetVotingAndStaking(address indexed voting, address indexed staking); event SetReserveConfig(uint256 ratio, uint256 claimRewardsInterval); event SetRebalancingInterval(uint256 rebalancingInterval); event IgnoreRebalancing(uint256 blockTimestamp, uint256 lastRebalancedAt, uint256 rebalancingInterval); event RewardPool(address indexed pool, uint256 amount); event SetRewardPools(uint256 len, address[] rewardPools); event SetPvpFee(uint256 pvpFee); enum ReserveStatus { EQUILIBRIUM, SHORTAGE, EXCESS } struct BasicConfig { address poolRestrictions; address powerPoke; address voting; address staking; uint256 reserveRatio; uint256 reserveRatioToForceRebalance; uint256 claimRewardsInterval; address pvp; uint256 pvpFee; address[] rewardPools; } WrappedPiErc20Interface public immutable piToken; address public immutable pvp; IPoolRestrictions public poolRestrictions; IPowerPoke public powerPoke; address public voting; address public staking; uint256 public reserveRatio; uint256 public claimRewardsInterval; uint256 public lastClaimRewardsAt; uint256 public lastRebalancedAt; uint256 public reserveRatioToForceRebalance; // 1 ether == 100% uint256 public pvpFee; address[] internal rewardPools; uint256 internal constant COMPENSATION_PLAN_1_ID = 1; modifier onlyPiToken() { require(msg.sender == address(piToken), "ONLY_PI_TOKEN_ALLOWED"); _; } modifier onlyEOA() { require(tx.origin == msg.sender, "ONLY_EOA"); _; } modifier onlyReporter(uint256 _reporterId, bytes calldata _rewardOpts) { uint256 gasStart = gasleft(); powerPoke.authorizeReporter(_reporterId, msg.sender); _; _reward(_reporterId, gasStart, COMPENSATION_PLAN_1_ID, _rewardOpts); } modifier onlyNonReporter(uint256 _reporterId, bytes calldata _rewardOpts) { uint256 gasStart = gasleft(); powerPoke.authorizeNonReporter(_reporterId, msg.sender); _; _reward(_reporterId, gasStart, COMPENSATION_PLAN_1_ID, _rewardOpts); } constructor(address _piToken, BasicConfig memory _basicConfig) public PowerIndexNaiveRouter() Ownable() { require(_piToken != address(0), "INVALID_PI_TOKEN"); require(_basicConfig.reserveRatio <= HUNDRED_PCT, "RR_GT_HUNDRED_PCT"); require(_basicConfig.pvpFee < HUNDRED_PCT, "PVP_FEE_GTE_HUNDRED_PCT"); require(_basicConfig.pvp != address(0), "INVALID_PVP_ADDR"); require(_basicConfig.poolRestrictions != address(0), "INVALID_POOL_RESTRICTIONS_ADDR"); piToken = WrappedPiErc20Interface(_piToken); poolRestrictions = IPoolRestrictions(_basicConfig.poolRestrictions); powerPoke = IPowerPoke(_basicConfig.powerPoke); voting = _basicConfig.voting; staking = _basicConfig.staking; reserveRatio = _basicConfig.reserveRatio; reserveRatioToForceRebalance = _basicConfig.reserveRatioToForceRebalance; claimRewardsInterval = _basicConfig.claimRewardsInterval; pvp = _basicConfig.pvp; pvpFee = _basicConfig.pvpFee; rewardPools = _basicConfig.rewardPools; } receive() external payable {} /*** OWNER METHODS ***/ /** * @dev Changing the staking address with a positive underlying stake will break `getPiEquivalentForUnderlying` * formula. Consider moving all the reserves to the piToken contract before doing this. */ function setVotingAndStaking(address _voting, address _staking) external override onlyOwner { voting = _voting; staking = _staking; emit SetVotingAndStaking(_voting, _staking); } function setReserveConfig(uint256 _reserveRatio, uint256 _claimRewardsInterval) public virtual override onlyOwner { require(_reserveRatio <= HUNDRED_PCT, "RR_GREATER_THAN_100_PCT"); reserveRatio = _reserveRatio; claimRewardsInterval = _claimRewardsInterval; emit SetReserveConfig(_reserveRatio, _claimRewardsInterval); } function setRewardPools(address[] calldata _rewardPools) external onlyOwner { require(_rewardPools.length > 0, "AT_LEAST_ONE_EXPECTED"); rewardPools = _rewardPools; emit SetRewardPools(_rewardPools.length, _rewardPools); } function setPvpFee(uint256 _pvpFee) external onlyOwner { require(_pvpFee < HUNDRED_PCT, "PVP_FEE_OVER_THE_LIMIT"); pvpFee = _pvpFee; emit SetPvpFee(_pvpFee); } function setPiTokenEthFee(uint256 _ethFee) external onlyOwner { require(_ethFee <= 0.1 ether, "ETH_FEE_OVER_THE_LIMIT"); piToken.setEthFee(_ethFee); } function withdrawEthFee(address payable _receiver) external onlyOwner { piToken.withdrawEthFee(_receiver); } function migrateToNewRouter( address _piToken, address payable _newRouter, address[] memory _tokens ) public override onlyOwner { super.migrateToNewRouter(_piToken, _newRouter, _tokens); _newRouter.transfer(address(this).balance); uint256 len = _tokens.length; for (uint256 i = 0; i < len; i++) { IERC20 t = IERC20(_tokens[i]); t.safeTransfer(_newRouter, t.balanceOf(address(this))); } } function pokeFromReporter( uint256 _reporterId, bool _claimAndDistributeRewards, bytes calldata _rewardOpts ) external onlyReporter(_reporterId, _rewardOpts) onlyEOA { (uint256 minInterval, ) = _getMinMaxReportInterval(); (ReserveStatus status, uint256 diff, bool forceRebalance) = getReserveStatus(_getUnderlyingStaked(), 0); require(forceRebalance || lastRebalancedAt + minInterval < block.timestamp, "MIN_INTERVAL_NOT_REACHED"); require(status != ReserveStatus.EQUILIBRIUM, "RESERVE_STATUS_EQUILIBRIUM"); _rebalancePoke(status, diff); _postPoke(_claimAndDistributeRewards); } function pokeFromSlasher( uint256 _reporterId, bool _claimAndDistributeRewards, bytes calldata _rewardOpts ) external onlyNonReporter(_reporterId, _rewardOpts) onlyEOA { (, uint256 maxInterval) = _getMinMaxReportInterval(); (ReserveStatus status, uint256 diff, bool forceRebalance) = getReserveStatus(_getUnderlyingStaked(), 0); require(forceRebalance || lastRebalancedAt + maxInterval < block.timestamp, "MAX_INTERVAL_NOT_REACHED"); require(status != ReserveStatus.EQUILIBRIUM, "RESERVE_STATUS_EQUILIBRIUM"); _rebalancePoke(status, diff); _postPoke(_claimAndDistributeRewards); } function poke(bool _claimAndDistributeRewards) external onlyEOA { (ReserveStatus status, uint256 diff, ) = getReserveStatus(_getUnderlyingStaked(), 0); _rebalancePoke(status, diff); _postPoke(_claimAndDistributeRewards); } function _postPoke(bool _claimAndDistributeRewards) internal { lastRebalancedAt = block.timestamp; if (_claimAndDistributeRewards && lastClaimRewardsAt + claimRewardsInterval < block.timestamp) { _claimRewards(); _distributeRewards(); lastClaimRewardsAt = block.timestamp; } } function _rebalancePoke(ReserveStatus reserveStatus, uint256 sushiDiff) internal virtual { // need to redefine in implementation } function _claimRewards() internal virtual { // need to redefine in implementation } function _distributeRewards() internal virtual { // need to redefine in implementation } function _callVoting(bytes4 _sig, bytes memory _data) internal { piToken.callExternal(voting, _sig, _data, 0); } function _callStaking(bytes4 _sig, bytes memory _data) internal { piToken.callExternal(staking, _sig, _data, 0); } function _checkVotingSenderAllowed() internal view { require(poolRestrictions.isVotingSenderAllowed(voting, msg.sender), "SENDER_NOT_ALLOWED"); } function _distributeRewardToPvp(uint256 _totalReward, IERC20 _underlying) internal returns (uint256 pvpReward, uint256 remainder) { pvpReward = 0; remainder = 0; if (pvpFee > 0) { pvpReward = _totalReward.mul(pvpFee).div(HUNDRED_PCT); remainder = _totalReward.sub(pvpReward); _underlying.safeTransfer(pvp, pvpReward); } else { remainder = _totalReward; } } function _distributePiRemainderToPools(IERC20 _piToken) internal returns (uint256 piBalanceToDistribute, address[] memory pools) { pools = rewardPools; uint256 poolsLen = pools.length; require(poolsLen > 0, "MISSING_REWARD_POOLS"); piBalanceToDistribute = piToken.balanceOf(address(this)); require(piBalanceToDistribute > 0, "NO_POOL_REWARDS_PI"); uint256 totalPiOnPools = 0; for (uint256 i = 0; i < poolsLen; i++) { totalPiOnPools = totalPiOnPools.add(_piToken.balanceOf(pools[i])); } require(totalPiOnPools > 0, "TOTAL_PI_IS_0"); for (uint256 i = 0; i < poolsLen; i++) { address pool = pools[i]; uint256 poolPiBalance = piToken.balanceOf(pool); if (poolPiBalance == 0) { continue; } uint256 poolReward = piBalanceToDistribute.mul(poolPiBalance) / totalPiOnPools; piToken.transfer(pool, poolReward); BPoolInterface(pool).gulp(address(piToken)); emit RewardPool(pool, poolReward); } } /* * @dev Getting status and diff of actual staked balance and target reserve balance. */ function getReserveStatusForStakedBalance() public view returns ( ReserveStatus status, uint256 diff, bool forceRebalance ) { return getReserveStatus(_getUnderlyingStaked(), 0); } /* * @dev Getting status and diff of provided staked balance and target reserve balance. */ function getReserveStatus(uint256 _stakedBalance, uint256 _withdrawAmount) public view returns ( ReserveStatus status, uint256 diff, bool forceRebalance ) { uint256 expectedReserveAmount; (status, diff, expectedReserveAmount) = getReserveStatusPure( reserveRatio, piToken.getUnderlyingBalance(), _stakedBalance, _withdrawAmount ); if (status == ReserveStatus.SHORTAGE) { uint256 currentRatio = expectedReserveAmount.sub(diff).mul(HUNDRED_PCT).div(expectedReserveAmount); forceRebalance = reserveRatioToForceRebalance >= currentRatio; } } // NOTICE: could/should be changed depending on implementation function _getUnderlyingStaked() internal view virtual returns (uint256) { if (staking == address(0)) { return 0; } return IERC20(staking).balanceOf(address(piToken)); } function getUnderlyingStaked() external view returns (uint256) { return _getUnderlyingStaked(); } function getRewardPools() external view returns (address[] memory) { return rewardPools; } function getPiEquivalentForUnderlying( uint256 _underlyingAmount, IERC20 _underlyingToken, uint256 _piTotalSupply ) public view virtual override returns (uint256) { uint256 underlyingOnPiToken = _underlyingToken.balanceOf(address(piToken)); return getPiEquivalentForUnderlyingPure( _underlyingAmount, // underlyingOnPiToken + underlyingOnStaking, underlyingOnPiToken.add(_getUnderlyingStaked()), _piTotalSupply ); } function getPiEquivalentForUnderlyingPure( uint256 _underlyingAmount, uint256 _totalUnderlyingWrapped, uint256 _piTotalSupply ) public pure virtual override returns (uint256) { if (_piTotalSupply == 0) { return _underlyingAmount; } // return _piTotalSupply * _underlyingAmount / _totalUnderlyingWrapped; return _piTotalSupply.mul(_underlyingAmount).div(_totalUnderlyingWrapped); } function getUnderlyingEquivalentForPi( uint256 _piAmount, IERC20 _underlyingToken, uint256 _piTotalSupply ) public view virtual override returns (uint256) { uint256 underlyingOnPiToken = _underlyingToken.balanceOf(address(piToken)); return getUnderlyingEquivalentForPiPure( _piAmount, // underlyingOnPiToken + underlyingOnStaking, underlyingOnPiToken.add(_getUnderlyingStaked()), _piTotalSupply ); } function getUnderlyingEquivalentForPiPure( uint256 _piAmount, uint256 _totalUnderlyingWrapped, uint256 _piTotalSupply ) public pure virtual override returns (uint256) { if (_piTotalSupply == 0) { return _piAmount; } // _piAmount * _totalUnderlyingWrapped / _piTotalSupply; return _totalUnderlyingWrapped.mul(_piAmount).div(_piTotalSupply); } /** * @notice Calculates the desired reserve status * @param _reserveRatioPct The reserve ratio in %, 1 ether == 100 ether * @param _leftOnPiToken The amount of origin tokens left on the piToken (WrappedPiErc20) contract * @param _stakedBalance The amount of original tokens staked on the staking contract * @param _withdrawAmount The amount to be withdrawn within the current transaction * (could be negative in a case of deposit) * @return status The reserve status: * * SHORTAGE - There is not enough underlying funds on the wrapper contract to satisfy the reserve ratio, * the diff amount should be redeemed from the staking contract * * EXCESS - there are some extra funds over reserve ratio on the wrapper contract, * the diff amount should be sent to the staking contract * * EQUILIBRIUM - the reserve ratio hasn't changed, * the diff amount is 0 and there are no additional stake/redeem actions expected * @return diff The difference between `adjustedReserveAmount` and `_leftOnWrapper` * @return expectedReserveAmount The calculated expected reserve amount */ function getReserveStatusPure( uint256 _reserveRatioPct, uint256 _leftOnPiToken, uint256 _stakedBalance, uint256 _withdrawAmount ) public pure returns ( ReserveStatus status, uint256 diff, uint256 expectedReserveAmount ) { require(_reserveRatioPct <= HUNDRED_PCT, "RR_GREATER_THAN_100_PCT"); expectedReserveAmount = getExpectedReserveAmount(_reserveRatioPct, _leftOnPiToken, _stakedBalance, _withdrawAmount); if (expectedReserveAmount > _leftOnPiToken) { status = ReserveStatus.SHORTAGE; diff = expectedReserveAmount.sub(_leftOnPiToken); } else if (expectedReserveAmount < _leftOnPiToken) { status = ReserveStatus.EXCESS; diff = _leftOnPiToken.sub(expectedReserveAmount); } else { status = ReserveStatus.EQUILIBRIUM; diff = 0; } } /** * @notice Calculates an expected reserve amount after the transaction taking into an account the withdrawAmount * @param _reserveRatioPct % of a reserve ratio, 1 ether == 100% * @param _leftOnPiToken The amount of origin tokens left on the piToken (WrappedPiErc20) contract * @param _stakedBalance The amount of original tokens staked on the staking contract * @param _withdrawAmount The amount to be withdrawn within the current transaction * (could be negative in a case of deposit) * @return expectedReserveAmount The expected reserve amount * * / %reserveRatio * (staked + _leftOnPiToken - withdrawAmount) \ * expectedReserveAmount = | ------------------------------------------------------------| + withdrawAmount * \ 100% / */ function getExpectedReserveAmount( uint256 _reserveRatioPct, uint256 _leftOnPiToken, uint256 _stakedBalance, uint256 _withdrawAmount ) public pure returns (uint256) { return _reserveRatioPct.mul(_stakedBalance.add(_leftOnPiToken).sub(_withdrawAmount)).div(HUNDRED_PCT).add( _withdrawAmount ); } function _reward( uint256 _reporterId, uint256 _gasStart, uint256 _compensationPlan, bytes calldata _rewardOpts ) internal { powerPoke.reward(_reporterId, _gasStart.sub(gasleft()), _compensationPlan, _rewardOpts); } function _getMinMaxReportInterval() internal view returns (uint256 min, uint256 max) { return powerPoke.getMinMaxReportIntervals(address(this)); } } // File: contracts/powerindex-router/implementations/SushiPowerIndexRouter.sol contract SushiPowerIndexRouter is PowerIndexBasicRouter { event Stake(address indexed sender, uint256 amount); event Redeem(address indexed sender, uint256 amount); event IgnoreDueMissingStaking(); event ClaimRewards( address indexed sender, uint256 xSushiBurned, uint256 expectedSushiReward, uint256 releasedSushiReward ); event DistributeRewards( address indexed sender, uint256 sushiReward, uint256 pvpReward, uint256 poolRewardsUnderlying, uint256 poolRewardsPi, address[] pools ); struct SushiConfig { address SUSHI; } IERC20 internal immutable SUSHI; constructor( address _piToken, BasicConfig memory _basicConfig, SushiConfig memory _sushiConfig ) public PowerIndexBasicRouter(_piToken, _basicConfig) { SUSHI = IERC20(_sushiConfig.SUSHI); } /*** PERMISSIONLESS REWARD CLAIMING AND DISTRIBUTION ***/ /** * @notice Withdraws the extra staked SUSHI as a reward and transfers it to the router */ function _claimRewards() internal override { uint256 rewardsPending = getPendingRewards(); require(rewardsPending > 0, "NOTHING_TO_CLAIM"); uint256 sushiBefore = SUSHI.balanceOf(address(piToken)); uint256 xSushiToBurn = getXSushiForSushi(rewardsPending); // Step #1. Claim the excess of SUSHI from SushiBar _callStaking(ISushiBar.leave.selector, abi.encode(xSushiToBurn)); uint256 released = SUSHI.balanceOf(address(piToken)).sub(sushiBefore); require(released > 0, "NOTHING_RELEASED"); // Step #2. Transfer the claimed SUSHI to the router piToken.callExternal(address(SUSHI), SUSHI.transfer.selector, abi.encode(address(this), released), 0); emit ClaimRewards(msg.sender, xSushiToBurn, rewardsPending, released); } /** * @notice Wraps the router's SUSHIs into piTokens and transfers it to the pools proportionally their SUSHI balances */ function _distributeRewards() internal override { uint256 pendingReward = SUSHI.balanceOf(address(this)); require(pendingReward > 0, "NO_PENDING_REWARD"); // Step #1. Distribute pvpReward (uint256 pvpReward, uint256 poolRewardsUnderlying) = _distributeRewardToPvp(pendingReward, SUSHI); require(poolRewardsUnderlying > 0, "NO_POOL_REWARDS_UNDERLYING"); // Step #2. Wrap SUSHI into piSUSHI SUSHI.approve(address(piToken), poolRewardsUnderlying); piToken.deposit(poolRewardsUnderlying); // Step #3. Distribute piSUSHI over the pools (uint256 poolRewardsPi, address[] memory pools) = _distributePiRemainderToPools(piToken); emit DistributeRewards(msg.sender, pendingReward, pvpReward, poolRewardsUnderlying, poolRewardsPi, pools); } /*** VIEWERS ***/ /** * @notice Get the amount of xSUSHI tokens SushiBar will mint in exchange of the given SUSHI tokens * @param _sushi The input amount of SUSHI tokens * @return The corresponding amount of xSUSHI tokens */ function getXSushiForSushi(uint256 _sushi) public view returns (uint256) { return _sushi.mul(IERC20(staking).totalSupply()) / SUSHI.balanceOf(staking); } /** * @notice Get the amount of SUSHI tokens SushiBar will release in exchange of the given xSUSHI tokens * @param _xSushi The input amount of xSUSHI tokens * @return The corresponding amount of SUSHI tokens */ function getSushiForXSushi(uint256 _xSushi) public view returns (uint256) { return _xSushi.mul(SUSHI.balanceOf(staking)) / IERC20(staking).totalSupply(); } /** * @notice Get the total amount of SUSHI tokens could be released in exchange of the piToken's xSUSHI balance. * Is comprised of the underlyingStaked and the pendingRewards. * @return The SUSHI amount */ function getUnderlyingBackedByXSushi() public view returns (uint256) { if (staking == address(0)) { return 0; } uint256 xSushiAtPiToken = IERC20(staking).balanceOf(address(piToken)); if (xSushiAtPiToken == 0) { return 0; } return getSushiForXSushi(xSushiAtPiToken); } /** * @notice Get the amount of current pending rewards available at SushiBar * @return amount of pending rewards */ function getPendingRewards() public view returns (uint256 amount) { // return sushiAtPiToken + sushiBackedByXSushi - piToken.totalSupply() amount = SUSHI.balanceOf(address(piToken)).add(getUnderlyingBackedByXSushi()).add(1).sub(piToken.totalSupply()); return amount == 1 ? 0 : amount; } /*** EQUIVALENT METHODS OVERRIDES ***/ function getPiEquivalentForUnderlying( uint256 _underlyingAmount, IERC20, /* _underlyingToken */ uint256 /* _piTotalSupply */ ) public view override returns (uint256) { return _underlyingAmount; } function getPiEquivalentForUnderlyingPure( uint256 _underlyingAmount, uint256, /* _totalUnderlyingWrapped */ uint256 /* _piTotalSupply */ ) public pure override returns (uint256) { return _underlyingAmount; } function getUnderlyingEquivalentForPi( uint256 _piAmount, IERC20, /* _underlyingToken */ uint256 /* _piTotalSupply */ ) public view override returns (uint256) { return _piAmount; } function getUnderlyingEquivalentForPiPure( uint256 _piAmount, uint256, /* _totalUnderlyingWrapped */ uint256 /* _piTotalSupply */ ) public pure override returns (uint256) { return _piAmount; } /*** OWNER METHODS ***/ /** * @notice The contract owner manually stakes the given amount of SUSHI * @param _sushi The amount SUSHI to stake */ function stake(uint256 _sushi) external onlyOwner { _stake(_sushi); } /** * @notice The contract owner manually burns the given amount of xSUSHI in exchange of SUSHI tokens * @param _xSushi The amount xSUSHI to burn */ function redeem(uint256 _xSushi) external onlyOwner { _redeem(_xSushi); } /*** POKE FUNCTION ***/ function _rebalancePoke(ReserveStatus reserveStatus, uint256 sushiDiff) internal override { require(staking != address(0), "STACKING_IS_NULL"); if (reserveStatus == ReserveStatus.SHORTAGE) { _redeem(getXSushiForSushi(sushiDiff)); } else if (reserveStatus == ReserveStatus.EXCESS) { _stake(sushiDiff); } } /*** INTERNALS ***/ /** * @notice Get the opposite to the reserve ratio amount of SUSHI staked at SushiBar * @return The SUSHI amount */ function _getUnderlyingStaked() internal view override returns (uint256) { // return piTokenTotalSupply - sushiAtPiToken return piToken.totalSupply().sub(SUSHI.balanceOf(address(piToken))); } function _stake(uint256 _sushi) internal { require(_sushi > 0, "CANT_STAKE_0"); piToken.approveUnderlying(staking, _sushi); _callStaking(ISushiBar(0).enter.selector, abi.encode(_sushi)); emit Stake(msg.sender, _sushi); } function _redeem(uint256 _xSushi) internal { require(_xSushi > 0, "CANT_REDEEM_0"); _callStaking(ISushiBar(0).leave.selector, abi.encode(_xSushi)); emit Redeem(msg.sender, _xSushi); } }
underlyingOnPiToken + underlyingOnStaking,
function getPiEquivalentForUnderlying( uint256 _underlyingAmount, IERC20 _underlyingToken, uint256 _piTotalSupply ) public view virtual override returns (uint256) { uint256 underlyingOnPiToken = _underlyingToken.balanceOf(address(piToken)); return getPiEquivalentForUnderlyingPure( _underlyingAmount, underlyingOnPiToken.add(_getUnderlyingStaked()), _piTotalSupply ); }
2,199,728
[ 1, 9341, 6291, 1398, 16539, 1345, 397, 6808, 1398, 510, 6159, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1689, 77, 22606, 1290, 14655, 6291, 12, 203, 565, 2254, 5034, 389, 9341, 6291, 6275, 16, 203, 565, 467, 654, 39, 3462, 389, 9341, 6291, 1345, 16, 203, 565, 2254, 5034, 389, 7259, 5269, 3088, 1283, 203, 225, 262, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 6808, 1398, 16539, 1345, 273, 389, 9341, 6291, 1345, 18, 12296, 951, 12, 2867, 12, 7259, 1345, 10019, 203, 565, 327, 203, 565, 1689, 77, 22606, 1290, 14655, 6291, 13645, 12, 203, 1377, 389, 9341, 6291, 6275, 16, 203, 1377, 6808, 1398, 16539, 1345, 18, 1289, 24899, 588, 14655, 6291, 510, 9477, 1435, 3631, 203, 1377, 389, 7259, 5269, 3088, 1283, 203, 565, 11272, 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 ]
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract SyscoinDepositsManager { using SafeMath for uint; mapping(address => uint) public deposits; event DepositMade(address who, uint amount); event DepositWithdrawn(address who, uint amount); // @dev – fallback to calling makeDeposit when ether is sent directly to contract. function() public payable { makeDeposit(); } // @dev – returns an account's deposit // @param who – the account's address. // @return – the account's deposit. function getDeposit(address who) constant public returns (uint) { return deposits[who]; } // @dev – allows a user to deposit eth. // @return – sender's updated deposit amount. function makeDeposit() public payable returns (uint) { increaseDeposit(msg.sender, msg.value); return deposits[msg.sender]; } // @dev – increases an account's deposit. // @return – the given user's updated deposit amount. function increaseDeposit(address who, uint amount) internal { deposits[who] = deposits[who].add(amount); require(deposits[who] <= address(this).balance); emit DepositMade(who, amount); } // @dev – allows a user to withdraw eth from their deposit. // @param amount – how much eth to withdraw // @return – sender's updated deposit amount. function withdrawDeposit(uint amount) public returns (uint) { require(deposits[msg.sender] >= amount); deposits[msg.sender] = deposits[msg.sender].sub(amount); msg.sender.transfer(amount); emit DepositWithdrawn(msg.sender, amount); return deposits[msg.sender]; } } // Interface contract to be implemented by SyscoinToken contract SyscoinTransactionProcessor { function processTransaction(uint txHash, uint value, address destinationAddress, uint32 _assetGUID, address superblockSubmitterAddress) public returns (uint); function burn(uint _value, uint32 _assetGUID, bytes syscoinWitnessProgram) payable public returns (bool success); } // Bitcoin transaction parsing library - modified for SYSCOIN // Copyright 2016 rain <https://keybase.io/rain> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // https://en.bitcoin.it/wiki/Protocol_documentation#tx // // Raw Bitcoin transaction structure: // // field | size | type | description // version | 4 | int32 | transaction version number // n_tx_in | 1-9 | var_int | number of transaction inputs // tx_in | 41+ | tx_in[] | list of transaction inputs // n_tx_out | 1-9 | var_int | number of transaction outputs // tx_out | 9+ | tx_out[] | list of transaction outputs // lock_time | 4 | uint32 | block number / timestamp at which tx locked // // Transaction input (tx_in) structure: // // field | size | type | description // previous | 36 | outpoint | Previous output transaction reference // script_len | 1-9 | var_int | Length of the signature script // sig_script | ? | uchar[] | Script for confirming transaction authorization // sequence | 4 | uint32 | Sender transaction version // // OutPoint structure: // // field | size | type | description // hash | 32 | char[32] | The hash of the referenced transaction // index | 4 | uint32 | The index of this output in the referenced transaction // // Transaction output (tx_out) structure: // // field | size | type | description // value | 8 | int64 | Transaction value (Satoshis) // pk_script_len | 1-9 | var_int | Length of the public key script // pk_script | ? | uchar[] | Public key as a Bitcoin script. // // Variable integers (var_int) can be encoded differently depending // on the represented value, to save space. Variable integers always // precede an array of a variable length data type (e.g. tx_in). // // Variable integer encodings as a function of represented value: // // value | bytes | format // <0xFD (253) | 1 | uint8 // <=0xFFFF (65535)| 3 | 0xFD followed by length as uint16 // <=0xFFFF FFFF | 5 | 0xFE followed by length as uint32 // - | 9 | 0xFF followed by length as uint64 // // Public key scripts `pk_script` are set on the output and can // take a number of forms. The regular transaction script is // called 'pay-to-pubkey-hash' (P2PKH): // // OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG // // OP_x are Bitcoin script opcodes. The bytes representation (including // the 0x14 20-byte stack push) is: // // 0x76 0xA9 0x14 <pubKeyHash> 0x88 0xAC // // The <pubKeyHash> is the ripemd160 hash of the sha256 hash of // the public key, preceded by a network version byte. (21 bytes total) // // Network version bytes: 0x00 (mainnet); 0x6f (testnet); 0x34 (namecoin) // // The Bitcoin address is derived from the pubKeyHash. The binary form is the // pubKeyHash, plus a checksum at the end. The checksum is the first 4 bytes // of the (32 byte) double sha256 of the pubKeyHash. (25 bytes total) // This is converted to base58 to form the publicly used Bitcoin address. // Mainnet P2PKH transaction scripts are to addresses beginning with '1'. // // P2SH ('pay to script hash') scripts only supply a script hash. The spender // must then provide the script that would allow them to redeem this output. // This allows for arbitrarily complex scripts to be funded using only a // hash of the script, and moves the onus on providing the script from // the spender to the redeemer. // // The P2SH script format is simple: // // OP_HASH160 <scriptHash> OP_EQUAL // // 0xA9 0x14 <scriptHash> 0x87 // // The <scriptHash> is the ripemd160 hash of the sha256 hash of the // redeem script. The P2SH address is derived from the scriptHash. // Addresses are the scriptHash with a version prefix of 5, encoded as // Base58check. These addresses begin with a '3'. // parse a raw Syscoin transaction byte array library SyscoinMessageLibrary { uint constant p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f; // secp256k1 uint constant q = (p + 1) / 4; // Error codes uint constant ERR_INVALID_HEADER = 10050; uint constant ERR_COINBASE_INDEX = 10060; // coinbase tx index within Litecoin merkle isn't 0 uint constant ERR_NOT_MERGE_MINED = 10070; // trying to check AuxPoW on a block that wasn't merge mined uint constant ERR_FOUND_TWICE = 10080; // 0xfabe6d6d found twice uint constant ERR_NO_MERGE_HEADER = 10090; // 0xfabe6d6d not found uint constant ERR_NOT_IN_FIRST_20 = 10100; // chain Merkle root isn't in the first 20 bytes of coinbase tx uint constant ERR_CHAIN_MERKLE = 10110; uint constant ERR_PARENT_MERKLE = 10120; uint constant ERR_PROOF_OF_WORK = 10130; uint constant ERR_INVALID_HEADER_HASH = 10140; uint constant ERR_PROOF_OF_WORK_AUXPOW = 10150; uint constant ERR_PARSE_TX_OUTPUT_LENGTH = 10160; uint constant ERR_PARSE_TX_SYS = 10170; enum Network { MAINNET, TESTNET, REGTEST } uint32 constant SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN = 0x7407; uint32 constant SYSCOIN_TX_VERSION_BURN = 0x7401; // AuxPoW block fields struct AuxPoW { uint blockHash; uint txHash; uint coinbaseMerkleRoot; // Merkle root of auxiliary block hash tree; stored in coinbase tx field uint[] chainMerkleProof; // proves that a given Syscoin block hash belongs to a tree with the above root uint syscoinHashIndex; // index of Syscoin block hash within block hash tree uint coinbaseMerkleRootCode; // encodes whether or not the root was found properly uint parentMerkleRoot; // Merkle root of transaction tree from parent Litecoin block header uint[] parentMerkleProof; // proves that coinbase tx belongs to a tree with the above root uint coinbaseTxIndex; // index of coinbase tx within Litecoin tx tree uint parentNonce; } // Syscoin block header stored as a struct, mostly for readability purposes. // BlockHeader structs can be obtained by parsing a block header's first 80 bytes // with parseHeaderBytes. struct BlockHeader { uint32 bits; uint blockHash; } // Convert a variable integer into something useful and return it and // the index to after it. function parseVarInt(bytes memory txBytes, uint pos) private pure returns (uint, uint) { // the first byte tells us how big the integer is uint8 ibit = uint8(txBytes[pos]); pos += 1; // skip ibit if (ibit < 0xfd) { return (ibit, pos); } else if (ibit == 0xfd) { return (getBytesLE(txBytes, pos, 16), pos + 2); } else if (ibit == 0xfe) { return (getBytesLE(txBytes, pos, 32), pos + 4); } else if (ibit == 0xff) { return (getBytesLE(txBytes, pos, 64), pos + 8); } } // convert little endian bytes to uint function getBytesLE(bytes memory data, uint pos, uint bits) internal pure returns (uint) { if (bits == 8) { return uint8(data[pos]); } else if (bits == 16) { return uint16(data[pos]) + uint16(data[pos + 1]) * 2 ** 8; } else if (bits == 32) { return uint32(data[pos]) + uint32(data[pos + 1]) * 2 ** 8 + uint32(data[pos + 2]) * 2 ** 16 + uint32(data[pos + 3]) * 2 ** 24; } else if (bits == 64) { return uint64(data[pos]) + uint64(data[pos + 1]) * 2 ** 8 + uint64(data[pos + 2]) * 2 ** 16 + uint64(data[pos + 3]) * 2 ** 24 + uint64(data[pos + 4]) * 2 ** 32 + uint64(data[pos + 5]) * 2 ** 40 + uint64(data[pos + 6]) * 2 ** 48 + uint64(data[pos + 7]) * 2 ** 56; } } // @dev - Parses a syscoin tx // // @param txBytes - tx byte array // Outputs // @return output_value - amount sent to the lock address in satoshis // @return destinationAddress - ethereum destination address function parseTransaction(bytes memory txBytes) internal pure returns (uint, uint, address, uint32) { uint output_value; uint32 assetGUID; address destinationAddress; uint32 version; uint pos = 0; version = bytesToUint32Flipped(txBytes, pos); if(version != SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN && version != SYSCOIN_TX_VERSION_BURN){ return (ERR_PARSE_TX_SYS, output_value, destinationAddress, assetGUID); } pos = skipInputs(txBytes, 4); (output_value, destinationAddress, assetGUID) = scanBurns(txBytes, version, pos); return (0, output_value, destinationAddress, assetGUID); } // skips witnesses and saves first script position/script length to extract pubkey of first witness scriptSig function skipWitnesses(bytes memory txBytes, uint pos, uint n_inputs) private pure returns (uint) { uint n_stack; (n_stack, pos) = parseVarInt(txBytes, pos); uint script_len; for (uint i = 0; i < n_inputs; i++) { for (uint j = 0; j < n_stack; j++) { (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len; } } return n_stack; } function skipInputs(bytes memory txBytes, uint pos) private pure returns (uint) { uint n_inputs; uint script_len; (n_inputs, pos) = parseVarInt(txBytes, pos); // if dummy 0x00 is present this is a witness transaction if(n_inputs == 0x00){ (n_inputs, pos) = parseVarInt(txBytes, pos); // flag assert(n_inputs != 0x00); // after dummy/flag the real var int comes for txins (n_inputs, pos) = parseVarInt(txBytes, pos); } require(n_inputs < 100); for (uint i = 0; i < n_inputs; i++) { pos += 36; // skip outpoint (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len + 4; // skip sig_script, seq } return pos; } // scan the burn outputs and return the value and script data of first burned output. function scanBurns(bytes memory txBytes, uint32 version, uint pos) private pure returns (uint, address, uint32) { uint script_len; uint output_value; uint32 assetGUID = 0; address destinationAddress; uint n_outputs; (n_outputs, pos) = parseVarInt(txBytes, pos); require(n_outputs < 10); for (uint i = 0; i < n_outputs; i++) { // output if(version == SYSCOIN_TX_VERSION_BURN){ output_value = getBytesLE(txBytes, pos, 64); } pos += 8; // varint (script_len, pos) = parseVarInt(txBytes, pos); if(!isOpReturn(txBytes, pos)){ // output script pos += script_len; output_value = 0; continue; } // skip opreturn marker pos += 1; if(version == SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN){ (output_value, destinationAddress, assetGUID) = scanAssetDetails(txBytes, pos); } else if(version == SYSCOIN_TX_VERSION_BURN){ destinationAddress = scanSyscoinDetails(txBytes, pos); } // only one opreturn data allowed per transaction break; } return (output_value, destinationAddress, assetGUID); } function skipOutputs(bytes memory txBytes, uint pos) private pure returns (uint) { uint n_outputs; uint script_len; (n_outputs, pos) = parseVarInt(txBytes, pos); require(n_outputs < 10); for (uint i = 0; i < n_outputs; i++) { pos += 8; (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len; } return pos; } // get final position of inputs, outputs and lock time // this is a helper function to slice a byte array and hash the inputs, outputs and lock time function getSlicePos(bytes memory txBytes, uint pos) private pure returns (uint slicePos) { slicePos = skipInputs(txBytes, pos + 4); slicePos = skipOutputs(txBytes, slicePos); slicePos += 4; // skip lock time } // scan a Merkle branch. // return array of values and the end position of the sibling hashes. // takes a 'stop' argument which sets the maximum number of // siblings to scan through. stop=0 => scan all. function scanMerkleBranch(bytes memory txBytes, uint pos, uint stop) private pure returns (uint[], uint) { uint n_siblings; uint halt; (n_siblings, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_siblings) { halt = n_siblings; } else { halt = stop; } uint[] memory sibling_values = new uint[](halt); for (uint i = 0; i < halt; i++) { sibling_values[i] = flip32Bytes(sliceBytes32Int(txBytes, pos)); pos += 32; } return (sibling_values, pos); } // Slice 20 contiguous bytes from bytes `data`, starting at `start` function sliceBytes20(bytes memory data, uint start) private pure returns (bytes20) { uint160 slice = 0; // FIXME: With solc v0.4.24 and optimizations enabled // using uint160 for index i will generate an error // "Error: VM Exception while processing transaction: Error: redPow(normalNum)" for (uint i = 0; i < 20; i++) { slice += uint160(data[i + start]) << (8 * (19 - i)); } return bytes20(slice); } // Slice 32 contiguous bytes from bytes `data`, starting at `start` function sliceBytes32Int(bytes memory data, uint start) private pure returns (uint slice) { for (uint i = 0; i < 32; i++) { if (i + start < data.length) { slice += uint(data[i + start]) << (8 * (31 - i)); } } } // @dev returns a portion of a given byte array specified by its starting and ending points // Should be private, made internal for testing // Breaks underscore naming convention for parameters because it raises a compiler error // if `offset` is changed to `_offset`. // // @param _rawBytes - array to be sliced // @param offset - first byte of sliced array // @param _endIndex - last byte of sliced array function sliceArray(bytes memory _rawBytes, uint offset, uint _endIndex) internal view returns (bytes) { uint len = _endIndex - offset; bytes memory result = new bytes(len); assembly { // Call precompiled contract to copy data if iszero(staticcall(gas, 0x04, add(add(_rawBytes, 0x20), offset), len, add(result, 0x20), len)) { revert(0, 0) } } return result; } // Returns true if the tx output is an OP_RETURN output function isOpReturn(bytes memory txBytes, uint pos) private pure returns (bool) { // scriptPub format is // 0x6a OP_RETURN return txBytes[pos] == byte(0x6a); } // Returns syscoin data parsed from the op_return data output from syscoin burn transaction function scanSyscoinDetails(bytes memory txBytes, uint pos) private pure returns (address) { uint8 op; (op, pos) = getOpcode(txBytes, pos); // ethereum addresses are 20 bytes (without the 0x) require(op == 0x14); return readEthereumAddress(txBytes, pos); } // Returns asset data parsed from the op_return data output from syscoin asset burn transaction function scanAssetDetails(bytes memory txBytes, uint pos) private pure returns (uint, address, uint32) { uint32 assetGUID; address destinationAddress; uint output_value; uint8 op; // vchAsset (op, pos) = getOpcode(txBytes, pos); // guid length should be 4 bytes require(op == 0x04); assetGUID = bytesToUint32(txBytes, pos); pos += op; // amount (op, pos) = getOpcode(txBytes, pos); require(op == 0x08); output_value = bytesToUint64(txBytes, pos); pos += op; // destination address (op, pos) = getOpcode(txBytes, pos); // ethereum contracts are 20 bytes (without the 0x) require(op == 0x14); destinationAddress = readEthereumAddress(txBytes, pos); return (output_value, destinationAddress, assetGUID); } // Read the ethereum address embedded in the tx output function readEthereumAddress(bytes memory txBytes, uint pos) private pure returns (address) { uint256 data; assembly { data := mload(add(add(txBytes, 20), pos)) } return address(uint160(data)); } // Read next opcode from script function getOpcode(bytes memory txBytes, uint pos) private pure returns (uint8, uint) { require(pos < txBytes.length); return (uint8(txBytes[pos]), pos + 1); } // @dev - convert an unsigned integer from little-endian to big-endian representation // // @param _input - little-endian value // @return - input value in big-endian format function flip32Bytes(uint _input) internal pure returns (uint result) { assembly { let pos := mload(0x40) for { let i := 0 } lt(i, 32) { i := add(i, 1) } { mstore8(add(pos, i), byte(sub(31, i), _input)) } result := mload(pos) } } // helpers for flip32Bytes struct UintWrapper { uint value; } function ptr(UintWrapper memory uw) private pure returns (uint addr) { assembly { addr := uw } } function parseAuxPoW(bytes memory rawBytes, uint pos) internal view returns (AuxPoW memory auxpow) { // we need to traverse the bytes with a pointer because some fields are of variable length pos += 80; // skip non-AuxPoW header uint slicePos; (slicePos) = getSlicePos(rawBytes, pos); auxpow.txHash = dblShaFlipMem(rawBytes, pos, slicePos - pos); pos = slicePos; // parent block hash, skip and manually hash below pos += 32; (auxpow.parentMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.coinbaseTxIndex = getBytesLE(rawBytes, pos, 32); pos += 4; (auxpow.chainMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.syscoinHashIndex = getBytesLE(rawBytes, pos, 32); pos += 4; // calculate block hash instead of reading it above, as some are LE and some are BE, we cannot know endianness and have to calculate from parent block header auxpow.blockHash = dblShaFlipMem(rawBytes, pos, 80); pos += 36; // skip parent version and prev block auxpow.parentMerkleRoot = sliceBytes32Int(rawBytes, pos); pos += 40; // skip root that was just read, parent block timestamp and bits auxpow.parentNonce = getBytesLE(rawBytes, pos, 32); uint coinbaseMerkleRootPosition; (auxpow.coinbaseMerkleRoot, coinbaseMerkleRootPosition, auxpow.coinbaseMerkleRootCode) = findCoinbaseMerkleRoot(rawBytes); } // @dev - looks for {0xfa, 0xbe, 'm', 'm'} byte sequence // returns the following 32 bytes if it appears once and only once, // 0 otherwise // also returns the position where the bytes first appear function findCoinbaseMerkleRoot(bytes memory rawBytes) private pure returns (uint, uint, uint) { uint position; bool found = false; for (uint i = 0; i < rawBytes.length; ++i) { if (rawBytes[i] == 0xfa && rawBytes[i+1] == 0xbe && rawBytes[i+2] == 0x6d && rawBytes[i+3] == 0x6d) { if (found) { // found twice return (0, position - 4, ERR_FOUND_TWICE); } else { found = true; position = i + 4; } } } if (!found) { // no merge mining header return (0, position - 4, ERR_NO_MERGE_HEADER); } else { return (sliceBytes32Int(rawBytes, position), position - 4, 1); } } // @dev - Evaluate the merkle root // // Given an array of hashes it calculates the // root of the merkle tree. // // @return root of merkle tree function makeMerkle(bytes32[] hashes2) external pure returns (bytes32) { bytes32[] memory hashes = hashes2; uint length = hashes.length; if (length == 1) return hashes[0]; require(length > 0); uint i; uint j; uint k; k = 0; while (length > 1) { k = 0; for (i = 0; i < length; i += 2) { j = i+1<length ? i+1 : length-1; hashes[k] = bytes32(concatHash(uint(hashes[i]), uint(hashes[j]))); k += 1; } length = k; } return hashes[0]; } // @dev - For a valid proof, returns the root of the Merkle tree. // // @param _txHash - transaction hash // @param _txIndex - transaction's index within the block it's assumed to be in // @param _siblings - transaction's Merkle siblings // @return - Merkle tree root of the block the transaction belongs to if the proof is valid, // garbage if it's invalid function computeMerkle(uint _txHash, uint _txIndex, uint[] memory _siblings) internal pure returns (uint) { uint resultHash = _txHash; uint i = 0; while (i < _siblings.length) { uint proofHex = _siblings[i]; uint sideOfSiblings = _txIndex % 2; // 0 means _siblings is on the right; 1 means left uint left; uint right; if (sideOfSiblings == 1) { left = proofHex; right = resultHash; } else if (sideOfSiblings == 0) { left = resultHash; right = proofHex; } resultHash = concatHash(left, right); _txIndex /= 2; i += 1; } return resultHash; } // @dev - calculates the Merkle root of a tree containing Litecoin transactions // in order to prove that `ap`'s coinbase tx is in that Litecoin block. // // @param _ap - AuxPoW information // @return - Merkle root of Litecoin block that the Syscoin block // with this info was mined in if AuxPoW Merkle proof is correct, // garbage otherwise function computeParentMerkle(AuxPoW memory _ap) internal pure returns (uint) { return flip32Bytes(computeMerkle(_ap.txHash, _ap.coinbaseTxIndex, _ap.parentMerkleProof)); } // @dev - calculates the Merkle root of a tree containing auxiliary block hashes // in order to prove that the Syscoin block identified by _blockHash // was merge-mined in a Litecoin block. // // @param _blockHash - SHA-256 hash of a certain Syscoin block // @param _ap - AuxPoW information corresponding to said block // @return - Merkle root of auxiliary chain tree // if AuxPoW Merkle proof is correct, garbage otherwise function computeChainMerkle(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) { return computeMerkle(_blockHash, _ap.syscoinHashIndex, _ap.chainMerkleProof); } // @dev - Helper function for Merkle root calculation. // Given two sibling nodes in a Merkle tree, calculate their parent. // Concatenates hashes `_tx1` and `_tx2`, then hashes the result. // // @param _tx1 - Merkle node (either root or internal node) // @param _tx2 - Merkle node (either root or internal node), has to be `_tx1`'s sibling // @return - `_tx1` and `_tx2`'s parent, i.e. the result of concatenating them, // hashing that twice and flipping the bytes. function concatHash(uint _tx1, uint _tx2) internal pure returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(flip32Bytes(_tx1), flip32Bytes(_tx2))))))); } // @dev - checks if a merge-mined block's Merkle proofs are correct, // i.e. Syscoin block hash is in coinbase Merkle tree // and coinbase transaction is in parent Merkle tree. // // @param _blockHash - SHA-256 hash of the block whose Merkle proofs are being checked // @param _ap - AuxPoW struct corresponding to the block // @return 1 if block was merge-mined and coinbase index, chain Merkle root and Merkle proofs are correct, // respective error code otherwise function checkAuxPoW(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) { if (_ap.coinbaseTxIndex != 0) { return ERR_COINBASE_INDEX; } if (_ap.coinbaseMerkleRootCode != 1) { return _ap.coinbaseMerkleRootCode; } if (computeChainMerkle(_blockHash, _ap) != _ap.coinbaseMerkleRoot) { return ERR_CHAIN_MERKLE; } if (computeParentMerkle(_ap) != _ap.parentMerkleRoot) { return ERR_PARENT_MERKLE; } return 1; } function sha256mem(bytes memory _rawBytes, uint offset, uint len) internal view returns (bytes32 result) { assembly { // Call sha256 precompiled contract (located in address 0x02) to copy data. // Assign to ptr the next available memory position (stored in memory position 0x40). let ptr := mload(0x40) if iszero(staticcall(gas, 0x02, add(add(_rawBytes, 0x20), offset), len, ptr, 0x20)) { revert(0, 0) } result := mload(ptr) } } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlip(bytes _dataBytes) internal pure returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(_dataBytes)))))); } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlipMem(bytes memory _rawBytes, uint offset, uint len) internal view returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256mem(_rawBytes, offset, len))))); } // @dev – Read a bytes32 from an offset in the byte array function readBytes32(bytes memory data, uint offset) internal pure returns (bytes32) { bytes32 result; assembly { result := mload(add(add(data, 0x20), offset)) } return result; } // @dev – Read an uint32 from an offset in the byte array function readUint32(bytes memory data, uint offset) internal pure returns (uint32) { uint32 result; assembly { result := mload(add(add(data, 0x20), offset)) } return result; } // @dev - Bitcoin-way of computing the target from the 'bits' field of a block header // based on http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html//ref3 // // @param _bits - difficulty in bits format // @return - difficulty in target format function targetFromBits(uint32 _bits) internal pure returns (uint) { uint exp = _bits / 0x1000000; // 2**24 uint mant = _bits & 0xffffff; return mant * 256**(exp - 3); } uint constant SYSCOIN_DIFFICULTY_ONE = 0xFFFFF * 256**(0x1e - 3); // @dev - Calculate syscoin difficulty from target // https://en.bitcoin.it/wiki/Difficulty // Min difficulty for bitcoin is 0x1d00ffff // Min difficulty for syscoin is 0x1e0fffff function targetToDiff(uint target) internal pure returns (uint) { return SYSCOIN_DIFFICULTY_ONE / target; } // 0x00 version // 0x04 prev block hash // 0x24 merkle root // 0x44 timestamp // 0x48 bits // 0x4c nonce // @dev - extract previous block field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading hash from // @return - hash of block's parent in big endian format function getHashPrevBlock(bytes memory _blockHeader) internal pure returns (uint) { uint hashPrevBlock; assembly { hashPrevBlock := mload(add(add(_blockHeader, 32), 0x04)) } return flip32Bytes(hashPrevBlock); } // @dev - extract Merkle root field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading root from // @return - block's Merkle root in big endian format function getHeaderMerkleRoot(bytes memory _blockHeader) public pure returns (uint) { uint merkle; assembly { merkle := mload(add(add(_blockHeader, 32), 0x24)) } return flip32Bytes(merkle); } // @dev - extract timestamp field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading bits from // @return - block's timestamp in big-endian format function getTimestamp(bytes memory _blockHeader) internal pure returns (uint32 time) { return bytesToUint32Flipped(_blockHeader, 0x44); } // @dev - extract bits field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading bits from // @return - block's difficulty in bits format, also big-endian function getBits(bytes memory _blockHeader) internal pure returns (uint32 bits) { return bytesToUint32Flipped(_blockHeader, 0x48); } // @dev - converts raw bytes representation of a Syscoin block header to struct representation // // @param _rawBytes - first 80 bytes of a block header // @return - exact same header information in BlockHeader struct form function parseHeaderBytes(bytes memory _rawBytes, uint pos) internal view returns (BlockHeader bh) { bh.bits = getBits(_rawBytes); bh.blockHash = dblShaFlipMem(_rawBytes, pos, 80); } uint32 constant VERSION_AUXPOW = (1 << 8); // @dev - Converts a bytes of size 4 to uint32, // e.g. for input [0x01, 0x02, 0x03 0x04] returns 0x01020304 function bytesToUint32Flipped(bytes memory input, uint pos) internal pure returns (uint32 result) { result = uint32(input[pos]) + uint32(input[pos + 1])*(2**8) + uint32(input[pos + 2])*(2**16) + uint32(input[pos + 3])*(2**24); } function bytesToUint64(bytes memory input, uint pos) internal pure returns (uint64 result) { result = uint64(input[pos+7]) + uint64(input[pos + 6])*(2**8) + uint64(input[pos + 5])*(2**16) + uint64(input[pos + 4])*(2**24) + uint64(input[pos + 3])*(2**32) + uint64(input[pos + 2])*(2**40) + uint64(input[pos + 1])*(2**48) + uint64(input[pos])*(2**56); } function bytesToUint32(bytes memory input, uint pos) internal pure returns (uint32 result) { result = uint32(input[pos+3]) + uint32(input[pos + 2])*(2**8) + uint32(input[pos + 1])*(2**16) + uint32(input[pos])*(2**24); } // @dev - checks version to determine if a block has merge mining information function isMergeMined(bytes memory _rawBytes, uint pos) internal pure returns (bool) { return bytesToUint32Flipped(_rawBytes, pos) & VERSION_AUXPOW != 0; } // @dev - Verify block header // @param _blockHeaderBytes - array of bytes with the block header // @param _pos - starting position of the block header // @param _proposedBlockHash - proposed block hash computing from block header bytes // @return - [ErrorCode, IsMergeMined] function verifyBlockHeader(bytes _blockHeaderBytes, uint _pos, uint _proposedBlockHash) external view returns (uint, bool) { BlockHeader memory blockHeader = parseHeaderBytes(_blockHeaderBytes, _pos); uint blockSha256Hash = blockHeader.blockHash; // must confirm that the header hash passed in and computing hash matches if(blockSha256Hash != _proposedBlockHash){ return (ERR_INVALID_HEADER_HASH, true); } uint target = targetFromBits(blockHeader.bits); if (_blockHeaderBytes.length > 80 && isMergeMined(_blockHeaderBytes, 0)) { AuxPoW memory ap = parseAuxPoW(_blockHeaderBytes, _pos); if (ap.blockHash > target) { return (ERR_PROOF_OF_WORK_AUXPOW, true); } uint auxPoWCode = checkAuxPoW(blockSha256Hash, ap); if (auxPoWCode != 1) { return (auxPoWCode, true); } return (0, true); } else { if (_proposedBlockHash > target) { return (ERR_PROOF_OF_WORK, false); } return (0, false); } } // For verifying Syscoin difficulty int64 constant TARGET_TIMESPAN = int64(21600); int64 constant TARGET_TIMESPAN_DIV_4 = TARGET_TIMESPAN / int64(4); int64 constant TARGET_TIMESPAN_MUL_4 = TARGET_TIMESPAN * int64(4); int64 constant TARGET_TIMESPAN_ADJUSTMENT = int64(360); // 6 hour uint constant INITIAL_CHAIN_WORK = 0x100001; uint constant POW_LIMIT = 0x00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // @dev - Calculate difficulty from compact representation (bits) found in block function diffFromBits(uint32 bits) external pure returns (uint) { return targetToDiff(targetFromBits(bits))*INITIAL_CHAIN_WORK; } function difficultyAdjustmentInterval() external pure returns (int64) { return TARGET_TIMESPAN_ADJUSTMENT; } // @param _actualTimespan - time elapsed from previous block creation til current block creation; // i.e., how much time it took to mine the current block // @param _bits - previous block header difficulty (in bits) // @return - expected difficulty for the next block function calculateDifficulty(int64 _actualTimespan, uint32 _bits) external pure returns (uint32 result) { int64 actualTimespan = _actualTimespan; // Limit adjustment step if (_actualTimespan < TARGET_TIMESPAN_DIV_4) { actualTimespan = TARGET_TIMESPAN_DIV_4; } else if (_actualTimespan > TARGET_TIMESPAN_MUL_4) { actualTimespan = TARGET_TIMESPAN_MUL_4; } // Retarget uint bnNew = targetFromBits(_bits); bnNew = bnNew * uint(actualTimespan); bnNew = uint(bnNew) / uint(TARGET_TIMESPAN); if (bnNew > POW_LIMIT) { bnNew = POW_LIMIT; } return toCompactBits(bnNew); } // @dev - shift information to the right by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the right, i.e. divided by 2**`_shift` function shiftRight(uint _val, uint _shift) private pure returns (uint) { return _val / uint(2)**_shift; } // @dev - shift information to the left by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the left, i.e. multiplied by 2**`_shift` function shiftLeft(uint _val, uint _shift) private pure returns (uint) { return _val * uint(2)**_shift; } // @dev - get the number of bits required to represent a given integer value without losing information // // @param _val - unsigned integer value // @return - given value's bit length function bitLen(uint _val) private pure returns (uint length) { uint int_type = _val; while (int_type > 0) { int_type = shiftRight(int_type, 1); length += 1; } } // @dev - Convert uint256 to compact encoding // based on https://github.com/petertodd/python-bitcoinlib/blob/2a5dda45b557515fb12a0a18e5dd48d2f5cd13c2/bitcoin/core/serialize.py // Analogous to arith_uint256::GetCompact from C++ implementation // // @param _val - difficulty in target format // @return - difficulty in bits format function toCompactBits(uint _val) private pure returns (uint32) { uint nbytes = uint (shiftRight((bitLen(_val) + 7), 3)); uint32 compact = 0; if (nbytes <= 3) { compact = uint32 (shiftLeft((_val & 0xFFFFFF), 8 * (3 - nbytes))); } else { compact = uint32 (shiftRight(_val, 8 * (nbytes - 3))); compact = uint32 (compact & 0xFFFFFF); } // If the sign bit (0x00800000) is set, divide the mantissa by 256 and // increase the exponent to get an encoding without it set. if ((compact & 0x00800000) > 0) { compact = uint32(shiftRight(compact, 8)); nbytes += 1; } return compact | uint32(shiftLeft(nbytes, 24)); } } // @dev - SyscoinSuperblocks error codes contract SyscoinErrorCodes { // Error codes uint constant ERR_SUPERBLOCK_OK = 0; uint constant ERR_SUPERBLOCK_BAD_STATUS = 50020; uint constant ERR_SUPERBLOCK_BAD_SYSCOIN_STATUS = 50025; uint constant ERR_SUPERBLOCK_NO_TIMEOUT = 50030; uint constant ERR_SUPERBLOCK_BAD_TIMESTAMP = 50035; uint constant ERR_SUPERBLOCK_INVALID_MERKLE = 50040; uint constant ERR_SUPERBLOCK_BAD_PARENT = 50050; uint constant ERR_SUPERBLOCK_OWN_CHALLENGE = 50055; uint constant ERR_SUPERBLOCK_MIN_DEPOSIT = 50060; uint constant ERR_SUPERBLOCK_NOT_CLAIMMANAGER = 50070; uint constant ERR_SUPERBLOCK_BAD_CLAIM = 50080; uint constant ERR_SUPERBLOCK_VERIFICATION_PENDING = 50090; uint constant ERR_SUPERBLOCK_CLAIM_DECIDED = 50100; uint constant ERR_SUPERBLOCK_BAD_CHALLENGER = 50110; uint constant ERR_SUPERBLOCK_BAD_ACCUMULATED_WORK = 50120; uint constant ERR_SUPERBLOCK_BAD_BITS = 50130; uint constant ERR_SUPERBLOCK_MISSING_CONFIRMATIONS = 50140; uint constant ERR_SUPERBLOCK_BAD_LASTBLOCK = 50150; uint constant ERR_SUPERBLOCK_BAD_BLOCKHEIGHT = 50160; // error codes for verifyTx uint constant ERR_BAD_FEE = 20010; uint constant ERR_CONFIRMATIONS = 20020; uint constant ERR_CHAIN = 20030; uint constant ERR_SUPERBLOCK = 20040; uint constant ERR_MERKLE_ROOT = 20050; uint constant ERR_TX_64BYTE = 20060; // error codes for relayTx uint constant ERR_RELAY_VERIFY = 30010; // Minimum gas requirements uint constant public minReward = 1000000000000000000; uint constant public superblockCost = 440000; uint constant public challengeCost = 34000; uint constant public minProposalDeposit = challengeCost + minReward; uint constant public minChallengeDeposit = superblockCost + minReward; uint constant public respondMerkleRootHashesCost = 378000; // TODO: measure this with 60 hashes uint constant public respondBlockHeaderCost = 40000; uint constant public verifySuperblockCost = 220000; } // @dev - Manages superblocks // // Management of superblocks and status transitions contract SyscoinSuperblocks is SyscoinErrorCodes { // @dev - Superblock status enum Status { Unitialized, New, InBattle, SemiApproved, Approved, Invalid } struct SuperblockInfo { bytes32 blocksMerkleRoot; uint accumulatedWork; uint timestamp; uint prevTimestamp; bytes32 lastHash; bytes32 parentId; address submitter; bytes32 ancestors; uint32 lastBits; uint32 index; uint32 height; uint32 blockHeight; Status status; } // Mapping superblock id => superblock data mapping (bytes32 => SuperblockInfo) superblocks; // Index to superblock id mapping (uint32 => bytes32) private indexSuperblock; struct ProcessTransactionParams { uint value; address destinationAddress; uint32 assetGUID; address superblockSubmitterAddress; SyscoinTransactionProcessor untrustedTargetContract; } mapping (uint => ProcessTransactionParams) private txParams; uint32 indexNextSuperblock; bytes32 public bestSuperblock; uint public bestSuperblockAccumulatedWork; event NewSuperblock(bytes32 superblockHash, address who); event ApprovedSuperblock(bytes32 superblockHash, address who); event ChallengeSuperblock(bytes32 superblockHash, address who); event SemiApprovedSuperblock(bytes32 superblockHash, address who); event InvalidSuperblock(bytes32 superblockHash, address who); event ErrorSuperblock(bytes32 superblockHash, uint err); event VerifyTransaction(bytes32 txHash, uint returnCode); event RelayTransaction(bytes32 txHash, uint returnCode); // SyscoinClaimManager address public trustedClaimManager; modifier onlyClaimManager() { require(msg.sender == trustedClaimManager); _; } // @dev – the constructor constructor() public {} // @dev - sets ClaimManager instance associated with managing superblocks. // Once trustedClaimManager has been set, it cannot be changed. // @param _claimManager - address of the ClaimManager contract to be associated with function setClaimManager(address _claimManager) public { require(address(trustedClaimManager) == 0x0 && _claimManager != 0x0); trustedClaimManager = _claimManager; } // @dev - Initializes superblocks contract // // Initializes the superblock contract. It can only be called once. // // @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock // @param _accumulatedWork Accumulated proof of work of the last block in the superblock // @param _timestamp Timestamp of the last block in the superblock // @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks) // @param _lastHash Hash of the last block in the superblock // @param _lastBits Difficulty bits of the last block in the superblock // @param _parentId Id of the parent superblock // @param _blockHeight Block height of last block in superblock // @return Error code and superblockHash function initialize( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, uint32 _blockHeight ) public returns (uint, bytes32) { require(bestSuperblock == 0); require(_parentId == 0); bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentId, _blockHeight); SuperblockInfo storage superblock = superblocks[superblockHash]; require(superblock.status == Status.Unitialized); indexSuperblock[indexNextSuperblock] = superblockHash; superblock.blocksMerkleRoot = _blocksMerkleRoot; superblock.accumulatedWork = _accumulatedWork; superblock.timestamp = _timestamp; superblock.prevTimestamp = _prevTimestamp; superblock.lastHash = _lastHash; superblock.parentId = _parentId; superblock.submitter = msg.sender; superblock.index = indexNextSuperblock; superblock.height = 1; superblock.lastBits = _lastBits; superblock.status = Status.Approved; superblock.ancestors = 0x0; superblock.blockHeight = _blockHeight; indexNextSuperblock++; emit NewSuperblock(superblockHash, msg.sender); bestSuperblock = superblockHash; bestSuperblockAccumulatedWork = _accumulatedWork; emit ApprovedSuperblock(superblockHash, msg.sender); return (ERR_SUPERBLOCK_OK, superblockHash); } // @dev - Proposes a new superblock // // To be accepted, a new superblock needs to have its parent // either approved or semi-approved. // // @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock // @param _accumulatedWork Accumulated proof of work of the last block in the superblock // @param _timestamp Timestamp of the last block in the superblock // @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks) // @param _lastHash Hash of the last block in the superblock // @param _lastBits Difficulty bits of the last block in the superblock // @param _parentId Id of the parent superblock // @param _blockHeight Block height of last block in superblock // @return Error code and superblockHash function propose( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, uint32 _blockHeight, address submitter ) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(0, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage parent = superblocks[_parentId]; if (parent.status != Status.SemiApproved && parent.status != Status.Approved) { emit ErrorSuperblock(superblockHash, ERR_SUPERBLOCK_BAD_PARENT); return (ERR_SUPERBLOCK_BAD_PARENT, 0); } bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentId, _blockHeight); SuperblockInfo storage superblock = superblocks[superblockHash]; if (superblock.status == Status.Unitialized) { indexSuperblock[indexNextSuperblock] = superblockHash; superblock.blocksMerkleRoot = _blocksMerkleRoot; superblock.accumulatedWork = _accumulatedWork; superblock.timestamp = _timestamp; superblock.prevTimestamp = _prevTimestamp; superblock.lastHash = _lastHash; superblock.parentId = _parentId; superblock.submitter = submitter; superblock.index = indexNextSuperblock; superblock.height = parent.height + 1; superblock.lastBits = _lastBits; superblock.status = Status.New; superblock.blockHeight = _blockHeight; superblock.ancestors = updateAncestors(parent.ancestors, parent.index, parent.height); indexNextSuperblock++; emit NewSuperblock(superblockHash, submitter); } return (ERR_SUPERBLOCK_OK, superblockHash); } // @dev - Confirm a proposed superblock // // An unchallenged superblock can be confirmed after a timeout. // A challenged superblock is confirmed if it has enough descendants // in the main chain. // // @param _superblockHash Id of the superblock to confirm // @param _validator Address requesting superblock confirmation // @return Error code and superblockHash function confirm(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.New && superblock.status != Status.SemiApproved) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } SuperblockInfo storage parent = superblocks[superblock.parentId]; if (parent.status != Status.Approved) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_PARENT); return (ERR_SUPERBLOCK_BAD_PARENT, 0); } superblock.status = Status.Approved; if (superblock.accumulatedWork > bestSuperblockAccumulatedWork) { bestSuperblock = _superblockHash; bestSuperblockAccumulatedWork = superblock.accumulatedWork; } emit ApprovedSuperblock(_superblockHash, _validator); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - Challenge a proposed superblock // // A new superblock can be challenged to start a battle // to verify the correctness of the data submitted. // // @param _superblockHash Id of the superblock to challenge // @param _challenger Address requesting a challenge // @return Error code and superblockHash function challenge(bytes32 _superblockHash, address _challenger) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.New && superblock.status != Status.InBattle) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } if(superblock.submitter == _challenger){ emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_OWN_CHALLENGE); return (ERR_SUPERBLOCK_OWN_CHALLENGE, 0); } superblock.status = Status.InBattle; emit ChallengeSuperblock(_superblockHash, _challenger); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - Semi-approve a challenged superblock // // A challenged superblock can be marked as semi-approved // if it satisfies all the queries or when all challengers have // stopped participating. // // @param _superblockHash Id of the superblock to semi-approve // @param _validator Address requesting semi approval // @return Error code and superblockHash function semiApprove(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.InBattle && superblock.status != Status.New) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } superblock.status = Status.SemiApproved; emit SemiApprovedSuperblock(_superblockHash, _validator); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - Invalidates a superblock // // A superblock with incorrect data can be invalidated immediately. // Superblocks that are not in the main chain can be invalidated // if not enough superblocks follow them, i.e. they don't have // enough descendants. // // @param _superblockHash Id of the superblock to invalidate // @param _validator Address requesting superblock invalidation // @return Error code and superblockHash function invalidate(bytes32 _superblockHash, address _validator) public returns (uint, bytes32) { if (msg.sender != trustedClaimManager) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER); return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0); } SuperblockInfo storage superblock = superblocks[_superblockHash]; if (superblock.status != Status.InBattle && superblock.status != Status.SemiApproved) { emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return (ERR_SUPERBLOCK_BAD_STATUS, 0); } superblock.status = Status.Invalid; emit InvalidSuperblock(_superblockHash, _validator); return (ERR_SUPERBLOCK_OK, _superblockHash); } // @dev - relays transaction `_txBytes` to `_untrustedTargetContract`'s processTransaction() method. // Also logs the value of processTransaction. // Note: callers cannot be 100% certain when an ERR_RELAY_VERIFY occurs because // it may also have been returned by processTransaction(). Callers should be // aware of the contract that they are relaying transactions to and // understand what that contract's processTransaction method returns. // // @param _txBytes - transaction bytes // @param _txIndex - transaction's index within the block // @param _txSiblings - transaction's Merkle siblings // @param _syscoinBlockHeader - block header containing transaction // @param _syscoinBlockIndex - block's index withing superblock // @param _syscoinBlockSiblings - block's merkle siblings // @param _superblockHash - superblock containing block header // @param _untrustedTargetContract - the contract that is going to process the transaction function relayTx( bytes memory _txBytes, uint _txIndex, uint[] _txSiblings, bytes memory _syscoinBlockHeader, uint _syscoinBlockIndex, uint[] memory _syscoinBlockSiblings, bytes32 _superblockHash, SyscoinTransactionProcessor _untrustedTargetContract ) public returns (uint) { // Check if Syscoin block belongs to given superblock if (bytes32(SyscoinMessageLibrary.computeMerkle(SyscoinMessageLibrary.dblShaFlip(_syscoinBlockHeader), _syscoinBlockIndex, _syscoinBlockSiblings)) != getSuperblockMerkleRoot(_superblockHash)) { // Syscoin block is not in superblock emit RelayTransaction(bytes32(0), ERR_SUPERBLOCK); return ERR_SUPERBLOCK; } uint txHash = verifyTx(_txBytes, _txIndex, _txSiblings, _syscoinBlockHeader, _superblockHash); if (txHash != 0) { uint ret = parseTxHelper(_txBytes, txHash, _untrustedTargetContract); if(ret != 0){ emit RelayTransaction(bytes32(0), ret); return ret; } ProcessTransactionParams memory params = txParams[txHash]; params.superblockSubmitterAddress = superblocks[_superblockHash].submitter; txParams[txHash] = params; return verifyTxHelper(txHash); } emit RelayTransaction(bytes32(0), ERR_RELAY_VERIFY); return(ERR_RELAY_VERIFY); } function parseTxHelper(bytes memory _txBytes, uint txHash, SyscoinTransactionProcessor _untrustedTargetContract) private returns (uint) { uint value; address destinationAddress; uint32 _assetGUID; uint ret; (ret, value, destinationAddress, _assetGUID) = SyscoinMessageLibrary.parseTransaction(_txBytes); if(ret != 0){ return ret; } ProcessTransactionParams memory params; params.value = value; params.destinationAddress = destinationAddress; params.assetGUID = _assetGUID; params.untrustedTargetContract = _untrustedTargetContract; txParams[txHash] = params; return 0; } function verifyTxHelper(uint txHash) private returns (uint) { ProcessTransactionParams memory params = txParams[txHash]; uint returnCode = params.untrustedTargetContract.processTransaction(txHash, params.value, params.destinationAddress, params.assetGUID, params.superblockSubmitterAddress); emit RelayTransaction(bytes32(txHash), returnCode); return (returnCode); } // @dev - Checks whether the transaction given by `_txBytes` is in the block identified by `_txBlockHeaderBytes`. // First it guards against a Merkle tree collision attack by raising an error if the transaction is exactly 64 bytes long, // then it calls helperVerifyHash to do the actual check. // // @param _txBytes - transaction bytes // @param _txIndex - transaction's index within the block // @param _siblings - transaction's Merkle siblings // @param _txBlockHeaderBytes - block header containing transaction // @param _txsuperblockHash - superblock containing block header // @return - SHA-256 hash of _txBytes if the transaction is in the block, 0 otherwise // TODO: this can probably be made private function verifyTx( bytes memory _txBytes, uint _txIndex, uint[] memory _siblings, bytes memory _txBlockHeaderBytes, bytes32 _txsuperblockHash ) public returns (uint) { uint txHash = SyscoinMessageLibrary.dblShaFlip(_txBytes); if (_txBytes.length == 64) { // todo: is check 32 also needed? emit VerifyTransaction(bytes32(txHash), ERR_TX_64BYTE); return 0; } if (helperVerifyHash(txHash, _txIndex, _siblings, _txBlockHeaderBytes, _txsuperblockHash) == 1) { return txHash; } else { // log is done via helperVerifyHash return 0; } } // @dev - Checks whether the transaction identified by `_txHash` is in the block identified by `_blockHeaderBytes` // and whether the block is in the Syscoin main chain. Transaction check is done via Merkle proof. // Note: no verification is performed to prevent txHash from just being an // internal hash in the Merkle tree. Thus this helper method should NOT be used // directly and is intended to be private. // // @param _txHash - transaction hash // @param _txIndex - transaction's index within the block // @param _siblings - transaction's Merkle siblings // @param _blockHeaderBytes - block header containing transaction // @param _txsuperblockHash - superblock containing block header // @return - 1 if the transaction is in the block and the block is in the main chain, // 20020 (ERR_CONFIRMATIONS) if the block is not in the main chain, // 20050 (ERR_MERKLE_ROOT) if the block is in the main chain but the Merkle proof fails. function helperVerifyHash( uint256 _txHash, uint _txIndex, uint[] memory _siblings, bytes memory _blockHeaderBytes, bytes32 _txsuperblockHash ) private returns (uint) { //TODO: Verify superblock is in superblock's main chain if (!isApproved(_txsuperblockHash) || !inMainChain(_txsuperblockHash)) { emit VerifyTransaction(bytes32(_txHash), ERR_CHAIN); return (ERR_CHAIN); } // Verify tx Merkle root uint merkle = SyscoinMessageLibrary.getHeaderMerkleRoot(_blockHeaderBytes); if (SyscoinMessageLibrary.computeMerkle(_txHash, _txIndex, _siblings) != merkle) { emit VerifyTransaction(bytes32(_txHash), ERR_MERKLE_ROOT); return (ERR_MERKLE_ROOT); } emit VerifyTransaction(bytes32(_txHash), 1); return (1); } // @dev - Calculate superblock hash from superblock data // // @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock // @param _accumulatedWork Accumulated proof of work of the last block in the superblock // @param _timestamp Timestamp of the last block in the superblock // @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened (every 360 blocks) // @param _lastHash Hash of the last block in the superblock // @param _lastBits Difficulty bits of the last block in the superblock // @param _parentId Id of the parent superblock // @param _blockHeight Block height of last block in superblock // @return Superblock id function calcSuperblockHash( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, uint32 _blockHeight ) public pure returns (bytes32) { return keccak256(abi.encodePacked( _blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentId, _blockHeight )); } // @dev - Returns the confirmed superblock with the most accumulated work // // @return Best superblock hash function getBestSuperblock() public view returns (bytes32) { return bestSuperblock; } // @dev - Returns the superblock data for the supplied superblock hash // // @return { // bytes32 _blocksMerkleRoot, // uint _accumulatedWork, // uint _timestamp, // uint _prevTimestamp, // bytes32 _lastHash, // uint32 _lastBits, // bytes32 _parentId, // address _submitter, // Status _status, // uint32 _blockHeight, // } Superblock data function getSuperblock(bytes32 superblockHash) public view returns ( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, address _submitter, Status _status, uint32 _blockHeight ) { SuperblockInfo storage superblock = superblocks[superblockHash]; return ( superblock.blocksMerkleRoot, superblock.accumulatedWork, superblock.timestamp, superblock.prevTimestamp, superblock.lastHash, superblock.lastBits, superblock.parentId, superblock.submitter, superblock.status, superblock.blockHeight ); } // @dev - Returns superblock height function getSuperblockHeight(bytes32 superblockHash) public view returns (uint32) { return superblocks[superblockHash].height; } // @dev - Returns superblock internal index function getSuperblockIndex(bytes32 superblockHash) public view returns (uint32) { return superblocks[superblockHash].index; } // @dev - Return superblock ancestors' indexes function getSuperblockAncestors(bytes32 superblockHash) public view returns (bytes32) { return superblocks[superblockHash].ancestors; } // @dev - Return superblock blocks' Merkle root function getSuperblockMerkleRoot(bytes32 _superblockHash) public view returns (bytes32) { return superblocks[_superblockHash].blocksMerkleRoot; } // @dev - Return superblock timestamp function getSuperblockTimestamp(bytes32 _superblockHash) public view returns (uint) { return superblocks[_superblockHash].timestamp; } // @dev - Return superblock prevTimestamp function getSuperblockPrevTimestamp(bytes32 _superblockHash) public view returns (uint) { return superblocks[_superblockHash].prevTimestamp; } // @dev - Return superblock last block hash function getSuperblockLastHash(bytes32 _superblockHash) public view returns (bytes32) { return superblocks[_superblockHash].lastHash; } // @dev - Return superblock parent function getSuperblockParentId(bytes32 _superblockHash) public view returns (bytes32) { return superblocks[_superblockHash].parentId; } // @dev - Return superblock accumulated work function getSuperblockAccumulatedWork(bytes32 _superblockHash) public view returns (uint) { return superblocks[_superblockHash].accumulatedWork; } // @dev - Return superblock status function getSuperblockStatus(bytes32 _superblockHash) public view returns (Status) { return superblocks[_superblockHash].status; } // @dev - Return indexNextSuperblock function getIndexNextSuperblock() public view returns (uint32) { return indexNextSuperblock; } // @dev - Calculate Merkle root from Syscoin block hashes function makeMerkle(bytes32[] hashes) public pure returns (bytes32) { return SyscoinMessageLibrary.makeMerkle(hashes); } function isApproved(bytes32 _superblockHash) public view returns (bool) { return (getSuperblockStatus(_superblockHash) == Status.Approved); } function getChainHeight() public view returns (uint) { return superblocks[bestSuperblock].height; } // @dev - write `_fourBytes` into `_word` starting from `_position` // This is useful for writing 32bit ints inside one 32 byte word // // @param _word - information to be partially overwritten // @param _position - position to start writing from // @param _eightBytes - information to be written function writeUint32(bytes32 _word, uint _position, uint32 _fourBytes) private pure returns (bytes32) { bytes32 result; assembly { let pointer := mload(0x40) mstore(pointer, _word) mstore8(add(pointer, _position), byte(28, _fourBytes)) mstore8(add(pointer, add(_position,1)), byte(29, _fourBytes)) mstore8(add(pointer, add(_position,2)), byte(30, _fourBytes)) mstore8(add(pointer, add(_position,3)), byte(31, _fourBytes)) result := mload(pointer) } return result; } uint constant ANCESTOR_STEP = 5; uint constant NUM_ANCESTOR_DEPTHS = 8; // @dev - Update ancestor to the new height function updateAncestors(bytes32 ancestors, uint32 index, uint height) internal pure returns (bytes32) { uint step = ANCESTOR_STEP; ancestors = writeUint32(ancestors, 0, index); uint i = 1; while (i<NUM_ANCESTOR_DEPTHS && (height % step == 1)) { ancestors = writeUint32(ancestors, 4*i, index); step *= ANCESTOR_STEP; ++i; } return ancestors; } // @dev - Returns a list of superblock hashes (9 hashes maximum) that helps an agent find out what // superblocks are missing. // The first position contains bestSuperblock, then // bestSuperblock - 1, // (bestSuperblock-1) - ((bestSuperblock-1) % 5), then // (bestSuperblock-1) - ((bestSuperblock-1) % 25), ... until // (bestSuperblock-1) - ((bestSuperblock-1) % 78125) // // @return - list of up to 9 ancestor supeerblock id function getSuperblockLocator() public view returns (bytes32[9]) { bytes32[9] memory locator; locator[0] = bestSuperblock; bytes32 ancestors = getSuperblockAncestors(bestSuperblock); uint i = NUM_ANCESTOR_DEPTHS; while (i > 0) { locator[i] = indexSuperblock[uint32(ancestors & 0xFFFFFFFF)]; ancestors >>= 32; --i; } return locator; } // @dev - Return ancestor at given index function getSuperblockAncestor(bytes32 superblockHash, uint index) internal view returns (bytes32) { bytes32 ancestors = superblocks[superblockHash].ancestors; uint32 ancestorsIndex = uint32(ancestors[4*index + 0]) * 0x1000000 + uint32(ancestors[4*index + 1]) * 0x10000 + uint32(ancestors[4*index + 2]) * 0x100 + uint32(ancestors[4*index + 3]) * 0x1; return indexSuperblock[ancestorsIndex]; } // dev - returns depth associated with an ancestor index; applies to any superblock // // @param _index - index of ancestor to be looked up; an integer between 0 and 7 // @return - depth corresponding to said index, i.e. 5**index function getAncDepth(uint _index) private pure returns (uint) { return ANCESTOR_STEP**(uint(_index)); } // @dev - return superblock hash at a given height in superblock main chain // // @param _height - superblock height // @return - hash corresponding to block of height _blockHeight function getSuperblockAt(uint _height) public view returns (bytes32) { bytes32 superblockHash = bestSuperblock; uint index = NUM_ANCESTOR_DEPTHS - 1; while (getSuperblockHeight(superblockHash) > _height) { while (getSuperblockHeight(superblockHash) - _height < getAncDepth(index) && index > 0) { index -= 1; } superblockHash = getSuperblockAncestor(superblockHash, index); } return superblockHash; } // @dev - Checks if a superblock is in superblock main chain // // @param _blockHash - hash of the block being searched for in the main chain // @return - true if the block identified by _blockHash is in the main chain, // false otherwise function inMainChain(bytes32 _superblockHash) internal view returns (bool) { uint height = getSuperblockHeight(_superblockHash); if (height == 0) return false; return (getSuperblockAt(height) == _superblockHash); } } // @dev - Manages a battle session between superblock submitter and challenger contract SyscoinBattleManager is SyscoinErrorCodes { enum ChallengeState { Unchallenged, // Unchallenged submission Challenged, // Claims was challenged QueryMerkleRootHashes, // Challenger expecting block hashes RespondMerkleRootHashes, // Blcok hashes were received and verified QueryBlockHeader, // Challenger is requesting block headers RespondBlockHeader, // All block headers were received PendingVerification, // Pending superblock verification SuperblockVerified, // Superblock verified SuperblockFailed // Superblock not valid } enum BlockInfoStatus { Uninitialized, Requested, Verified } struct BlockInfo { bytes32 prevBlock; uint64 timestamp; uint32 bits; BlockInfoStatus status; bytes powBlockHeader; bytes32 blockHash; } struct BattleSession { bytes32 id; bytes32 superblockHash; address submitter; address challenger; uint lastActionTimestamp; // Last action timestamp uint lastActionClaimant; // Number last action submitter uint lastActionChallenger; // Number last action challenger uint actionsCounter; // Counter session actions bytes32[] blockHashes; // Block hashes uint countBlockHeaderQueries; // Number of block header queries uint countBlockHeaderResponses; // Number of block header responses mapping (bytes32 => BlockInfo) blocksInfo; ChallengeState challengeState; // Claim state } mapping (bytes32 => BattleSession) public sessions; uint public sessionsCount = 0; uint public superblockDuration; // Superblock duration (in seconds) uint public superblockTimeout; // Timeout action (in seconds) // network that the stored blocks belong to SyscoinMessageLibrary.Network private net; // Syscoin claim manager SyscoinClaimManager trustedSyscoinClaimManager; // Superblocks contract SyscoinSuperblocks trustedSuperblocks; event NewBattle(bytes32 superblockHash, bytes32 sessionId, address submitter, address challenger); event ChallengerConvicted(bytes32 superblockHash, bytes32 sessionId, address challenger); event SubmitterConvicted(bytes32 superblockHash, bytes32 sessionId, address submitter); event QueryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address submitter); event RespondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes32[] blockHashes); event QueryBlockHeader(bytes32 superblockHash, bytes32 sessionId, address submitter, bytes32 blockSha256Hash); event RespondBlockHeader(bytes32 superblockHash, bytes32 sessionId, address challenger, bytes blockHeader, bytes powBlockHeader); event ErrorBattle(bytes32 sessionId, uint err); modifier onlyFrom(address sender) { require(msg.sender == sender); _; } modifier onlyClaimant(bytes32 sessionId) { require(msg.sender == sessions[sessionId].submitter); _; } modifier onlyChallenger(bytes32 sessionId) { require(msg.sender == sessions[sessionId].challenger); _; } // @dev – Configures the contract managing superblocks battles // @param _network Network type to use for block difficulty validation // @param _superblocks Contract that manages superblocks // @param _superblockDuration Superblock duration (in seconds) // @param _superblockTimeout Time to wait for challenges (in seconds) constructor( SyscoinMessageLibrary.Network _network, SyscoinSuperblocks _superblocks, uint _superblockDuration, uint _superblockTimeout ) public { net = _network; trustedSuperblocks = _superblocks; superblockDuration = _superblockDuration; superblockTimeout = _superblockTimeout; } function setSyscoinClaimManager(SyscoinClaimManager _syscoinClaimManager) public { require(address(trustedSyscoinClaimManager) == 0x0 && address(_syscoinClaimManager) != 0x0); trustedSyscoinClaimManager = _syscoinClaimManager; } // @dev - Start a battle session function beginBattleSession(bytes32 superblockHash, address submitter, address challenger) onlyFrom(trustedSyscoinClaimManager) public returns (bytes32) { bytes32 sessionId = keccak256(abi.encode(superblockHash, msg.sender, sessionsCount)); BattleSession storage session = sessions[sessionId]; session.id = sessionId; session.superblockHash = superblockHash; session.submitter = submitter; session.challenger = challenger; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = 0; session.lastActionClaimant = 1; // Force challenger to start session.actionsCounter = 1; session.challengeState = ChallengeState.Challenged; sessionsCount += 1; emit NewBattle(superblockHash, sessionId, submitter, challenger); return sessionId; } // @dev - Challenger makes a query for superblock hashes function doQueryMerkleRootHashes(BattleSession storage session) internal returns (uint) { if (!hasDeposit(msg.sender, respondMerkleRootHashesCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } if (session.challengeState == ChallengeState.Challenged) { session.challengeState = ChallengeState.QueryMerkleRootHashes; assert(msg.sender == session.challenger); (uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondMerkleRootHashesCost); if (err != ERR_SUPERBLOCK_OK) { return err; } return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - Challenger makes a query for superblock hashes function queryMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId) onlyChallenger(sessionId) public { BattleSession storage session = sessions[sessionId]; uint err = doQueryMerkleRootHashes(session); if (err != ERR_SUPERBLOCK_OK) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = session.actionsCounter; emit QueryMerkleRootHashes(superblockHash, sessionId, session.submitter); } } // @dev - Submitter sends hashes to verify superblock merkle root function doVerifyMerkleRootHashes(BattleSession storage session, bytes32[] blockHashes) internal returns (uint) { if (!hasDeposit(msg.sender, verifySuperblockCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } require(session.blockHashes.length == 0); if (session.challengeState == ChallengeState.QueryMerkleRootHashes) { (bytes32 merkleRoot, , , , bytes32 lastHash, , , ,,) = getSuperblockInfo(session.superblockHash); if (lastHash != blockHashes[blockHashes.length - 1]){ return ERR_SUPERBLOCK_BAD_LASTBLOCK; } if (merkleRoot != SyscoinMessageLibrary.makeMerkle(blockHashes)) { return ERR_SUPERBLOCK_INVALID_MERKLE; } (uint err, ) = bondDeposit(session.superblockHash, msg.sender, verifySuperblockCost); if (err != ERR_SUPERBLOCK_OK) { return err; } session.blockHashes = blockHashes; session.challengeState = ChallengeState.RespondMerkleRootHashes; return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - For the submitter to respond to challenger queries function respondMerkleRootHashes(bytes32 superblockHash, bytes32 sessionId, bytes32[] blockHashes) onlyClaimant(sessionId) public { BattleSession storage session = sessions[sessionId]; uint err = doVerifyMerkleRootHashes(session, blockHashes); if (err != 0) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionClaimant = session.actionsCounter; emit RespondMerkleRootHashes(superblockHash, sessionId, session.challenger, blockHashes); } } // @dev - Challenger makes a query for block header data for a hash function doQueryBlockHeader(BattleSession storage session, bytes32 blockHash) internal returns (uint) { if (!hasDeposit(msg.sender, respondBlockHeaderCost)) { return ERR_SUPERBLOCK_MIN_DEPOSIT; } if ((session.countBlockHeaderQueries == 0 && session.challengeState == ChallengeState.RespondMerkleRootHashes) || (session.countBlockHeaderQueries > 0 && session.challengeState == ChallengeState.RespondBlockHeader)) { require(session.countBlockHeaderQueries < session.blockHashes.length); require(session.blocksInfo[blockHash].status == BlockInfoStatus.Uninitialized); (uint err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost); if (err != ERR_SUPERBLOCK_OK) { return err; } session.countBlockHeaderQueries += 1; session.blocksInfo[blockHash].status = BlockInfoStatus.Requested; session.challengeState = ChallengeState.QueryBlockHeader; return ERR_SUPERBLOCK_OK; } return ERR_SUPERBLOCK_BAD_STATUS; } // @dev - For the challenger to start a query function queryBlockHeader(bytes32 superblockHash, bytes32 sessionId, bytes32 blockHash) onlyChallenger(sessionId) public { BattleSession storage session = sessions[sessionId]; uint err = doQueryBlockHeader(session, blockHash); if (err != ERR_SUPERBLOCK_OK) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionChallenger = session.actionsCounter; emit QueryBlockHeader(superblockHash, sessionId, session.submitter, blockHash); } } // @dev - Verify that block timestamp is in the superblock timestamp interval function verifyTimestamp(bytes32 superblockHash, bytes blockHeader) internal view returns (bool) { uint blockTimestamp = SyscoinMessageLibrary.getTimestamp(blockHeader); uint superblockTimestamp; (, , superblockTimestamp, , , , , ,,) = getSuperblockInfo(superblockHash); // Block timestamp to be within the expected timestamp of the superblock return (blockTimestamp <= superblockTimestamp) && (blockTimestamp / superblockDuration >= superblockTimestamp / superblockDuration - 1); } // @dev - Verify Syscoin block AuxPoW function verifyBlockAuxPoW( BlockInfo storage blockInfo, bytes32 blockHash, bytes blockHeader ) internal returns (uint, bytes) { (uint err, bool isMergeMined) = SyscoinMessageLibrary.verifyBlockHeader(blockHeader, 0, uint(blockHash)); if (err != 0) { return (err, new bytes(0)); } bytes memory powBlockHeader = (isMergeMined) ? SyscoinMessageLibrary.sliceArray(blockHeader, blockHeader.length - 80, blockHeader.length) : SyscoinMessageLibrary.sliceArray(blockHeader, 0, 80); blockInfo.timestamp = SyscoinMessageLibrary.getTimestamp(blockHeader); blockInfo.bits = SyscoinMessageLibrary.getBits(blockHeader); blockInfo.prevBlock = bytes32(SyscoinMessageLibrary.getHashPrevBlock(blockHeader)); blockInfo.blockHash = blockHash; blockInfo.powBlockHeader = powBlockHeader; return (ERR_SUPERBLOCK_OK, powBlockHeader); } // @dev - Verify block header sent by challenger function doVerifyBlockHeader( BattleSession storage session, bytes memory blockHeader ) internal returns (uint, bytes) { if (!hasDeposit(msg.sender, respondBlockHeaderCost)) { return (ERR_SUPERBLOCK_MIN_DEPOSIT, new bytes(0)); } if (session.challengeState == ChallengeState.QueryBlockHeader) { bytes32 blockSha256Hash = bytes32(SyscoinMessageLibrary.dblShaFlipMem(blockHeader, 0, 80)); BlockInfo storage blockInfo = session.blocksInfo[blockSha256Hash]; if (blockInfo.status != BlockInfoStatus.Requested) { return (ERR_SUPERBLOCK_BAD_SYSCOIN_STATUS, new bytes(0)); } if (!verifyTimestamp(session.superblockHash, blockHeader)) { return (ERR_SUPERBLOCK_BAD_TIMESTAMP, new bytes(0)); } // pass in blockSha256Hash here instead of proposedScryptHash because we // don't need a proposed hash (we already calculated it here, syscoin uses // sha256 just like bitcoin) (uint err, bytes memory powBlockHeader) = verifyBlockAuxPoW(blockInfo, blockSha256Hash, blockHeader); if (err != ERR_SUPERBLOCK_OK) { return (err, new bytes(0)); } // set to verify block header status blockInfo.status = BlockInfoStatus.Verified; (err, ) = bondDeposit(session.superblockHash, msg.sender, respondBlockHeaderCost); if (err != ERR_SUPERBLOCK_OK) { return (err, new bytes(0)); } session.countBlockHeaderResponses += 1; // if header responses matches num block hashes we skip to respond block header instead of pending verification if (session.countBlockHeaderResponses == session.blockHashes.length) { session.challengeState = ChallengeState.PendingVerification; } else { session.challengeState = ChallengeState.RespondBlockHeader; } return (ERR_SUPERBLOCK_OK, powBlockHeader); } return (ERR_SUPERBLOCK_BAD_STATUS, new bytes(0)); } // @dev - For the submitter to respond to challenger queries function respondBlockHeader( bytes32 superblockHash, bytes32 sessionId, bytes memory blockHeader ) onlyClaimant(sessionId) public { BattleSession storage session = sessions[sessionId]; (uint err, bytes memory powBlockHeader) = doVerifyBlockHeader(session, blockHeader); if (err != 0) { emit ErrorBattle(sessionId, err); } else { session.actionsCounter += 1; session.lastActionTimestamp = block.timestamp; session.lastActionClaimant = session.actionsCounter; emit RespondBlockHeader(superblockHash, sessionId, session.challenger, blockHeader, powBlockHeader); } } // @dev - Validate superblock information from last blocks function validateLastBlocks(BattleSession storage session) internal view returns (uint) { if (session.blockHashes.length <= 0) { return ERR_SUPERBLOCK_BAD_LASTBLOCK; } uint lastTimestamp; uint prevTimestamp; uint32 lastBits; bytes32 parentId; (, , lastTimestamp, prevTimestamp, , lastBits, parentId,,,) = getSuperblockInfo(session.superblockHash); bytes32 blockSha256Hash = session.blockHashes[session.blockHashes.length - 1]; if (session.blocksInfo[blockSha256Hash].timestamp != lastTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } if (session.blocksInfo[blockSha256Hash].bits != lastBits) { return ERR_SUPERBLOCK_BAD_BITS; } if (prevTimestamp > lastTimestamp) { return ERR_SUPERBLOCK_BAD_TIMESTAMP; } return ERR_SUPERBLOCK_OK; } // @dev - Validate superblock accumulated work function validateProofOfWork(BattleSession storage session) internal view returns (uint) { uint accWork; bytes32 prevBlock; uint32 prevHeight; uint32 proposedHeight; uint prevTimestamp; (, accWork, , prevTimestamp, , , prevBlock, ,,proposedHeight) = getSuperblockInfo(session.superblockHash); uint parentTimestamp; uint32 prevBits; uint work; (, work, parentTimestamp, , prevBlock, prevBits, , , ,prevHeight) = getSuperblockInfo(prevBlock); if (proposedHeight != (prevHeight+uint32(session.blockHashes.length))) { return ERR_SUPERBLOCK_BAD_BLOCKHEIGHT; } uint ret = validateSuperblockProofOfWork(session, parentTimestamp, prevHeight, work, accWork, prevTimestamp, prevBits, prevBlock); if(ret != 0){ return ret; } return ERR_SUPERBLOCK_OK; } function validateSuperblockProofOfWork(BattleSession storage session, uint parentTimestamp, uint32 prevHeight, uint work, uint accWork, uint prevTimestamp, uint32 prevBits, bytes32 prevBlock) internal view returns (uint){ uint32 idx = 0; while (idx < session.blockHashes.length) { bytes32 blockSha256Hash = session.blockHashes[idx]; uint32 bits = session.blocksInfo[blockSha256Hash].bits; if (session.blocksInfo[blockSha256Hash].prevBlock != prevBlock) { return ERR_SUPERBLOCK_BAD_PARENT; } if (net != SyscoinMessageLibrary.Network.REGTEST) { uint32 newBits; if (net == SyscoinMessageLibrary.Network.TESTNET && session.blocksInfo[blockSha256Hash].timestamp - parentTimestamp > 120) { newBits = 0x1e0fffff; } else if((prevHeight+idx+1) % SyscoinMessageLibrary.difficultyAdjustmentInterval() != 0){ newBits = prevBits; } else{ newBits = SyscoinMessageLibrary.calculateDifficulty(int64(parentTimestamp) - int64(prevTimestamp), prevBits); prevTimestamp = parentTimestamp; prevBits = bits; } if (bits != newBits) { return ERR_SUPERBLOCK_BAD_BITS; } } work += SyscoinMessageLibrary.diffFromBits(bits); prevBlock = blockSha256Hash; parentTimestamp = session.blocksInfo[blockSha256Hash].timestamp; idx += 1; } if (net != SyscoinMessageLibrary.Network.REGTEST && work != accWork) { return ERR_SUPERBLOCK_BAD_ACCUMULATED_WORK; } return 0; } // @dev - Verify whether a superblock's data is consistent // Only should be called when all blocks header were submitted function doVerifySuperblock(BattleSession storage session, bytes32 sessionId) internal returns (uint) { if (session.challengeState == ChallengeState.PendingVerification) { uint err; err = validateLastBlocks(session); if (err != 0) { emit ErrorBattle(sessionId, err); return 2; } err = validateProofOfWork(session); if (err != 0) { emit ErrorBattle(sessionId, err); return 2; } return 1; } else if (session.challengeState == ChallengeState.SuperblockFailed) { return 2; } return 0; } // @dev - Perform final verification once all blocks were submitted function verifySuperblock(bytes32 sessionId) public { BattleSession storage session = sessions[sessionId]; uint status = doVerifySuperblock(session, sessionId); if (status == 1) { convictChallenger(sessionId, session.challenger, session.superblockHash); } else if (status == 2) { convictSubmitter(sessionId, session.submitter, session.superblockHash); } } // @dev - Trigger conviction if response is not received in time function timeout(bytes32 sessionId) public returns (uint) { BattleSession storage session = sessions[sessionId]; if (session.challengeState == ChallengeState.SuperblockFailed || (session.lastActionChallenger > session.lastActionClaimant && block.timestamp > session.lastActionTimestamp + superblockTimeout)) { convictSubmitter(sessionId, session.submitter, session.superblockHash); return ERR_SUPERBLOCK_OK; } else if (session.lastActionClaimant > session.lastActionChallenger && block.timestamp > session.lastActionTimestamp + superblockTimeout) { convictChallenger(sessionId, session.challenger, session.superblockHash); return ERR_SUPERBLOCK_OK; } emit ErrorBattle(sessionId, ERR_SUPERBLOCK_NO_TIMEOUT); return ERR_SUPERBLOCK_NO_TIMEOUT; } // @dev - To be called when a challenger is convicted function convictChallenger(bytes32 sessionId, address challenger, bytes32 superblockHash) internal { BattleSession storage session = sessions[sessionId]; sessionDecided(sessionId, superblockHash, session.submitter, session.challenger); disable(sessionId); emit ChallengerConvicted(superblockHash, sessionId, challenger); } // @dev - To be called when a submitter is convicted function convictSubmitter(bytes32 sessionId, address submitter, bytes32 superblockHash) internal { BattleSession storage session = sessions[sessionId]; sessionDecided(sessionId, superblockHash, session.challenger, session.submitter); disable(sessionId); emit SubmitterConvicted(superblockHash, sessionId, submitter); } // @dev - Disable session // It should be called only when either the submitter or the challenger were convicted. function disable(bytes32 sessionId) internal { delete sessions[sessionId]; } // @dev - Check if a session's challenger did not respond before timeout function getChallengerHitTimeout(bytes32 sessionId) public view returns (bool) { BattleSession storage session = sessions[sessionId]; return (session.lastActionClaimant > session.lastActionChallenger && block.timestamp > session.lastActionTimestamp + superblockTimeout); } // @dev - Check if a session's submitter did not respond before timeout function getSubmitterHitTimeout(bytes32 sessionId) public view returns (bool) { BattleSession storage session = sessions[sessionId]; return (session.lastActionChallenger > session.lastActionClaimant && block.timestamp > session.lastActionTimestamp + superblockTimeout); } // @dev - Return Syscoin block hashes associated with a certain battle session function getSyscoinBlockHashes(bytes32 sessionId) public view returns (bytes32[]) { return sessions[sessionId].blockHashes; } // @dev - To be called when a battle sessions was decided function sessionDecided(bytes32 sessionId, bytes32 superblockHash, address winner, address loser) internal { trustedSyscoinClaimManager.sessionDecided(sessionId, superblockHash, winner, loser); } // @dev - Retrieve superblock information function getSuperblockInfo(bytes32 superblockHash) internal view returns ( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, address _submitter, SyscoinSuperblocks.Status _status, uint32 _height ) { return trustedSuperblocks.getSuperblock(superblockHash); } // @dev - Verify whether a user has a certain amount of deposits or more function hasDeposit(address who, uint amount) internal view returns (bool) { return trustedSyscoinClaimManager.getDeposit(who) >= amount; } // @dev – locks up part of a user's deposit into a claim. function bondDeposit(bytes32 superblockHash, address account, uint amount) internal returns (uint, uint) { return trustedSyscoinClaimManager.bondDeposit(superblockHash, account, amount); } } // @dev - Manager of superblock claims // // Manages superblocks proposal and challenges contract SyscoinClaimManager is SyscoinDepositsManager, SyscoinErrorCodes { using SafeMath for uint; struct SuperblockClaim { bytes32 superblockHash; // Superblock Id address submitter; // Superblock submitter uint createdAt; // Superblock creation time address[] challengers; // List of challengers mapping (address => uint) bondedDeposits; // Deposit associated to challengers uint currentChallenger; // Index of challenger in current session mapping (address => bytes32) sessions; // Challenge sessions uint challengeTimeout; // Claim timeout bool verificationOngoing; // Challenge session has started bool decided; // If the claim was decided bool invalid; // If superblock is invalid } // Active superblock claims mapping (bytes32 => SuperblockClaim) public claims; // Superblocks contract SyscoinSuperblocks public trustedSuperblocks; // Battle manager contract SyscoinBattleManager public trustedSyscoinBattleManager; // Confirmations required to confirm semi approved superblocks uint public superblockConfirmations; // Monetary reward for opponent in case battle is lost uint public battleReward; uint public superblockDelay; // Delay required to submit superblocks (in seconds) uint public superblockTimeout; // Timeout for action (in seconds) event DepositBonded(bytes32 superblockHash, address account, uint amount); event DepositUnbonded(bytes32 superblockHash, address account, uint amount); event SuperblockClaimCreated(bytes32 superblockHash, address submitter); event SuperblockClaimChallenged(bytes32 superblockHash, address challenger); event SuperblockBattleDecided(bytes32 sessionId, address winner, address loser); event SuperblockClaimSuccessful(bytes32 superblockHash, address submitter); event SuperblockClaimPending(bytes32 superblockHash, address submitter); event SuperblockClaimFailed(bytes32 superblockHash, address submitter); event VerificationGameStarted(bytes32 superblockHash, address submitter, address challenger, bytes32 sessionId); event ErrorClaim(bytes32 superblockHash, uint err); modifier onlyBattleManager() { require(msg.sender == address(trustedSyscoinBattleManager)); _; } modifier onlyMeOrBattleManager() { require(msg.sender == address(trustedSyscoinBattleManager) || msg.sender == address(this)); _; } // @dev – Sets up the contract managing superblock challenges // @param _superblocks Contract that manages superblocks // @param _battleManager Contract that manages battles // @param _superblockDelay Delay to accept a superblock submission (in seconds) // @param _superblockTimeout Time to wait for challenges (in seconds) // @param _superblockConfirmations Confirmations required to confirm semi approved superblocks constructor( SyscoinSuperblocks _superblocks, SyscoinBattleManager _syscoinBattleManager, uint _superblockDelay, uint _superblockTimeout, uint _superblockConfirmations, uint _battleReward ) public { trustedSuperblocks = _superblocks; trustedSyscoinBattleManager = _syscoinBattleManager; superblockDelay = _superblockDelay; superblockTimeout = _superblockTimeout; superblockConfirmations = _superblockConfirmations; battleReward = _battleReward; } // @dev – locks up part of a user's deposit into a claim. // @param superblockHash – claim id. // @param account – user's address. // @param amount – amount of deposit to lock up. // @return – user's deposit bonded for the claim. function bondDeposit(bytes32 superblockHash, address account, uint amount) onlyMeOrBattleManager external returns (uint, uint) { SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { return (ERR_SUPERBLOCK_BAD_CLAIM, 0); } if (deposits[account] < amount) { return (ERR_SUPERBLOCK_MIN_DEPOSIT, deposits[account]); } deposits[account] = deposits[account].sub(amount); claim.bondedDeposits[account] = claim.bondedDeposits[account].add(amount); emit DepositBonded(superblockHash, account, amount); return (ERR_SUPERBLOCK_OK, claim.bondedDeposits[account]); } // @dev – accessor for a claim's bonded deposits. // @param superblockHash – claim id. // @param account – user's address. // @return – user's deposit bonded for the claim. function getBondedDeposit(bytes32 superblockHash, address account) public view returns (uint) { SuperblockClaim storage claim = claims[superblockHash]; require(claimExists(claim)); return claim.bondedDeposits[account]; } function getDeposit(address account) public view returns (uint) { return deposits[account]; } // @dev – unlocks a user's bonded deposits from a claim. // @param superblockHash – claim id. // @param account – user's address. // @return – user's deposit which was unbonded from the claim. function unbondDeposit(bytes32 superblockHash, address account) internal returns (uint, uint) { SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { return (ERR_SUPERBLOCK_BAD_CLAIM, 0); } if (!claim.decided) { return (ERR_SUPERBLOCK_BAD_STATUS, 0); } uint bondedDeposit = claim.bondedDeposits[account]; delete claim.bondedDeposits[account]; deposits[account] = deposits[account].add(bondedDeposit); emit DepositUnbonded(superblockHash, account, bondedDeposit); return (ERR_SUPERBLOCK_OK, bondedDeposit); } // @dev – Propose a new superblock. // // @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock // @param _accumulatedWork Accumulated proof of work of the last block in the superblock // @param _timestamp Timestamp of the last block in the superblock // @param _prevTimestamp Timestamp of the block when the last difficulty adjustment happened // @param _lastHash Hash of the last block in the superblock // @param _lastBits Difficulty bits of the last block in the superblock // @param _parentHash Id of the parent superblock // @return Error code and superblockHash function proposeSuperblock( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentHash, uint32 _blockHeight ) public returns (uint, bytes32) { require(address(trustedSuperblocks) != 0); if (deposits[msg.sender] < minProposalDeposit) { emit ErrorClaim(0, ERR_SUPERBLOCK_MIN_DEPOSIT); return (ERR_SUPERBLOCK_MIN_DEPOSIT, 0); } if (_timestamp + superblockDelay > block.timestamp) { emit ErrorClaim(0, ERR_SUPERBLOCK_BAD_TIMESTAMP); return (ERR_SUPERBLOCK_BAD_TIMESTAMP, 0); } uint err; bytes32 superblockHash; (err, superblockHash) = trustedSuperblocks.propose(_blocksMerkleRoot, _accumulatedWork, _timestamp, _prevTimestamp, _lastHash, _lastBits, _parentHash, _blockHeight,msg.sender); if (err != 0) { emit ErrorClaim(superblockHash, err); return (err, superblockHash); } SuperblockClaim storage claim = claims[superblockHash]; // allow to propose an existing claim only if its invalid and decided and its a different submitter or not on the tip // those are the ones that may actually be stuck and need to be proposed again, // but we want to ensure its not the same submitter submitting the same thing if (claimExists(claim)) { bool allowed = claim.invalid == true && claim.decided == true && claim.submitter != msg.sender; if(allowed){ // we also want to ensure that if parent is approved we are building on the tip and not anywhere else if(trustedSuperblocks.getSuperblockStatus(_parentHash) == SyscoinSuperblocks.Status.Approved){ allowed = trustedSuperblocks.getBestSuperblock() == _parentHash; } // or if its semi approved allow to build on top as well else if(trustedSuperblocks.getSuperblockStatus(_parentHash) == SyscoinSuperblocks.Status.SemiApproved){ allowed = true; } else{ allowed = false; } } if(!allowed){ emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return (ERR_SUPERBLOCK_BAD_CLAIM, superblockHash); } } claim.superblockHash = superblockHash; claim.submitter = msg.sender; claim.currentChallenger = 0; claim.decided = false; claim.invalid = false; claim.verificationOngoing = false; claim.createdAt = block.timestamp; claim.challengeTimeout = block.timestamp + superblockTimeout; claim.challengers.length = 0; (err, ) = this.bondDeposit(superblockHash, msg.sender, battleReward); assert(err == ERR_SUPERBLOCK_OK); emit SuperblockClaimCreated(superblockHash, msg.sender); return (ERR_SUPERBLOCK_OK, superblockHash); } // @dev – challenge a superblock claim. // @param superblockHash – Id of the superblock to challenge. // @return - Error code and claim Id function challengeSuperblock(bytes32 superblockHash) public returns (uint, bytes32) { require(address(trustedSuperblocks) != 0); SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return (ERR_SUPERBLOCK_BAD_CLAIM, superblockHash); } if (claim.decided) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_CLAIM_DECIDED); return (ERR_SUPERBLOCK_CLAIM_DECIDED, superblockHash); } if (deposits[msg.sender] < minChallengeDeposit) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_MIN_DEPOSIT); return (ERR_SUPERBLOCK_MIN_DEPOSIT, superblockHash); } uint err; (err, ) = trustedSuperblocks.challenge(superblockHash, msg.sender); if (err != 0) { emit ErrorClaim(superblockHash, err); return (err, 0); } (err, ) = this.bondDeposit(superblockHash, msg.sender, battleReward); assert(err == ERR_SUPERBLOCK_OK); claim.challengeTimeout = block.timestamp + superblockTimeout; claim.challengers.push(msg.sender); emit SuperblockClaimChallenged(superblockHash, msg.sender); if (!claim.verificationOngoing) { runNextBattleSession(superblockHash); } return (ERR_SUPERBLOCK_OK, superblockHash); } // @dev – runs a battle session to verify a superblock for the next challenger // @param superblockHash – claim id. function runNextBattleSession(bytes32 superblockHash) internal returns (bool) { SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return false; } // superblocks marked as invalid do not have to run remaining challengers if (claim.decided || claim.invalid) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_CLAIM_DECIDED); return false; } if (claim.verificationOngoing) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_VERIFICATION_PENDING); return false; } if (claim.currentChallenger < claim.challengers.length) { bytes32 sessionId = trustedSyscoinBattleManager.beginBattleSession(superblockHash, claim.submitter, claim.challengers[claim.currentChallenger]); claim.sessions[claim.challengers[claim.currentChallenger]] = sessionId; emit VerificationGameStarted(superblockHash, claim.submitter, claim.challengers[claim.currentChallenger], sessionId); claim.verificationOngoing = true; claim.currentChallenger += 1; } return true; } // @dev – check whether a claim has successfully withstood all challenges. // If successful without challenges, it will mark the superblock as confirmed. // If successful with at least one challenge, it will mark the superblock as semi-approved. // If verification failed, it will mark the superblock as invalid. // // @param superblockHash – claim ID. function checkClaimFinished(bytes32 superblockHash) public returns (bool) { SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return false; } // check that there is no ongoing verification game. if (claim.verificationOngoing) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_VERIFICATION_PENDING); return false; } // an invalid superblock can be rejected immediately if (claim.invalid) { // The superblock is invalid, submitter abandoned // or superblock data is inconsistent claim.decided = true; trustedSuperblocks.invalidate(claim.superblockHash, msg.sender); emit SuperblockClaimFailed(superblockHash, claim.submitter); doPayChallengers(superblockHash, claim); return false; } // check that the claim has exceeded the claim's specific challenge timeout. if (block.timestamp <= claim.challengeTimeout) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_NO_TIMEOUT); return false; } // check that all verification games have been played. if (claim.currentChallenger < claim.challengers.length) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_VERIFICATION_PENDING); return false; } claim.decided = true; bool confirmImmediately = false; // No challengers and parent approved; confirm immediately if (claim.challengers.length == 0) { bytes32 parentId = trustedSuperblocks.getSuperblockParentId(claim.superblockHash); SyscoinSuperblocks.Status status = trustedSuperblocks.getSuperblockStatus(parentId); if (status == SyscoinSuperblocks.Status.Approved) { confirmImmediately = true; } } if (confirmImmediately) { trustedSuperblocks.confirm(claim.superblockHash, msg.sender); unbondDeposit(superblockHash, claim.submitter); emit SuperblockClaimSuccessful(superblockHash, claim.submitter); } else { trustedSuperblocks.semiApprove(claim.superblockHash, msg.sender); emit SuperblockClaimPending(superblockHash, claim.submitter); } return true; } // @dev – confirm semi approved superblock. // // A semi approved superblock can be confirmed if it has several descendant // superblocks that are also semi-approved. // If none of the descendants were challenged they will also be confirmed. // // @param superblockHash – the claim ID. // @param descendantId - claim ID descendants function confirmClaim(bytes32 superblockHash, bytes32 descendantId) public returns (bool) { uint numSuperblocks = 0; bool confirmDescendants = true; bytes32 id = descendantId; SuperblockClaim storage claim = claims[id]; while (id != superblockHash) { if (!claimExists(claim)) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return false; } if (trustedSuperblocks.getSuperblockStatus(id) != SyscoinSuperblocks.Status.SemiApproved) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return false; } if (confirmDescendants && claim.challengers.length > 0) { confirmDescendants = false; } id = trustedSuperblocks.getSuperblockParentId(id); claim = claims[id]; numSuperblocks += 1; } if (numSuperblocks < superblockConfirmations) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_MISSING_CONFIRMATIONS); return false; } if (trustedSuperblocks.getSuperblockStatus(id) != SyscoinSuperblocks.Status.SemiApproved) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return false; } bytes32 parentId = trustedSuperblocks.getSuperblockParentId(superblockHash); if (trustedSuperblocks.getSuperblockStatus(parentId) != SyscoinSuperblocks.Status.Approved) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return false; } (uint err, ) = trustedSuperblocks.confirm(superblockHash, msg.sender); if (err != ERR_SUPERBLOCK_OK) { emit ErrorClaim(superblockHash, err); return false; } emit SuperblockClaimSuccessful(superblockHash, claim.submitter); doPaySubmitter(superblockHash, claim); unbondDeposit(superblockHash, claim.submitter); if (confirmDescendants) { bytes32[] memory descendants = new bytes32[](numSuperblocks); id = descendantId; uint idx = 0; while (id != superblockHash) { descendants[idx] = id; id = trustedSuperblocks.getSuperblockParentId(id); idx += 1; } while (idx > 0) { idx -= 1; id = descendants[idx]; claim = claims[id]; (err, ) = trustedSuperblocks.confirm(id, msg.sender); require(err == ERR_SUPERBLOCK_OK); emit SuperblockClaimSuccessful(id, claim.submitter); doPaySubmitter(id, claim); unbondDeposit(id, claim.submitter); } } return true; } // @dev – Reject a semi approved superblock. // // Superblocks that are not in the main chain can be marked as // invalid. // // @param superblockHash – the claim ID. function rejectClaim(bytes32 superblockHash) public returns (bool) { SuperblockClaim storage claim = claims[superblockHash]; if (!claimExists(claim)) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM); return false; } uint height = trustedSuperblocks.getSuperblockHeight(superblockHash); bytes32 id = trustedSuperblocks.getBestSuperblock(); if (trustedSuperblocks.getSuperblockHeight(id) < height + superblockConfirmations) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_MISSING_CONFIRMATIONS); return false; } id = trustedSuperblocks.getSuperblockAt(height); if (id != superblockHash) { SyscoinSuperblocks.Status status = trustedSuperblocks.getSuperblockStatus(superblockHash); if (status != SyscoinSuperblocks.Status.SemiApproved) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS); return false; } if (!claim.decided) { emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_CLAIM_DECIDED); return false; } trustedSuperblocks.invalidate(superblockHash, msg.sender); emit SuperblockClaimFailed(superblockHash, claim.submitter); doPayChallengers(superblockHash, claim); return true; } return false; } // @dev – called when a battle session has ended. // // @param sessionId – session Id. // @param superblockHash - claim Id // @param winner – winner of verification game. // @param loser – loser of verification game. function sessionDecided(bytes32 sessionId, bytes32 superblockHash, address winner, address loser) public onlyBattleManager { SuperblockClaim storage claim = claims[superblockHash]; require(claimExists(claim)); claim.verificationOngoing = false; if (claim.submitter == loser) { // the claim is over. // Trigger end of verification game claim.invalid = true; } else if (claim.submitter == winner) { // the claim continues. // It should not fail when called from sessionDecided runNextBattleSession(superblockHash); } else { revert(); } emit SuperblockBattleDecided(sessionId, winner, loser); } // @dev - Pay challengers than ran their battles with submitter deposits // Challengers that did not run will be returned their deposits function doPayChallengers(bytes32 superblockHash, SuperblockClaim storage claim) internal { uint rewards = claim.bondedDeposits[claim.submitter]; claim.bondedDeposits[claim.submitter] = 0; uint totalDeposits = 0; uint idx = 0; for (idx = 0; idx < claim.currentChallenger; ++idx) { totalDeposits = totalDeposits.add(claim.bondedDeposits[claim.challengers[idx]]); } address challenger; uint reward = 0; if(totalDeposits == 0 && claim.currentChallenger > 0){ reward = rewards.div(claim.currentChallenger); } for (idx = 0; idx < claim.currentChallenger; ++idx) { reward = 0; challenger = claim.challengers[idx]; if(totalDeposits > 0){ reward = rewards.mul(claim.bondedDeposits[challenger]).div(totalDeposits); } claim.bondedDeposits[challenger] = claim.bondedDeposits[challenger].add(reward); } uint bondedDeposit; for (idx = 0; idx < claim.challengers.length; ++idx) { challenger = claim.challengers[idx]; bondedDeposit = claim.bondedDeposits[challenger]; deposits[challenger] = deposits[challenger].add(bondedDeposit); claim.bondedDeposits[challenger] = 0; emit DepositUnbonded(superblockHash, challenger, bondedDeposit); } } // @dev - Pay submitter with challenger deposits function doPaySubmitter(bytes32 superblockHash, SuperblockClaim storage claim) internal { address challenger; uint bondedDeposit; for (uint idx=0; idx < claim.challengers.length; ++idx) { challenger = claim.challengers[idx]; bondedDeposit = claim.bondedDeposits[challenger]; claim.bondedDeposits[challenger] = 0; claim.bondedDeposits[claim.submitter] = claim.bondedDeposits[claim.submitter].add(bondedDeposit); } unbondDeposit(superblockHash, claim.submitter); } // @dev - Check if a superblock can be semi approved by calling checkClaimFinished function getInBattleAndSemiApprovable(bytes32 superblockHash) public view returns (bool) { SuperblockClaim storage claim = claims[superblockHash]; return (trustedSuperblocks.getSuperblockStatus(superblockHash) == SyscoinSuperblocks.Status.InBattle && !claim.invalid && !claim.verificationOngoing && block.timestamp > claim.challengeTimeout && claim.currentChallenger >= claim.challengers.length); } // @dev – Check if a claim exists function claimExists(SuperblockClaim claim) private pure returns (bool) { return (claim.submitter != 0x0); } // @dev - Return a given superblock's submitter function getClaimSubmitter(bytes32 superblockHash) public view returns (address) { return claims[superblockHash].submitter; } // @dev - Return superblock submission timestamp function getNewSuperblockEventTimestamp(bytes32 superblockHash) public view returns (uint) { return claims[superblockHash].createdAt; } // @dev - Return whether or not a claim has already been made function getClaimExists(bytes32 superblockHash) public view returns (bool) { return claimExists(claims[superblockHash]); } // @dev - Return claim status function getClaimDecided(bytes32 superblockHash) public view returns (bool) { return claims[superblockHash].decided; } // @dev - Check if a claim is invalid function getClaimInvalid(bytes32 superblockHash) public view returns (bool) { // TODO: see if this is redundant with superblock status return claims[superblockHash].invalid; } // @dev - Check if a claim has a verification game in progress function getClaimVerificationOngoing(bytes32 superblockHash) public view returns (bool) { return claims[superblockHash].verificationOngoing; } // @dev - Returns timestamp of challenge timeout function getClaimChallengeTimeout(bytes32 superblockHash) public view returns (uint) { return claims[superblockHash].challengeTimeout; } // @dev - Return the number of challengers whose battles haven't been decided yet function getClaimRemainingChallengers(bytes32 superblockHash) public view returns (uint) { SuperblockClaim storage claim = claims[superblockHash]; return claim.challengers.length - (claim.currentChallenger); } // @dev – Return session by challenger function getSession(bytes32 superblockHash, address challenger) public view returns(bytes32) { return claims[superblockHash].sessions[challenger]; } function getClaimChallengers(bytes32 superblockHash) public view returns (address[]) { SuperblockClaim storage claim = claims[superblockHash]; return claim.challengers; } function getSuperblockInfo(bytes32 superblockHash) internal view returns ( bytes32 _blocksMerkleRoot, uint _accumulatedWork, uint _timestamp, uint _prevTimestamp, bytes32 _lastHash, uint32 _lastBits, bytes32 _parentId, address _submitter, SyscoinSuperblocks.Status _status, uint32 _height ) { return trustedSuperblocks.getSuperblock(superblockHash); } }
@dev - Verify Syscoin block AuxPoW
function verifyBlockAuxPoW( BlockInfo storage blockInfo, bytes32 blockHash, bytes blockHeader ) internal returns (uint, bytes) { (uint err, bool isMergeMined) = SyscoinMessageLibrary.verifyBlockHeader(blockHeader, 0, uint(blockHash)); if (err != 0) { return (err, new bytes(0)); } bytes memory powBlockHeader = (isMergeMined) ? SyscoinMessageLibrary.sliceArray(blockHeader, blockHeader.length - 80, blockHeader.length) : SyscoinMessageLibrary.sliceArray(blockHeader, 0, 80); blockInfo.timestamp = SyscoinMessageLibrary.getTimestamp(blockHeader); blockInfo.bits = SyscoinMessageLibrary.getBits(blockHeader); blockInfo.prevBlock = bytes32(SyscoinMessageLibrary.getHashPrevBlock(blockHeader)); blockInfo.blockHash = blockHash; blockInfo.powBlockHeader = powBlockHeader; return (ERR_SUPERBLOCK_OK, powBlockHeader); }
6,390,678
[ 1, 17, 8553, 16455, 1017, 885, 1203, 432, 2616, 29198, 59, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3929, 1768, 21981, 29198, 59, 12, 203, 3639, 3914, 966, 2502, 1203, 966, 16, 203, 3639, 1731, 1578, 31493, 16, 203, 3639, 1731, 1203, 1864, 203, 565, 262, 2713, 1135, 261, 11890, 16, 1731, 13, 288, 203, 3639, 261, 11890, 393, 16, 1426, 353, 6786, 49, 1920, 13, 273, 203, 5411, 16455, 1017, 885, 1079, 9313, 18, 8705, 1768, 1864, 12, 2629, 1864, 16, 374, 16, 2254, 12, 2629, 2310, 10019, 203, 3639, 309, 261, 370, 480, 374, 13, 288, 203, 5411, 327, 261, 370, 16, 394, 1731, 12, 20, 10019, 203, 3639, 289, 203, 3639, 1731, 3778, 7602, 1768, 1864, 273, 261, 291, 6786, 49, 1920, 13, 692, 203, 5411, 16455, 1017, 885, 1079, 9313, 18, 6665, 1076, 12, 2629, 1864, 16, 1203, 1864, 18, 2469, 300, 8958, 16, 1203, 1864, 18, 2469, 13, 294, 203, 5411, 16455, 1017, 885, 1079, 9313, 18, 6665, 1076, 12, 2629, 1864, 16, 374, 16, 8958, 1769, 203, 203, 3639, 1203, 966, 18, 5508, 273, 16455, 1017, 885, 1079, 9313, 18, 588, 4921, 12, 2629, 1864, 1769, 203, 3639, 1203, 966, 18, 6789, 273, 16455, 1017, 885, 1079, 9313, 18, 588, 6495, 12, 2629, 1864, 1769, 203, 3639, 1203, 966, 18, 10001, 1768, 273, 1731, 1578, 12, 10876, 1017, 885, 1079, 9313, 18, 588, 2310, 9958, 1768, 12, 2629, 1864, 10019, 203, 3639, 1203, 966, 18, 2629, 2310, 273, 31493, 31, 203, 3639, 1203, 966, 18, 23509, 1768, 1864, 273, 7602, 1768, 1864, 31, 203, 3639, 327, 261, 9712, 67, 13272, 654, 11403, 67, 3141, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title iOVM_CrossDomainMessenger */ interface iOVM_CrossDomainMessenger { /********** * Events * **********/ event SentMessage(bytes message); event RelayedMessage(bytes32 msgHash); event FailedRelayedMessage(bytes32 msgHash); /************* * Variables * *************/ function xDomainMessageSender() external view returns (address); /******************** * Public Functions * ********************/ /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes calldata _message, uint32 _gasLimit ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_CrossDomainMessenger } from "../../iOVM/bridge/messaging/iOVM_CrossDomainMessenger.sol"; /** * @title OVM_CrossDomainEnabled * @dev Helper contract for contracts performing cross-domain communications * * Compiler used: defined by inheriting contract * Runtime target: defined by inheriting contract */ contract OVM_CrossDomainEnabled { /************* * Variables * *************/ // Messenger contract used to send and recieve messages from the other domain. address public messenger; /*************** * Constructor * ***************/ /** * @param _messenger Address of the CrossDomainMessenger on the current layer. */ constructor( address _messenger ) { messenger = _messenger; } /********************** * Function Modifiers * **********************/ /** * Enforces that the modified function is only callable by a specific cross-domain account. * @param _sourceDomainAccount The only account on the originating domain which is * authenticated to call this function. */ modifier onlyFromCrossDomainAccount( address _sourceDomainAccount ) { require( msg.sender == address(getCrossDomainMessenger()), "OVM_XCHAIN: messenger contract unauthenticated" ); require( getCrossDomainMessenger().xDomainMessageSender() == _sourceDomainAccount, "OVM_XCHAIN: wrong sender of cross-domain message" ); _; } /********************** * Internal Functions * **********************/ /** * Gets the messenger, usually from storage. This function is exposed in case a child contract * needs to override. * @return The address of the cross-domain messenger contract which should be used. */ function getCrossDomainMessenger() internal virtual returns ( iOVM_CrossDomainMessenger ) { return iOVM_CrossDomainMessenger(messenger); } /** * Sends a message to an account on another domain * @param _crossDomainTarget The intended recipient on the destination domain * @param _message The data to send to the target (usually calldata to a function with * `onlyFromCrossDomainAccount()`) * @param _gasLimit The gasLimit for the receipt of the message on the target domain. */ function sendCrossDomainMessage( address _crossDomainTarget, uint32 _gasLimit, bytes memory _message ) internal { getCrossDomainMessenger().sendMessage(_crossDomainTarget, _message, _gasLimit); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1StandardBridge } from "../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol"; import { iOVM_L1ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol"; import { iOVM_L2ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol"; /* Library Imports */ import { ERC165Checker } from "@openzeppelin/contracts/introspection/ERC165Checker.sol"; import { OVM_CrossDomainEnabled } from "../../../libraries/bridge/OVM_CrossDomainEnabled.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { IL2StandardERC20 } from "../../../libraries/standards/IL2StandardERC20.sol"; /** * @title OVM_L2StandardBridge * @dev The L2 Standard bridge is a contract which works together with the L1 Standard bridge to * enable ETH and ERC20 transitions between L1 and L2. * This contract acts as a minter for new tokens when it hears about deposits into the L1 Standard * bridge. * This contract also acts as a burner of the tokens intended for withdrawal, informing the L1 * bridge to release L1 funds. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_L2StandardBridge is iOVM_L2ERC20Bridge, OVM_CrossDomainEnabled { /******************************** * External Contract References * ********************************/ address public l1TokenBridge; /*************** * Constructor * ***************/ /** * @param _l2CrossDomainMessenger Cross-domain messenger used by this contract. * @param _l1TokenBridge Address of the L1 bridge deployed to the main chain. */ constructor( address _l2CrossDomainMessenger, address _l1TokenBridge ) OVM_CrossDomainEnabled(_l2CrossDomainMessenger) { l1TokenBridge = _l1TokenBridge; } /*************** * Withdrawing * ***************/ /** * @inheritdoc iOVM_L2ERC20Bridge */ function withdraw( address _l2Token, uint256 _amount, uint32 _l1Gas, bytes calldata _data ) external override virtual { _initiateWithdrawal( _l2Token, msg.sender, msg.sender, _amount, _l1Gas, _data ); } /** * @inheritdoc iOVM_L2ERC20Bridge */ function withdrawTo( address _l2Token, address _to, uint256 _amount, uint32 _l1Gas, bytes calldata _data ) external override virtual { _initiateWithdrawal( _l2Token, msg.sender, _to, _amount, _l1Gas, _data ); } /** * @dev Performs the logic for deposits by storing the token and informing the L2 token Gateway * of the deposit. * @param _l2Token Address of L2 token where withdrawal was initiated. * @param _from Account to pull the deposit from on L2. * @param _to Account to give the withdrawal to on L1. * @param _amount Amount of the token to withdraw. * param _l1Gas Unused, but included for potential forward compatibility considerations. * @param _data Optional data to forward to L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function _initiateWithdrawal( address _l2Token, address _from, address _to, uint256 _amount, uint32 _l1Gas, bytes calldata _data ) internal { // When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2 // usage IL2StandardERC20(_l2Token).burn(msg.sender, _amount); // Construct calldata for l1TokenBridge.finalizeERC20Withdrawal(_to, _amount) address l1Token = IL2StandardERC20(_l2Token).l1Token(); bytes memory message; if (_l2Token == Lib_PredeployAddresses.OVM_ETH) { message = abi.encodeWithSelector( iOVM_L1StandardBridge.finalizeETHWithdrawal.selector, _from, _to, _amount, _data ); } else { message = abi.encodeWithSelector( iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector, l1Token, _l2Token, _from, _to, _amount, _data ); } // Send message up to L1 bridge sendCrossDomainMessage( l1TokenBridge, _l1Gas, message ); emit WithdrawalInitiated(l1Token, _l2Token, msg.sender, _to, _amount, _data); } /************************************ * Cross-chain Function: Depositing * ************************************/ /** * @inheritdoc iOVM_L2ERC20Bridge */ function finalizeDeposit( address _l1Token, address _l2Token, address _from, address _to, uint256 _amount, bytes calldata _data ) external override virtual onlyFromCrossDomainAccount(l1TokenBridge) { // Check the target token is compliant and // verify the deposited token on L1 matches the L2 deposited token representation here if ( ERC165Checker.supportsInterface(_l2Token, 0x1d1d8b63) && _l1Token == IL2StandardERC20(_l2Token).l1Token() ) { // When a deposit is finalized, we credit the account on L2 with the same amount of // tokens. IL2StandardERC20(_l2Token).mint(_to, _amount); emit DepositFinalized(_l1Token, _l2Token, _from, _to, _amount, _data); } else { // Either the L2 token which is being deposited-into disagrees about the correct address // of its L1 token, or does not support the correct interface. // This should only happen if there is a malicious L2 token, or if a user somehow // specified the wrong L2 token address to deposit into. // In either case, we stop the process here and construct a withdrawal // message so that users can get their funds out in some cases. // There is no way to prevent malicious token contracts altogether, but this does limit // user error and mitigate some forms of malicious contract behavior. bytes memory message = abi.encodeWithSelector( iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector, _l1Token, _l2Token, _to, // switched the _to and _from here to bounce back the deposit to the sender _from, _amount, _data ); // Send message up to L1 bridge sendCrossDomainMessage( l1TokenBridge, 0, message ); emit DepositFailed(_l1Token, _l2Token, _from, _to, _amount, _data); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0; pragma experimental ABIEncoderV2; import "./iOVM_L1ERC20Bridge.sol"; /** * @title iOVM_L1StandardBridge */ interface iOVM_L1StandardBridge is iOVM_L1ERC20Bridge { /********** * Events * **********/ event ETHDepositInitiated ( address indexed _from, address indexed _to, uint256 _amount, bytes _data ); event ETHWithdrawalFinalized ( address indexed _from, address indexed _to, uint256 _amount, bytes _data ); /******************** * Public Functions * ********************/ /** * @dev Deposit an amount of the ETH to the caller's balance on L2. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositETH ( uint32 _l2Gas, bytes calldata _data ) external payable; /** * @dev Deposit an amount of ETH to a recipient's balance on L2. * @param _to L2 address to credit the withdrawal to. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositETHTo ( address _to, uint32 _l2Gas, bytes calldata _data ) external payable; /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ETH token. Since only the xDomainMessenger can call this function, it will never be called * before the withdrawal is finalized. * @param _from L2 address initiating the transfer. * @param _to L1 address to credit the withdrawal to. * @param _amount Amount of the ERC20 to deposit. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function finalizeETHWithdrawal ( address _from, address _to, uint _amount, bytes calldata _data ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0; pragma experimental ABIEncoderV2; /** * @title iOVM_L1ERC20Bridge */ interface iOVM_L1ERC20Bridge { /********** * Events * **********/ event ERC20DepositInitiated ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); event ERC20WithdrawalFinalized ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); /******************** * Public Functions * ********************/ /** * @dev deposit an amount of the ERC20 to the caller's balance on L2. * @param _l1Token Address of the L1 ERC20 we are depositing * @param _l2Token Address of the L1 respective L2 ERC20 * @param _amount Amount of the ERC20 to deposit * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositERC20 ( address _l1Token, address _l2Token, uint _amount, uint32 _l2Gas, bytes calldata _data ) external; /** * @dev deposit an amount of ERC20 to a recipient's balance on L2. * @param _l1Token Address of the L1 ERC20 we are depositing * @param _l2Token Address of the L1 respective L2 ERC20 * @param _to L2 address to credit the withdrawal to. * @param _amount Amount of the ERC20 to deposit. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function depositERC20To ( address _l1Token, address _l2Token, address _to, uint _amount, uint32 _l2Gas, bytes calldata _data ) external; /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the * L1 ERC20 token. * This call will fail if the initialized withdrawal from L2 has not been finalized. * * @param _l1Token Address of L1 token to finalizeWithdrawal for. * @param _l2Token Address of L2 token where withdrawal was initiated. * @param _from L2 address initiating the transfer. * @param _to L1 address to credit the withdrawal to. * @param _amount Amount of the ERC20 to deposit. * @param _data Data provided by the sender on L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function finalizeERC20Withdrawal ( address _l1Token, address _l2Token, address _from, address _to, uint _amount, bytes calldata _data ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0; pragma experimental ABIEncoderV2; /** * @title iOVM_L2ERC20Bridge */ interface iOVM_L2ERC20Bridge { /********** * Events * **********/ event WithdrawalInitiated ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); event DepositFinalized ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); event DepositFailed ( address indexed _l1Token, address indexed _l2Token, address indexed _from, address _to, uint256 _amount, bytes _data ); /******************** * Public Functions * ********************/ /** * @dev initiate a withdraw of some tokens to the caller's account on L1 * @param _l2Token Address of L2 token where withdrawal was initiated. * @param _amount Amount of the token to withdraw. * param _l1Gas Unused, but included for potential forward compatibility considerations. * @param _data Optional data to forward to L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function withdraw ( address _l2Token, uint _amount, uint32 _l1Gas, bytes calldata _data ) external; /** * @dev initiate a withdraw of some token to a recipient's account on L1. * @param _l2Token Address of L2 token where withdrawal is initiated. * @param _to L1 adress to credit the withdrawal to. * @param _amount Amount of the token to withdraw. * param _l1Gas Unused, but included for potential forward compatibility considerations. * @param _data Optional data to forward to L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function withdrawTo ( address _l2Token, address _to, uint _amount, uint32 _l1Gas, bytes calldata _data ) external; /************************* * Cross-chain Functions * *************************/ /** * @dev Complete a deposit from L1 to L2, and credits funds to the recipient's balance of this * L2 token. This call will fail if it did not originate from a corresponding deposit in * OVM_l1TokenGateway. * @param _l1Token Address for the l1 token this is called with * @param _l2Token Address for the l2 token this is called with * @param _from Account to pull the deposit from on L2. * @param _to Address to receive the withdrawal at * @param _amount Amount of the token to withdraw * @param _data Data provider by the sender on L1. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function finalizeDeposit ( address _l1Token, address _l2Token, address _from, address _to, uint _amount, bytes calldata _data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_PredeployAddresses */ library Lib_PredeployAddresses { address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000; address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001; address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002; address internal constant ECDSA_CONTRACT_ACCOUNT = 0x4200000000000000000000000000000000000003; address internal constant SEQUENCER_ENTRYPOINT = 0x4200000000000000000000000000000000000005; address payable internal constant OVM_ETH = 0x4200000000000000000000000000000000000006; // solhint-disable-next-line max-line-length address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007; address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008; address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009; // solhint-disable-next-line max-line-length address internal constant EXECUTION_MANAGER_WRAPPER = 0x420000000000000000000000000000000000000B; address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011; address internal constant ERC1820_REGISTRY = 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24; address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.8.0; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol"; interface IL2StandardERC20 is IERC20, IERC165 { function l1Token() external returns (address); function mint(address _to, uint256 _amount) external; function burn(address _from, uint256 _amount) external; event Mint(address indexed _account, uint256 _amount); event Burn(address indexed _account, uint256 _amount); } // 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 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.5.0 <0.8.0; /* Library Imports */ import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { OVM_ETH } from "../predeploys/OVM_ETH.sol"; import { OVM_L2StandardBridge } from "../bridge/tokens/OVM_L2StandardBridge.sol"; /** * @title OVM_SequencerFeeVault * @dev Simple holding contract for fees paid to the Sequencer. Likely to be replaced in the future * but "good enough for now". * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_SequencerFeeVault { /************* * Constants * *************/ // Minimum ETH balance that can be withdrawn in a single withdrawal. uint256 public constant MIN_WITHDRAWAL_AMOUNT = 15 ether; /************* * Variables * *************/ // Address on L1 that will hold the fees once withdrawn. Dynamically initialized within l2geth. address public l1FeeWallet; /*************** * Constructor * ***************/ /** * @param _l1FeeWallet Initial address for the L1 wallet that will hold fees once withdrawn. * Currently HAS NO EFFECT in production because l2geth will mutate this storage slot during * the genesis block. This is ONLY for testing purposes. */ constructor( address _l1FeeWallet ) { l1FeeWallet = _l1FeeWallet; } /******************** * Public Functions * ********************/ function withdraw() public { uint256 balance = OVM_ETH(Lib_PredeployAddresses.OVM_ETH).balanceOf(address(this)); require( balance >= MIN_WITHDRAWAL_AMOUNT, // solhint-disable-next-line max-line-length "OVM_SequencerFeeVault: withdrawal amount must be greater than minimum withdrawal amount" ); OVM_L2StandardBridge(Lib_PredeployAddresses.L2_STANDARD_BRIDGE).withdrawTo( Lib_PredeployAddresses.OVM_ETH, l1FeeWallet, balance, 0, bytes("") ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { L2StandardERC20 } from "../../libraries/standards/L2StandardERC20.sol"; import { IWETH9 } from "../../libraries/standards/IWETH9.sol"; /** * @title OVM_ETH * @dev The ETH predeploy provides an ERC20 interface for ETH deposited to Layer 2. Note that * unlike on Layer 1, Layer 2 accounts do not have a balance field. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_ETH is L2StandardERC20, IWETH9 { /*************** * Constructor * ***************/ constructor() L2StandardERC20( Lib_PredeployAddresses.L2_STANDARD_BRIDGE, address(0), "Ether", "ETH" ) {} /****************************** * Custom WETH9 Functionality * ******************************/ fallback() external payable { deposit(); } /** * Implements the WETH9 deposit() function as a no-op. * WARNING: this function does NOT have to do with cross-chain asset bridging. The relevant * deposit and withdraw functions for that use case can be found at L2StandardBridge.sol. * This function allows developers to treat OVM_ETH as WETH without any modifications to their * code. */ function deposit() public payable override { // Calling deposit() with nonzero value will send the ETH to this contract address. // Once received here, we transfer it back by sending to the msg.sender. _transfer(address(this), msg.sender, msg.value); emit Deposit(msg.sender, msg.value); } /** * Implements the WETH9 withdraw() function as a no-op. * WARNING: this function does NOT have to do with cross-chain asset bridging. The relevant * deposit and withdraw functions for that use case can be found at L2StandardBridge.sol. * This function allows developers to treat OVM_ETH as WETH without any modifications to their * code. * @param _wad Amount being withdrawn */ function withdraw( uint256 _wad ) external override { // Calling withdraw() with value exceeding the withdrawer's ovmBALANCE should revert, // as in WETH9. require(balanceOf(msg.sender) >= _wad); // Other than emitting an event, OVM_ETH already is native ETH, so we don't need to do // anything else. emit Withdrawal(msg.sender, _wad); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.8.0; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IL2StandardERC20.sol"; contract L2StandardERC20 is IL2StandardERC20, ERC20 { address public override l1Token; address public l2Bridge; /** * @param _l2Bridge Address of the L2 standard bridge. * @param _l1Token Address of the corresponding L1 token. * @param _name ERC20 name. * @param _symbol ERC20 symbol. */ constructor( address _l2Bridge, address _l1Token, string memory _name, string memory _symbol ) ERC20(_name, _symbol) { l1Token = _l1Token; l2Bridge = _l2Bridge; } modifier onlyL2Bridge { require(msg.sender == l2Bridge, "Only L2 Bridge can mint and burn"); _; } function supportsInterface(bytes4 _interfaceId) public override pure returns (bool) { bytes4 firstSupportedInterface = bytes4(keccak256("supportsInterface(bytes4)")); // ERC165 bytes4 secondSupportedInterface = IL2StandardERC20.l1Token.selector ^ IL2StandardERC20.mint.selector ^ IL2StandardERC20.burn.selector; return _interfaceId == firstSupportedInterface || _interfaceId == secondSupportedInterface; } function mint(address _to, uint256 _amount) public virtual override onlyL2Bridge { _mint(_to, _amount); emit Mint(_to, _amount); } function burn(address _from, uint256 _amount) public virtual override onlyL2Bridge { _burn(_from, _amount); emit Burn(_from, _amount); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Interface for WETH9. Also contains the non-ERC20 events /// normally present in the WETH9 implementation. interface IWETH9 is IERC20 { event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { //require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1StandardBridge } from "../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol"; import { iOVM_L1ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol"; import { iOVM_L2ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /* Library Imports */ import { OVM_CrossDomainEnabled } from "../../../libraries/bridge/OVM_CrossDomainEnabled.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title OVM_L1StandardBridge * @dev The L1 ETH and ERC20 Bridge is a contract which stores deposited L1 funds and standard * tokens that are in use on L2. It synchronizes a corresponding L2 Bridge, informing it of deposits * and listening to it for newly finalized withdrawals. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1StandardBridge is iOVM_L1StandardBridge, OVM_CrossDomainEnabled { using SafeMath for uint; using SafeERC20 for IERC20; /******************************** * External Contract References * ********************************/ address public l2TokenBridge; // Maps L1 token to L2 token to balance of the L1 token deposited mapping(address => mapping (address => uint256)) public deposits; /*************** * Constructor * ***************/ // This contract lives behind a proxy, so the constructor parameters will go unused. constructor() OVM_CrossDomainEnabled(address(0)) {} /****************** * Initialization * ******************/ /** * @param _l1messenger L1 Messenger address being used for cross-chain communications. * @param _l2TokenBridge L2 standard bridge address. */ function initialize( address _l1messenger, address _l2TokenBridge ) public { require(messenger == address(0), "Contract has already been initialized."); messenger = _l1messenger; l2TokenBridge = _l2TokenBridge; } /************** * Depositing * **************/ /** @dev Modifier requiring sender to be EOA. This check could be bypassed by a malicious * contract via initcode, but it takes care of the user error we want to avoid. */ modifier onlyEOA() { // Used to stop deposits from contracts (avoid accidentally lost tokens) require(!Address.isContract(msg.sender), "Account not EOA"); _; } /** * @dev This function can be called with no data * to deposit an amount of ETH to the caller's balance on L2. * Since the receive function doesn't take data, a conservative * default amount is forwarded to L2. */ receive() external payable onlyEOA() { _initiateETHDeposit( msg.sender, msg.sender, 1_300_000, bytes("") ); } /** * @inheritdoc iOVM_L1StandardBridge */ function depositETH( uint32 _l2Gas, bytes calldata _data ) external override payable onlyEOA() { _initiateETHDeposit( msg.sender, msg.sender, _l2Gas, _data ); } /** * @inheritdoc iOVM_L1StandardBridge */ function depositETHTo( address _to, uint32 _l2Gas, bytes calldata _data ) external override payable { _initiateETHDeposit( msg.sender, _to, _l2Gas, _data ); } /** * @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of * the deposit. * @param _from Account to pull the deposit from on L1. * @param _to Account to give the deposit to on L2. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function _initiateETHDeposit( address _from, address _to, uint32 _l2Gas, bytes memory _data ) internal { // Construct calldata for finalizeDeposit call bytes memory message = abi.encodeWithSelector( iOVM_L2ERC20Bridge.finalizeDeposit.selector, address(0), Lib_PredeployAddresses.OVM_ETH, _from, _to, msg.value, _data ); // Send calldata into L2 sendCrossDomainMessage( l2TokenBridge, _l2Gas, message ); emit ETHDepositInitiated(_from, _to, msg.value, _data); } /** * @inheritdoc iOVM_L1ERC20Bridge */ function depositERC20( address _l1Token, address _l2Token, uint256 _amount, uint32 _l2Gas, bytes calldata _data ) external override virtual onlyEOA() { _initiateERC20Deposit(_l1Token, _l2Token, msg.sender, msg.sender, _amount, _l2Gas, _data); } /** * @inheritdoc iOVM_L1ERC20Bridge */ function depositERC20To( address _l1Token, address _l2Token, address _to, uint256 _amount, uint32 _l2Gas, bytes calldata _data ) external override virtual { _initiateERC20Deposit(_l1Token, _l2Token, msg.sender, _to, _amount, _l2Gas, _data); } /** * @dev Performs the logic for deposits by informing the L2 Deposited Token * contract of the deposit and calling a handler to lock the L1 funds. (e.g. transferFrom) * * @param _l1Token Address of the L1 ERC20 we are depositing * @param _l2Token Address of the L1 respective L2 ERC20 * @param _from Account to pull the deposit from on L1 * @param _to Account to give the deposit to on L2 * @param _amount Amount of the ERC20 to deposit. * @param _l2Gas Gas limit required to complete the deposit on L2. * @param _data Optional data to forward to L2. This data is provided * solely as a convenience for external contracts. Aside from enforcing a maximum * length, these contracts provide no guarantees about its content. */ function _initiateERC20Deposit( address _l1Token, address _l2Token, address _from, address _to, uint256 _amount, uint32 _l2Gas, bytes calldata _data ) internal { // When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future // withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if // _from is an EOA or address(0). IERC20(_l1Token).safeTransferFrom( _from, address(this), _amount ); // Construct calldata for _l2Token.finalizeDeposit(_to, _amount) bytes memory message = abi.encodeWithSelector( iOVM_L2ERC20Bridge.finalizeDeposit.selector, _l1Token, _l2Token, _from, _to, _amount, _data ); // Send calldata into L2 sendCrossDomainMessage( l2TokenBridge, _l2Gas, message ); deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].add(_amount); emit ERC20DepositInitiated(_l1Token, _l2Token, _from, _to, _amount, _data); } /************************* * Cross-chain Functions * *************************/ /** * @inheritdoc iOVM_L1StandardBridge */ function finalizeETHWithdrawal( address _from, address _to, uint256 _amount, bytes calldata _data ) external override onlyFromCrossDomainAccount(l2TokenBridge) { (bool success, ) = _to.call{value: _amount}(new bytes(0)); require(success, "TransferHelper::safeTransferETH: ETH transfer failed"); emit ETHWithdrawalFinalized(_from, _to, _amount, _data); } /** * @inheritdoc iOVM_L1ERC20Bridge */ function finalizeERC20Withdrawal( address _l1Token, address _l2Token, address _from, address _to, uint256 _amount, bytes calldata _data ) external override onlyFromCrossDomainAccount(l2TokenBridge) { deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].sub(_amount); // When a withdrawal is finalized on L1, the L1 Bridge transfers the funds to the withdrawer IERC20(_l1Token).safeTransfer(_to, _amount); emit ERC20WithdrawalFinalized(_l1Token, _l2Token, _from, _to, _amount, _data); } /***************************** * Temporary - Migrating ETH * *****************************/ /** * @dev Adds ETH balance to the account. This is meant to allow for ETH * to be migrated from an old gateway to a new gateway. * NOTE: This is left for one upgrade only so we are able to receive the migrated ETH from the * old contract */ function donateETH() external payable {} } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_ECDSAContractAccount } from "../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol"; /* Library Imports */ import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol"; import { Lib_ExecutionManagerWrapper } from "../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Contract Imports */ import { OVM_ETH } from "../predeploys/OVM_ETH.sol"; /* External Imports */ import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ECDSA } from "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title OVM_ECDSAContractAccount * @dev The ECDSA Contract Account can be used as the implementation for a ProxyEOA deployed by the * ovmCREATEEOA operation. It enables backwards compatibility with Ethereum's Layer 1, by * providing EIP155 formatted transaction encodings. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_ECDSAContractAccount is iOVM_ECDSAContractAccount { /************* * Libraries * *************/ using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx; /************* * Constants * *************/ // TODO: should be the amount sufficient to cover the gas costs of all of the transactions up // to and including the CALL/CREATE which forms the entrypoint of the transaction. uint256 constant EXECUTION_VALIDATION_GAS_OVERHEAD = 25000; /******************** * Public Functions * ********************/ /** * No-op fallback mirrors behavior of calling an EOA on L1. */ fallback() external payable { return; } /** * @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 ) public view returns ( bytes4 magicValue ) { return ECDSA.recover(hash, signature) == address(this) ? this.isValidSignature.selector : bytes4(0); } /** * Executes a signed transaction. * @param _transaction Signed EIP155 transaction. * @return Whether or not the call returned (rather than reverted). * @return Data returned by the call. */ function execute( Lib_EIP155Tx.EIP155Tx memory _transaction ) override public returns ( bool, bytes memory ) { // Address of this contract within the ovm (ovmADDRESS) should be the same as the // recovered address of the user who signed this message. This is how we manage to shim // account abstraction even though the user isn't a contract. require( _transaction.sender() == Lib_ExecutionManagerWrapper.ovmADDRESS(), "Signature provided for EOA transaction execution is invalid." ); require( _transaction.chainId == Lib_ExecutionManagerWrapper.ovmCHAINID(), "Transaction signed with wrong chain ID" ); // Need to make sure that the transaction nonce is right. require( _transaction.nonce == Lib_ExecutionManagerWrapper.ovmGETNONCE(), "Transaction nonce does not match the expected nonce." ); // TEMPORARY: Disable gas checks for mainnet. // // Need to make sure that the gas is sufficient to execute the transaction. // require( // gasleft() >= SafeMath.add(transaction.gasLimit, EXECUTION_VALIDATION_GAS_OVERHEAD), // "Gas is not sufficient to execute the transaction." // ); // Transfer fee to relayer. require( OVM_ETH(Lib_PredeployAddresses.OVM_ETH).transfer( Lib_PredeployAddresses.SEQUENCER_FEE_WALLET, SafeMath.mul(_transaction.gasLimit, _transaction.gasPrice) ), "Fee was not transferred to relayer." ); if (_transaction.isCreate) { // TEMPORARY: Disable value transfer for contract creations. require( _transaction.value == 0, "Value transfer in contract creation not supported." ); (address created, bytes memory revertdata) = Lib_ExecutionManagerWrapper.ovmCREATE( _transaction.data ); // Return true if the contract creation succeeded, false w/ revertdata otherwise. if (created != address(0)) { return (true, abi.encode(created)); } else { return (false, revertdata); } } else { // We only want to bump the nonce for `ovmCALL` because `ovmCREATE` automatically bumps // the nonce of the calling account. Normally an EOA would bump the nonce for both // cases, but since this is a contract we'd end up bumping the nonce twice. Lib_ExecutionManagerWrapper.ovmINCREMENTNONCE(); // NOTE: Upgrades are temporarily disabled because users can, in theory, modify their // EOA so that they don't have to pay any fees to the sequencer. Function will remain // disabled until a robust solution is in place. require( _transaction.to != Lib_ExecutionManagerWrapper.ovmADDRESS(), "Calls to self are disabled until upgradability is re-enabled." ); return _transaction.to.call{value: _transaction.value}(_transaction.data); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol"; /** * @title iOVM_ECDSAContractAccount */ interface iOVM_ECDSAContractAccount { /******************** * Public Functions * ********************/ function execute( Lib_EIP155Tx.EIP155Tx memory _transaction ) external returns ( bool, bytes memory ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; /** * @title Lib_EIP155Tx * @dev A simple library for dealing with the transaction type defined by EIP155: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md */ library Lib_EIP155Tx { /*********** * Structs * ***********/ // Struct representing an EIP155 transaction. See EIP link above for more information. struct EIP155Tx { // These fields correspond to the actual RLP-encoded fields specified by EIP155. uint256 nonce; uint256 gasPrice; uint256 gasLimit; address to; uint256 value; bytes data; uint8 v; bytes32 r; bytes32 s; // Chain ID to associate this transaction with. Used all over the place, seemed easier to // set this once when we create the transaction rather than providing it as an input to // each function. I don't see a strong need to have a transaction with a mutable chain ID. uint256 chainId; // The ECDSA "recovery parameter," should always be 0 or 1. EIP155 specifies that: // `v = {0,1} + CHAIN_ID * 2 + 35` // Where `{0,1}` is a stand in for our `recovery_parameter`. Now computing our formula for // the recovery parameter: // 1. `v = {0,1} + CHAIN_ID * 2 + 35` // 2. `v = recovery_parameter + CHAIN_ID * 2 + 35` // 3. `v - CHAIN_ID * 2 - 35 = recovery_parameter` // So we're left with the final formula: // `recovery_parameter = v - CHAIN_ID * 2 - 35` // NOTE: This variable is a uint8 because `v` is inherently limited to a uint8. If we // didn't use a uint8, then recovery_parameter would always be a negative number for chain // IDs greater than 110 (`255 - 110 * 2 - 35 = 0`). So we need to wrap around to support // anything larger. uint8 recoveryParam; // Whether or not the transaction is a creation. Necessary because we can't make an address // "nil". Using the zero address creates a potential conflict if the user did actually // intend to send a transaction to the zero address. bool isCreate; } // Lets us use nicer syntax. using Lib_EIP155Tx for EIP155Tx; /********************** * Internal Functions * **********************/ /** * Decodes an EIP155 transaction and attaches a given Chain ID. * Transaction *must* be RLP-encoded. * @param _encoded RLP-encoded EIP155 transaction. * @param _chainId Chain ID to assocaite with this transaction. * @return Parsed transaction. */ function decode( bytes memory _encoded, uint256 _chainId ) internal pure returns ( EIP155Tx memory ) { Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_encoded); // Note formula above about how recoveryParam is computed. uint8 v = uint8(Lib_RLPReader.readUint256(decoded[6])); uint8 recoveryParam = uint8(v - 2 * _chainId - 35); // Recovery param being anything other than 0 or 1 indicates that we have the wrong chain // ID. require( recoveryParam < 2, "Lib_EIP155Tx: Transaction signed with wrong chain ID" ); // Creations can be detected by looking at the byte length here. bool isCreate = Lib_RLPReader.readBytes(decoded[3]).length == 0; return EIP155Tx({ nonce: Lib_RLPReader.readUint256(decoded[0]), gasPrice: Lib_RLPReader.readUint256(decoded[1]), gasLimit: Lib_RLPReader.readUint256(decoded[2]), to: Lib_RLPReader.readAddress(decoded[3]), value: Lib_RLPReader.readUint256(decoded[4]), data: Lib_RLPReader.readBytes(decoded[5]), v: v, r: Lib_RLPReader.readBytes32(decoded[7]), s: Lib_RLPReader.readBytes32(decoded[8]), chainId: _chainId, recoveryParam: recoveryParam, isCreate: isCreate }); } /** * Encodes an EIP155 transaction into RLP. * @param _transaction EIP155 transaction to encode. * @param _includeSignature Whether or not to encode the signature. * @return RLP-encoded transaction. */ function encode( EIP155Tx memory _transaction, bool _includeSignature ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](9); raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce); raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice); raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit); // We write the encoding of empty bytes when the transaction is a creation, *not* the zero // address as one might assume. if (_transaction.isCreate) { raw[3] = Lib_RLPWriter.writeBytes(""); } else { raw[3] = Lib_RLPWriter.writeAddress(_transaction.to); } raw[4] = Lib_RLPWriter.writeUint(_transaction.value); raw[5] = Lib_RLPWriter.writeBytes(_transaction.data); if (_includeSignature) { raw[6] = Lib_RLPWriter.writeUint(_transaction.v); raw[7] = Lib_RLPWriter.writeBytes32(_transaction.r); raw[8] = Lib_RLPWriter.writeBytes32(_transaction.s); } else { // Chain ID *is* included in the unsigned transaction. raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId); raw[7] = Lib_RLPWriter.writeBytes(""); raw[8] = Lib_RLPWriter.writeBytes(""); } return Lib_RLPWriter.writeList(raw); } /** * Computes the hash of an EIP155 transaction. Assumes that you don't want to include the * signature in this hash because that's a very uncommon usecase. If you really want to include * the signature, just encode with the signature and take the hash yourself. */ function hash( EIP155Tx memory _transaction ) internal pure returns ( bytes32 ) { return keccak256( _transaction.encode(false) ); } /** * Computes the sender of an EIP155 transaction. * @param _transaction EIP155 transaction to get a sender for. * @return Address corresponding to the private key that signed this transaction. */ function sender( EIP155Tx memory _transaction ) internal pure returns ( address ) { return ecrecover( _transaction.hash(), _transaction.recoveryParam + 27, _transaction.r, _transaction.s ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol"; import { Lib_PredeployAddresses } from "../constants/Lib_PredeployAddresses.sol"; /** * @title Lib_ExecutionManagerWrapper * @dev This library acts as a utility for easily calling the OVM_ExecutionManagerWrapper, the * predeployed contract which exposes the `kall` builtin. Effectively, this contract allows the * user to trigger OVM opcodes by directly calling the OVM_ExecutionManger. * * Compiler used: solc * Runtime target: OVM */ library Lib_ExecutionManagerWrapper { /********************** * Internal Functions * **********************/ /** * Performs a safe ovmCREATE call. * @param _bytecode Code for the new contract. * @return Address of the created contract. */ function ovmCREATE( bytes memory _bytecode ) internal returns ( address, bytes memory ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCREATE(bytes)", _bytecode ) ); return abi.decode(returndata, (address, bytes)); } /** * Performs a safe ovmGETNONCE call. * @return Result of calling ovmGETNONCE. */ function ovmGETNONCE() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmGETNONCE()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmINCREMENTNONCE call. */ function ovmINCREMENTNONCE() internal { _callWrapperContract( abi.encodeWithSignature( "ovmINCREMENTNONCE()" ) ); } /** * Performs a safe ovmCREATEEOA call. * @param _messageHash Message hash which was signed by EOA * @param _v v value of signature (0 or 1) * @param _r r value of signature * @param _s s value of signature */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) internal { _callWrapperContract( abi.encodeWithSignature( "ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)", _messageHash, _v, _r, _s ) ); } /** * Calls the ovmL1TXORIGIN opcode. * @return Address that sent this message from L1. */ function ovmL1TXORIGIN() internal returns ( address ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmL1TXORIGIN()" ) ); return abi.decode(returndata, (address)); } /** * Calls the ovmCHAINID opcode. * @return Chain ID of the current network. */ function ovmCHAINID() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCHAINID()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmADDRESS call. * @return Result of calling ovmADDRESS. */ function ovmADDRESS() internal returns ( address ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmADDRESS()" ) ); return abi.decode(returndata, (address)); } /** * Calls the value-enabled ovmCALL opcode. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _value ETH value to pass with the call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata ) internal returns ( bool, bytes memory ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCALL(uint256,address,uint256,bytes)", _gasLimit, _address, _value, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Calls the ovmBALANCE opcode. * @param _address OVM account to query the balance of. * @return Balance of the account. */ function ovmBALANCE( address _address ) internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmBALANCE(address)", _address ) ); return abi.decode(returndata, (uint256)); } /** * Calls the ovmCALLVALUE opcode. * @return Value of the current call frame. */ function ovmCALLVALUE() internal returns ( uint256 ) { bytes memory returndata = _callWrapperContract( abi.encodeWithSignature( "ovmCALLVALUE()" ) ); return abi.decode(returndata, (uint256)); } /********************* * Private Functions * *********************/ /** * Performs an ovm interaction and the necessary safety checks. * @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash). * @return Data sent back by the OVM_ExecutionManager. */ function _callWrapperContract( bytes memory _calldata ) private returns ( bytes memory ) { (bool success, bytes memory returndata) = Lib_PredeployAddresses.EXECUTION_MANAGER_WRAPPER.delegatecall(_calldata); if (success == true) { return returndata; } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 constant internal MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem( bytes memory _in ) internal pure returns ( RLPItem memory ) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( RLPItem memory _in ) internal pure returns ( RLPItem[] memory ) { ( uint256 listOffset, , RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value." ); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require( itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length." ); ( uint256 itemOffset, uint256 itemLength, ) = _decodeLength(RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( bytes memory _in ) internal pure returns ( RLPItem[] memory ) { return readList( toRLPItem(_in) ); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value." ); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( bytes memory _in ) internal pure returns ( bytes memory ) { return readBytes( toRLPItem(_in) ); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( RLPItem memory _in ) internal pure returns ( string memory ) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( bytes memory _in ) internal pure returns ( string memory ) { return readString( toRLPItem(_in) ); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( RLPItem memory _in ) internal pure returns ( bytes32 ) { require( _in.length <= 33, "Invalid RLP bytes32 value." ); ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value." ); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( bytes memory _in ) internal pure returns ( bytes32 ) { return readBytes32( toRLPItem(_in) ); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( RLPItem memory _in ) internal pure returns ( uint256 ) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( bytes memory _in ) internal pure returns ( uint256 ) { return readUint256( toRLPItem(_in) ); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( RLPItem memory _in ) internal pure returns ( bool ) { require( _in.length == 1, "Invalid RLP boolean value." ); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require( out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1" ); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( bytes memory _in ) internal pure returns ( bool ) { return readBool( toRLPItem(_in) ); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( RLPItem memory _in ) internal pure returns ( address ) { if (_in.length == 1) { return address(0); } require( _in.length == 21, "Invalid RLP address value." ); return address(readUint256(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( bytes memory _in ) internal pure returns ( address ) { return readAddress( toRLPItem(_in) ); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength( RLPItem memory _in ) private pure returns ( uint256, uint256, RLPItemType ) { require( _in.length > 0, "RLP item cannot be null." ); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require( _in.length > strLen, "Invalid RLP short string." ); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require( _in.length > lenOfStrLen, "Invalid RLP long string length." ); uint256 strLen; assembly { // Pick out the string length. strLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)) ) } require( _in.length > lenOfStrLen + strLen, "Invalid RLP long string." ); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require( _in.length > listLen, "Invalid RLP short list." ); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require( _in.length > lenOfListLen, "Invalid RLP long list length." ); uint256 listLen; assembly { // Pick out the list length. listLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)) ) } require( _in.length > lenOfListLen + listLen, "Invalid RLP long list." ); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns ( bytes memory ) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask = 256 ** (32 - (_length % 32)) - 1; assembly { mstore( dest, or( and(mload(src), not(mask)), and(mload(dest), mask) ) ) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy( RLPItem memory _in ) private pure returns ( bytes memory ) { return _copy(_in.ptr, 0, _in.length); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return The RLP encoded string in bytes. */ function writeBytes( bytes memory _in ) internal pure returns ( bytes memory ) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function writeList( bytes[] memory _in ) internal pure returns ( bytes memory ) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return The RLP encoded string in bytes. */ function writeString( string memory _in ) internal pure returns ( bytes memory ) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return The RLP encoded address in bytes. */ function writeAddress( address _in ) internal pure returns ( bytes memory ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a bytes32 value. * @param _in The bytes32 to encode. * @return _out The RLP encoded bytes32 in bytes. */ function writeBytes32( bytes32 _in ) internal pure returns ( bytes memory _out ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return The RLP encoded uint256 in bytes. */ function writeUint( uint256 _in ) internal pure returns ( bytes memory ) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return The RLP encoded bool in bytes. */ function writeBool( bool _in ) internal pure returns ( bytes memory ) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function _writeLength( uint256 _len, uint256 _offset ) private pure returns ( bytes memory ) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = byte(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55); for(i = 1; i <= lenLen; i++) { encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function _toBinary( uint256 _x ) private pure returns ( bytes memory ) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function _flatten( bytes[] memory _list ) private pure returns ( bytes memory ) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20)} _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_ErrorUtils */ library Lib_ErrorUtils { /********************** * Internal Functions * **********************/ /** * Encodes an error string into raw solidity-style revert data. * (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))")) * Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string) * #panic-via-assert-and-error-via-require * @param _reason Reason for the reversion. * @return Standard solidity revert data for the given reason. */ function encodeRevertString( string memory _reason ) internal pure returns ( bytes memory ) { return abi.encodeWithSignature( "Error(string)", _reason ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; import { Lib_ExecutionManagerWrapper } from "../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol"; /** * @title OVM_ProxyEOA * @dev The Proxy EOA contract uses a delegate call to execute the logic in an implementation * contract. In combination with the logic implemented in the ECDSA Contract Account, this enables * a form of upgradable 'account abstraction' on layer 2. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_ProxyEOA { /********** * Events * **********/ event Upgraded( address indexed implementation ); /************* * Constants * *************/ // solhint-disable-next-line max-line-length bytes32 constant IMPLEMENTATION_KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; //bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1); /********************* * Fallback Function * *********************/ fallback() external payable { (bool success, bytes memory returndata) = getImplementation().delegatecall(msg.data); if (success) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } // WARNING: We use the deployed bytecode of this contract as a template to create ProxyEOA // contracts. As a result, we must *not* perform any constructor logic. Use initialization // functions if necessary. /******************** * Public Functions * ********************/ /** * Changes the implementation address. * @param _implementation New implementation address. */ function upgrade( address _implementation ) external { require( msg.sender == Lib_ExecutionManagerWrapper.ovmADDRESS(), "EOAs can only upgrade their own EOA implementation." ); _setImplementation(_implementation); emit Upgraded(_implementation); } /** * Gets the address of the current implementation. * @return Current implementation address. */ function getImplementation() public view returns ( address ) { bytes32 addr32; assembly { addr32 := sload(IMPLEMENTATION_KEY) } address implementation = Lib_Bytes32Utils.toAddress(addr32); if (implementation == address(0)) { return Lib_PredeployAddresses.ECDSA_CONTRACT_ACCOUNT; } else { return implementation; } } /********************** * Internal Functions * **********************/ function _setImplementation( address _implementation ) internal { bytes32 addr32 = Lib_Bytes32Utils.fromAddress(_implementation); assembly { sstore(IMPLEMENTATION_KEY, addr32) } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool( bytes32 _in ) internal pure returns ( bool ) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool( bool _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress( bytes32 _in ) internal pure returns ( address ) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress( address _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in)); } /** * Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value. * @param _in Input bytes32 value. * @return Bytes32 without any leading zeros. */ function removeLeadingZeros( bytes32 _in ) internal pure returns ( bytes memory ) { bytes memory out; assembly { // Figure out how many leading zero bytes to remove. let shift := 0 for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } { shift := add(shift, 1) } // Reserve some space for our output and fix the free memory pointer. out := mload(0x40) mstore(0x40, add(out, 0x40)) // Shift the value and store it into the output bytes. mstore(add(out, 0x20), shl(mul(shift, 8), _in)) // Store the new size (with leading zero bytes removed) in the output byte size. mstore(out, sub(32, shift)) } return out; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol"; import { Lib_ExecutionManagerWrapper } from "../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol"; import { iOVM_ECDSAContractAccount } from "../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol"; /** * @title OVM_SequencerEntrypoint * @dev The Sequencer Entrypoint is a predeploy which, despite its name, can in fact be called by * any account. It accepts a more efficient compressed calldata format, which it decompresses and * encodes to the standard EIP155 transaction format. * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_SequencerEntrypoint { /************* * Libraries * *************/ using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx; /********************* * Fallback Function * *********************/ /** * Expects an RLP-encoded EIP155 transaction as input. See the EIP for a more detailed * description of this transaction format: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md */ fallback() external { // We use this twice, so it's more gas efficient to store a copy of it (barely). bytes memory encodedTx = msg.data; // Decode the tx with the correct chain ID. Lib_EIP155Tx.EIP155Tx memory transaction = Lib_EIP155Tx.decode( encodedTx, Lib_ExecutionManagerWrapper.ovmCHAINID() ); // Value is computed on the fly. Keep it in the stack to save some gas. address target = transaction.sender(); bool isEmptyContract; assembly { isEmptyContract := iszero(extcodesize(target)) } // If the account is empty, deploy the default EOA to that address. if (isEmptyContract) { Lib_ExecutionManagerWrapper.ovmCREATEEOA( transaction.hash(), transaction.recoveryParam, transaction.r, transaction.s ); } // Forward the transaction over to the EOA. (bool success, bytes memory returndata) = target.call( abi.encodeWithSelector(iOVM_ECDSAContractAccount.execute.selector, transaction) ); if (success) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EIP155Tx } from "../../optimistic-ethereum/libraries/codec/Lib_EIP155Tx.sol"; /** * @title TestLib_EIP155Tx */ contract TestLib_EIP155Tx { function decode( bytes memory _encoded, uint256 _chainId ) public pure returns ( Lib_EIP155Tx.EIP155Tx memory ) { return Lib_EIP155Tx.decode( _encoded, _chainId ); } function encode( Lib_EIP155Tx.EIP155Tx memory _transaction, bool _includeSignature ) public pure returns ( bytes memory ) { return Lib_EIP155Tx.encode( _transaction, _includeSignature ); } function hash( Lib_EIP155Tx.EIP155Tx memory _transaction ) public pure returns ( bytes32 ) { return Lib_EIP155Tx.hash( _transaction ); } function sender( Lib_EIP155Tx.EIP155Tx memory _transaction ) public pure returns ( address ) { return Lib_EIP155Tx.sender( _transaction ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPWriter } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPWriter.sol"; import { TestERC20 } from "../../test-helpers/TestERC20.sol"; /** * @title TestLib_RLPWriter */ contract TestLib_RLPWriter { function writeBytes( bytes memory _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeBytes(_in); } function writeList( bytes[] memory _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeList(_in); } function writeString( string memory _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeString(_in); } function writeAddress( address _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeAddress(_in); } function writeUint( uint256 _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeUint(_in); } function writeBool( bool _in ) public pure returns ( bytes memory _out ) { return Lib_RLPWriter.writeBool(_in); } function writeAddressWithTaintedMemory( address _in ) public returns ( bytes memory _out ) { new TestERC20(); return Lib_RLPWriter.writeAddress(_in); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; // a test ERC20 token with an open mint function contract TestERC20 { using SafeMath for uint; string public constant name = 'Test'; string public constant symbol = 'TST'; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); constructor() {} function mint(address to, uint256 value) public { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _approve(address owner, address spender, uint256 value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint256 value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } } library SafeMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_BytesUtils } from "../../optimistic-ethereum/libraries/utils/Lib_BytesUtils.sol"; import { TestERC20 } from "../../test-helpers/TestERC20.sol"; /** * @title TestLib_BytesUtils */ contract TestLib_BytesUtils { function concat( bytes memory _preBytes, bytes memory _postBytes ) public pure returns (bytes memory) { return abi.encodePacked( _preBytes, _postBytes ); } function slice( bytes memory _bytes, uint256 _start, uint256 _length ) public pure returns (bytes memory) { return Lib_BytesUtils.slice( _bytes, _start, _length ); } function toBytes32( bytes memory _bytes ) public pure returns (bytes32) { return Lib_BytesUtils.toBytes32( _bytes ); } function toUint256( bytes memory _bytes ) public pure returns (uint256) { return Lib_BytesUtils.toUint256( _bytes ); } function toNibbles( bytes memory _bytes ) public pure returns (bytes memory) { return Lib_BytesUtils.toNibbles( _bytes ); } function fromNibbles( bytes memory _bytes ) public pure returns (bytes memory) { return Lib_BytesUtils.fromNibbles( _bytes ); } function equal( bytes memory _bytes, bytes memory _other ) public pure returns (bool) { return Lib_BytesUtils.equal( _bytes, _other ); } function sliceWithTaintedMemory( bytes memory _bytes, uint256 _start, uint256 _length ) public returns (bytes memory) { new TestERC20(); return Lib_BytesUtils.slice( _bytes, _start, _length ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ 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 slice( bytes memory _bytes, uint256 _start ) internal pure returns ( bytes memory ) { if (_start >= _bytes.length) { return bytes(""); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32PadLeft( bytes memory _bytes ) internal pure returns ( bytes32 ) { bytes32 ret; uint256 len = _bytes.length <= 32 ? _bytes.length : 32; assembly { ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32))) } return ret; } function toBytes32( bytes memory _bytes ) internal pure returns ( bytes32 ) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes } function toUint256( bytes memory _bytes ) internal pure returns ( uint256 ) { return uint256(toBytes32(_bytes)); } 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; } function toUint8( bytes memory _bytes, uint256 _start ) internal pure returns ( uint8 ) { require(_start + 1 >= _start, "toUint8_overflow"); require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } 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 toNibbles( bytes memory _bytes ) internal pure returns ( bytes memory ) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles( bytes memory _bytes ) internal pure returns ( bytes memory ) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal( bytes memory _bytes, bytes memory _other ) internal pure returns ( bool ) { return keccak256(_bytes) == keccak256(_other); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol"; import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_BytesUtils } from "../../libraries/utils/Lib_BytesUtils.sol"; import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol"; import { Lib_RLPWriter } from "../../libraries/rlp/Lib_RLPWriter.sol"; import { Lib_RLPReader } from "../../libraries/rlp/Lib_RLPReader.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol"; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol"; /* Contract Imports */ import { Abs_FraudContributor } from "./Abs_FraudContributor.sol"; /** * @title OVM_StateTransitioner * @dev The State Transitioner coordinates the execution of a state transition during the evaluation * of a fraud proof. It feeds verified input to the Execution Manager's run(), and controls a * State Manager (which is uniquely created for each fraud proof). * Once a fraud proof has been initialized, this contract is provided with the pre-state root and * verifies that the OVM storage slots committed to the State Mangager are contained in that state * This contract controls the State Manager and Execution Manager, and uses them to calculate the * post-state root by applying the transaction. The Fraud Verifier can then check for fraud by * comparing the calculated post-state root with the proposed post-state root. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateTransitioner is Lib_AddressResolver, Abs_FraudContributor, iOVM_StateTransitioner { /******************* * Data Structures * *******************/ enum TransitionPhase { PRE_EXECUTION, POST_EXECUTION, COMPLETE } /******************************************* * Contract Variables: Contract References * *******************************************/ iOVM_StateManager public ovmStateManager; /******************************************* * Contract Variables: Internal Accounting * *******************************************/ bytes32 internal preStateRoot; bytes32 internal postStateRoot; TransitionPhase public phase; uint256 internal stateTransitionIndex; bytes32 internal transactionHash; /************* * Constants * *************/ // solhint-disable-next-line max-line-length bytes32 internal constant EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line max-line-length bytes32 internal constant EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. * @param _stateTransitionIndex Index of the state transition being verified. * @param _preStateRoot State root before the transition was executed. * @param _transactionHash Hash of the executed transaction. */ constructor( address _libAddressManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) Lib_AddressResolver(_libAddressManager) { stateTransitionIndex = _stateTransitionIndex; preStateRoot = _preStateRoot; postStateRoot = _preStateRoot; transactionHash = _transactionHash; ovmStateManager = iOVM_StateManagerFactory(resolve("OVM_StateManagerFactory")) .create(address(this)); } /********************** * Function Modifiers * **********************/ /** * Checks that a function is only run during a specific phase. * @param _phase Phase the function must run within. */ modifier onlyDuringPhase( TransitionPhase _phase ) { require( phase == _phase, "Function must be called during the correct phase." ); _; } /********************************** * Public Functions: State Access * **********************************/ /** * Retrieves the state root before execution. * @return _preStateRoot State root before execution. */ function getPreStateRoot() override external view returns ( bytes32 _preStateRoot ) { return preStateRoot; } /** * Retrieves the state root after execution. * @return _postStateRoot State root after execution. */ function getPostStateRoot() override external view returns ( bytes32 _postStateRoot ) { return postStateRoot; } /** * Checks whether the transitioner is complete. * @return _complete Whether or not the transition process is finished. */ function isComplete() override external view returns ( bool _complete ) { return phase == TransitionPhase.COMPLETE; } /*********************************** * Public Functions: Pre-Execution * ***********************************/ /** * Allows a user to prove the initial state of a contract. * @param _ovmContractAddress Address of the contract on the OVM. * @param _ethContractAddress Address of the corresponding contract on L1. * @param _stateTrieWitness Proof of the account state. */ function proveContractState( address _ovmContractAddress, address _ethContractAddress, bytes memory _stateTrieWitness ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { // Exit quickly to avoid unnecessary work. require( ( ovmStateManager.hasAccount(_ovmContractAddress) == false && ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false ), "Account state has already been proven." ); // Function will fail if the proof is not a valid inclusion or exclusion proof. ( bool exists, bytes memory encodedAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(_ovmContractAddress), _stateTrieWitness, preStateRoot ); if (exists == true) { // Account exists, this was an inclusion proof. Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedAccount ); address ethContractAddress = _ethContractAddress; if (account.codeHash == EMPTY_ACCOUNT_CODE_HASH) { // Use a known empty contract to prevent an attack in which a user provides a // contract address here and then later deploys code to it. ethContractAddress = 0x0000000000000000000000000000000000000000; } else { // Otherwise, make sure that the code at the provided eth address matches the hash // of the code stored on L2. require( Lib_EthUtils.getCodeHash(ethContractAddress) == account.codeHash, // solhint-disable-next-line max-line-length "OVM_StateTransitioner: Provided L1 contract code hash does not match L2 contract code hash." ); } ovmStateManager.putAccount( _ovmContractAddress, Lib_OVMCodec.Account({ nonce: account.nonce, balance: account.balance, storageRoot: account.storageRoot, codeHash: account.codeHash, ethAddress: ethContractAddress, isFresh: false }) ); } else { // Account does not exist, this was an exclusion proof. ovmStateManager.putEmptyAccount(_ovmContractAddress); } } /** * Allows a user to prove the initial state of a contract storage slot. * @param _ovmContractAddress Address of the contract on the OVM. * @param _key Claimed account slot key. * @param _storageTrieWitness Proof of the storage slot. */ function proveStorageSlot( address _ovmContractAddress, bytes32 _key, bytes memory _storageTrieWitness ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { // Exit quickly to avoid unnecessary work. require( ovmStateManager.hasContractStorage(_ovmContractAddress, _key) == false, "Storage slot has already been proven." ); require( ovmStateManager.hasAccount(_ovmContractAddress) == true, "Contract must be verified before proving a storage slot." ); bytes32 storageRoot = ovmStateManager.getAccountStorageRoot(_ovmContractAddress); bytes32 value; if (storageRoot == EMPTY_ACCOUNT_STORAGE_ROOT) { // Storage trie was empty, so the user is always allowed to insert zero-byte values. value = bytes32(0); } else { // Function will fail if the proof is not a valid inclusion or exclusion proof. ( bool exists, bytes memory encodedValue ) = Lib_SecureMerkleTrie.get( abi.encodePacked(_key), _storageTrieWitness, storageRoot ); if (exists == true) { // Inclusion proof. // Stored values are RLP encoded, with leading zeros removed. value = Lib_BytesUtils.toBytes32PadLeft( Lib_RLPReader.readBytes(encodedValue) ); } else { // Exclusion proof, can only be zero bytes. value = bytes32(0); } } ovmStateManager.putContractStorage( _ovmContractAddress, _key, value ); } /******************************* * Public Functions: Execution * *******************************/ /** * Executes the state transition. * @param _transaction OVM transaction to execute. */ function applyTransaction( Lib_OVMCodec.Transaction memory _transaction ) override external onlyDuringPhase(TransitionPhase.PRE_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( Lib_OVMCodec.hashTransaction(_transaction) == transactionHash, "Invalid transaction provided." ); // We require gas to complete the logic here in run() before/after execution, // But must ensure the full _tx.gasLimit can be given to the ovmCALL (determinism) // This includes 1/64 of the gas getting lost because of EIP-150 (lost twice--first // going into EM, then going into the code contract). require( // 1032/1000 = 1.032 = (64/63)^2 rounded up gasleft() >= 100000 + _transaction.gasLimit * 1032 / 1000, "Not enough gas to execute transaction deterministically." ); iOVM_ExecutionManager ovmExecutionManager = iOVM_ExecutionManager(resolve("OVM_ExecutionManager")); // We call `setExecutionManager` right before `run` (and not earlier) just in case the // OVM_ExecutionManager address was updated between the time when this contract was created // and when `applyTransaction` was called. ovmStateManager.setExecutionManager(address(ovmExecutionManager)); // `run` always succeeds *unless* the user hasn't provided enough gas to `applyTransaction` // or an INVALID_STATE_ACCESS flag was triggered. Either way, we won't get beyond this line // if that's the case. ovmExecutionManager.run(_transaction, address(ovmStateManager)); // Prevent the Execution Manager from calling this SM again. ovmStateManager.setExecutionManager(address(0)); phase = TransitionPhase.POST_EXECUTION; } /************************************ * Public Functions: Post-Execution * ************************************/ /** * Allows a user to commit the final state of a contract. * @param _ovmContractAddress Address of the contract on the OVM. * @param _stateTrieWitness Proof of the account state. */ function commitContractState( address _ovmContractAddress, bytes memory _stateTrieWitness ) override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( ovmStateManager.getTotalUncommittedContractStorage() == 0, "All storage must be committed before committing account states." ); require ( ovmStateManager.commitAccount(_ovmContractAddress) == true, "Account state wasn't changed or has already been committed." ); Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress); postStateRoot = Lib_SecureMerkleTrie.update( abi.encodePacked(_ovmContractAddress), Lib_OVMCodec.encodeEVMAccount( Lib_OVMCodec.toEVMAccount(account) ), _stateTrieWitness, postStateRoot ); // Emit an event to help clients figure out the proof ordering. emit AccountCommitted( _ovmContractAddress ); } /** * Allows a user to commit the final state of a contract storage slot. * @param _ovmContractAddress Address of the contract on the OVM. * @param _key Claimed account slot key. * @param _storageTrieWitness Proof of the storage slot. */ function commitStorageSlot( address _ovmContractAddress, bytes32 _key, bytes memory _storageTrieWitness ) override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) contributesToFraudProof(preStateRoot, transactionHash) { require( ovmStateManager.commitContractStorage(_ovmContractAddress, _key) == true, "Storage slot value wasn't changed or has already been committed." ); Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress); bytes32 value = ovmStateManager.getContractStorage(_ovmContractAddress, _key); account.storageRoot = Lib_SecureMerkleTrie.update( abi.encodePacked(_key), Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros(value) ), _storageTrieWitness, account.storageRoot ); ovmStateManager.putAccount(_ovmContractAddress, account); // Emit an event to help clients figure out the proof ordering. emit ContractStorageCommitted( _ovmContractAddress, _key ); } /********************************** * Public Functions: Finalization * **********************************/ /** * Finalizes the transition process. */ function completeTransition() override external onlyDuringPhase(TransitionPhase.POST_EXECUTION) { require( ovmStateManager.getTotalUncommittedAccounts() == 0, "All accounts must be committed before completing a transition." ); require( ovmStateManager.getTotalUncommittedContractStorage() == 0, "All storage must be committed before completing a transition." ); phase = TransitionPhase.COMPLETE; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol"; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct Account { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; address ethAddress; bool isFresh; } struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } /********************** * Internal Functions * **********************/ /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction( Transaction memory _transaction ) internal pure returns ( bytes memory ) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction( Transaction memory _transaction ) internal pure returns ( bytes32 ) { return keccak256(encodeTransaction(_transaction)); } /** * Converts an OVM account to an EVM account. * @param _in OVM account to convert. * @return Converted EVM account. */ function toEVMAccount( Account memory _in ) internal pure returns ( EVMAccount memory ) { return EVMAccount({ nonce: _in.nonce, balance: _in.balance, storageRoot: _in.storageRoot, codeHash: _in.codeHash }); } /** * @notice RLP-encodes an account state struct. * @param _account Account state struct. * @return RLP-encoded account state. */ function encodeEVMAccount( EVMAccount memory _account ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](4); // Unfortunately we can't create this array outright because // Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning // index-by-index circumvents this issue. raw[0] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.nonce) ) ); raw[1] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.balance) ) ); raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot)); raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash)); return Lib_RLPWriter.writeList(raw); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount( bytes memory _encoded ) internal pure returns ( EVMAccount memory ) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /************* * Variables * *************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor( address _libAddressManager ) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ /** * Resolves the address associated with a given name. * @param _name Name to resolve an address for. * @return Address associated with the given name. */ function resolve( string memory _name ) public view returns ( address ) { return libAddressManager.getAddress(_name); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol"; /** * @title Lib_EthUtils */ library Lib_EthUtils { /********************** * Internal Functions * **********************/ /** * Gets the code for a given address. * @param _address Address to get code for. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Code read from the contract. */ function getCode( address _address, uint256 _offset, uint256 _length ) internal view returns ( bytes memory ) { bytes memory code; assembly { code := mload(0x40) mstore(0x40, add(code, add(_length, 0x20))) mstore(code, _length) extcodecopy(_address, add(code, 0x20), _offset, _length) } return code; } /** * Gets the full code for a given address. * @param _address Address to get code for. * @return Full code of the contract. */ function getCode( address _address ) internal view returns ( bytes memory ) { return getCode( _address, 0, getCodeSize(_address) ); } /** * Gets the size of a contract's code in bytes. * @param _address Address to get code size for. * @return Size of the contract's code in bytes. */ function getCodeSize( address _address ) internal view returns ( uint256 ) { uint256 codeSize; assembly { codeSize := extcodesize(_address) } return codeSize; } /** * Gets the hash of a contract's code. * @param _address Address to get a code hash for. * @return Hash of the contract's code. */ function getCodeHash( address _address ) internal view returns ( bytes32 ) { bytes32 codeHash; assembly { codeHash := extcodehash(_address) } return codeHash; } /** * Creates a contract with some given initialization code. * @param _code Contract initialization code. * @return Address of the created contract. */ function createContract( bytes memory _code ) internal returns ( address ) { address created; assembly { created := create( 0, add(_code, 0x20), mload(_code) ) } return created; } /** * Computes the address that would be generated by CREATE. * @param _creator Address creating the contract. * @param _nonce Creator's nonce. * @return Address to be generated by CREATE. */ function getAddressForCREATE( address _creator, uint256 _nonce ) internal pure returns ( address ) { bytes[] memory encoded = new bytes[](2); encoded[0] = Lib_RLPWriter.writeAddress(_creator); encoded[1] = Lib_RLPWriter.writeUint(_nonce); bytes memory encodedList = Lib_RLPWriter.writeList(encoded); return Lib_Bytes32Utils.toAddress(keccak256(encodedList)); } /** * Computes the address that would be generated by CREATE2. * @param _creator Address creating the contract. * @param _bytecode Bytecode of the contract to be created. * @param _salt 32 byte salt value mixed into the hash. * @return Address to be generated by CREATE2. */ function getAddressForCREATE2( address _creator, bytes memory _bytecode, bytes32 _salt ) internal pure returns ( address ) { bytes32 hashedData = keccak256(abi.encodePacked( byte(0xff), _creator, _salt, keccak256(_bytecode) )); return Lib_Bytes32Utils.toAddress(hashedData); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol"; /** * @title Lib_SecureMerkleTrie */ library Lib_SecureMerkleTrie { /********************** * Internal Functions * **********************/ /** * @notice Verifies a proof that a given key/value pair is present in the * Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the desired node. Unlike * traditional Merkle trees, this proof is executed top-down and consists * of a list of RLP-encoded nodes that make a path down to the target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise. */ function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root); } /** * @notice Updates a Merkle trie and returns a new root hash. * @param _key Key of the node to update, as a hex string. * @param _value Value of the node to update, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. If the key exists, we can simply update the value. * Otherwise, we need to modify the trie to handle the new k/v pair. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _updatedRoot Root hash of the newly constructed trie. */ function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bytes32 _updatedRoot ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.update(key, _value, _proof, _root); } /** * @notice Retrieves the value associated with a given key. * @param _key Key to search for, as hex bytes. * @param _proof Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * @return _exists Whether or not the key exists. * @return _value Value of the key if it exists. */ function get( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _exists, bytes memory _value ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.get(key, _proof, _root); } /** * Computes the root hash for a trie with a single node. * @param _key Key for the single node. * @param _value Value for the single node. * @return _updatedRoot Hash of the trie. */ function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) internal pure returns ( bytes32 _updatedRoot ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.getSingleNodeRootHash(key, _value); } /********************* * Private Functions * *********************/ /** * Computes the secure counterpart to a key. * @param _key Key to get a secure key from. * @return _secureKey Secure version of the key. */ function _getSecureKey( bytes memory _key ) private pure returns ( bytes memory _secureKey ) { return abi.encodePacked(keccak256(_key)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateTransitioner */ interface iOVM_StateTransitioner { /********** * Events * **********/ event AccountCommitted( address _address ); event ContractStorageCommitted( address _address, bytes32 _key ); /********************************** * Public Functions: State Access * **********************************/ function getPreStateRoot() external view returns (bytes32 _preStateRoot); function getPostStateRoot() external view returns (bytes32 _postStateRoot); function isComplete() external view returns (bool _complete); /*********************************** * Public Functions: Pre-Execution * ***********************************/ function proveContractState( address _ovmContractAddress, address _ethContractAddress, bytes calldata _stateTrieWitness ) external; function proveStorageSlot( address _ovmContractAddress, bytes32 _key, bytes calldata _storageTrieWitness ) external; /******************************* * Public Functions: Execution * *******************************/ function applyTransaction( Lib_OVMCodec.Transaction calldata _transaction ) external; /************************************ * Public Functions: Post-Execution * ************************************/ function commitContractState( address _ovmContractAddress, bytes calldata _stateTrieWitness ) external; function commitStorageSlot( address _ovmContractAddress, bytes32 _key, bytes calldata _storageTrieWitness ) external; /********************************** * Public Functions: Finalization * **********************************/ function completeTransition() external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; interface ERC20 { function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); } /// All the errors which may be encountered on the bond manager library Errors { string constant ERC20_ERR = "BondManager: Could not post bond"; // solhint-disable-next-line max-line-length string constant ALREADY_FINALIZED = "BondManager: Fraud proof for this pre-state root has already been finalized"; string constant SLASHED = "BondManager: Cannot finalize withdrawal, you probably got slashed"; string constant WRONG_STATE = "BondManager: Wrong bond state for proposer"; string constant CANNOT_CLAIM = "BondManager: Cannot claim yet. Dispute must be finalized first"; string constant WITHDRAWAL_PENDING = "BondManager: Withdrawal already pending"; string constant TOO_EARLY = "BondManager: Too early to finalize your withdrawal"; // solhint-disable-next-line max-line-length string constant ONLY_TRANSITIONER = "BondManager: Only the transitioner for this pre-state root may call this function"; // solhint-disable-next-line max-line-length string constant ONLY_FRAUD_VERIFIER = "BondManager: Only the fraud verifier may call this function"; // solhint-disable-next-line max-line-length string constant ONLY_STATE_COMMITMENT_CHAIN = "BondManager: Only the state commitment chain may call this function"; string constant WAIT_FOR_DISPUTES = "BondManager: Wait for other potential disputes"; } /** * @title iOVM_BondManager */ interface iOVM_BondManager { /******************* * Data Structures * *******************/ /// The lifecycle of a proposer's bond enum State { // Before depositing or after getting slashed, a user is uncollateralized NOT_COLLATERALIZED, // After depositing, a user is collateralized COLLATERALIZED, // After a user has initiated a withdrawal WITHDRAWING } /// A bond posted by a proposer struct Bond { // The user's state State state; // The timestamp at which a proposer issued their withdrawal request uint32 withdrawalTimestamp; // The time when the first disputed was initiated for this bond uint256 firstDisputeAt; // The earliest observed state root for this bond which has had fraud bytes32 earliestDisputedStateRoot; // The state root's timestamp uint256 earliestTimestamp; } // Per pre-state root, store the number of state provisions that were made // and how many of these calls were made by each user. Payouts will then be // claimed by users proportionally for that dispute. struct Rewards { // Flag to check if rewards for a fraud proof are claimable bool canClaim; // Total number of `recordGasSpent` calls made uint256 total; // The gas spent by each user to provide witness data. The sum of all // values inside this map MUST be equal to the value of `total` mapping(address => uint256) gasSpent; } /******************** * Public Functions * ********************/ function recordGasSpent( bytes32 _preStateRoot, bytes32 _txHash, address _who, uint256 _gasSpent ) external; function finalize( bytes32 _preStateRoot, address _publisher, uint256 _timestamp ) external; function deposit() external; function startWithdrawal() external; function finalizeWithdrawal() external; function claim( address _who ) external; function isCollateralized( address _who ) external view returns (bool); function getGasSpent( bytes32 _preStateRoot, address _who ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; interface iOVM_ExecutionManager { /********** * Enums * *********/ enum RevertFlag { OUT_OF_GAS, INTENTIONAL_REVERT, EXCEEDS_NUISANCE_GAS, INVALID_STATE_ACCESS, UNSAFE_BYTECODE, CREATE_COLLISION, STATIC_VIOLATION, CREATOR_NOT_ALLOWED } enum GasMetadataKey { CURRENT_EPOCH_START_TIMESTAMP, CUMULATIVE_SEQUENCER_QUEUE_GAS, CUMULATIVE_L1TOL2_QUEUE_GAS, PREV_EPOCH_SEQUENCER_QUEUE_GAS, PREV_EPOCH_L1TOL2_QUEUE_GAS } enum MessageType { ovmCALL, ovmSTATICCALL, ovmDELEGATECALL, ovmCREATE, ovmCREATE2 } /*********** * Structs * ***********/ struct GasMeterConfig { uint256 minTransactionGasLimit; uint256 maxTransactionGasLimit; uint256 maxGasPerQueuePerEpoch; uint256 secondsPerEpoch; } struct GlobalContext { uint256 ovmCHAINID; } struct TransactionContext { Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN; uint256 ovmTIMESTAMP; uint256 ovmNUMBER; uint256 ovmGASLIMIT; uint256 ovmTXGASLIMIT; address ovmL1TXORIGIN; } struct TransactionRecord { uint256 ovmGasRefund; } struct MessageContext { address ovmCALLER; address ovmADDRESS; uint256 ovmCALLVALUE; bool isStatic; } struct MessageRecord { uint256 nuisanceGasLeft; } /************************************ * Transaction Execution Entrypoint * ************************************/ function run( Lib_OVMCodec.Transaction calldata _transaction, address _txStateManager ) external returns (bytes memory); /******************* * Context Opcodes * *******************/ function ovmCALLER() external view returns (address _caller); function ovmADDRESS() external view returns (address _address); function ovmCALLVALUE() external view returns (uint _callValue); function ovmTIMESTAMP() external view returns (uint256 _timestamp); function ovmNUMBER() external view returns (uint256 _number); function ovmGASLIMIT() external view returns (uint256 _gasLimit); function ovmCHAINID() external view returns (uint256 _chainId); /********************** * L2 Context Opcodes * **********************/ function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin); function ovmL1TXORIGIN() external view returns (address _l1TxOrigin); /******************* * Halting Opcodes * *******************/ function ovmREVERT(bytes memory _data) external; /***************************** * Contract Creation Opcodes * *****************************/ function ovmCREATE(bytes memory _bytecode) external returns (address _contract, bytes memory _revertdata); function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external returns (address _contract, bytes memory _revertdata); /******************************* * Account Abstraction Opcodes * ******************************/ function ovmGETNONCE() external returns (uint256 _nonce); function ovmINCREMENTNONCE() external; function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external; /**************************** * Contract Calling Opcodes * ****************************/ // Valueless ovmCALL for maintaining backwards compatibility with legacy OVM bytecode. function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmCALL(uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); /**************************** * Contract Storage Opcodes * ****************************/ function ovmSLOAD(bytes32 _key) external returns (bytes32 _value); function ovmSSTORE(bytes32 _key, bytes32 _value) external; /************************* * Contract Code Opcodes * *************************/ function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external returns (bytes memory _code); function ovmEXTCODESIZE(address _contract) external returns (uint256 _size); function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash); /********************* * ETH Value Opcodes * *********************/ function ovmBALANCE(address _contract) external returns (uint256 _balance); function ovmSELFBALANCE() external returns (uint256 _balance); /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateManager */ interface iOVM_StateManager { /******************* * Data Structures * *******************/ enum ItemState { ITEM_UNTOUCHED, ITEM_LOADED, ITEM_CHANGED, ITEM_COMMITTED } /*************************** * Public Functions: Misc * ***************************/ function isAuthenticated(address _address) external view returns (bool); /*************************** * Public Functions: Setup * ***************************/ function owner() external view returns (address _owner); function ovmExecutionManager() external view returns (address _ovmExecutionManager); function setExecutionManager(address _ovmExecutionManager) external; /************************************ * Public Functions: Account Access * ************************************/ function putAccount(address _address, Lib_OVMCodec.Account memory _account) external; function putEmptyAccount(address _address) external; function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account); function hasAccount(address _address) external view returns (bool _exists); function hasEmptyAccount(address _address) external view returns (bool _exists); function setAccountNonce(address _address, uint256 _nonce) external; function getAccountNonce(address _address) external view returns (uint256 _nonce); function getAccountEthAddress(address _address) external view returns (address _ethAddress); function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot); function initPendingAccount(address _address) external; function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external; function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded); function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged); function commitAccount(address _address) external returns (bool _wasAccountCommitted); function incrementTotalUncommittedAccounts() external; function getTotalUncommittedAccounts() external view returns (uint256 _total); function wasAccountChanged(address _address) external view returns (bool); function wasAccountCommitted(address _address) external view returns (bool); /************************************ * Public Functions: Storage Access * ************************************/ function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external; function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value); function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists); function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded); function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged); function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted); function incrementTotalUncommittedContractStorage() external; function getTotalUncommittedContractStorage() external view returns (uint256 _total); function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool); function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { iOVM_StateManager } from "./iOVM_StateManager.sol"; /** * @title iOVM_StateManagerFactory */ interface iOVM_StateManagerFactory { /*************************************** * Public Functions: Contract Creation * ***************************************/ function create( address _owner ) external returns ( iOVM_StateManager _ovmStateManager ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /// Minimal contract to be inherited by contracts consumed by users that provide /// data for fraud proofs abstract contract Abs_FraudContributor is Lib_AddressResolver { /// Decorate your functions with this modifier to store how much total gas was /// consumed by the sender, to reward users fairly modifier contributesToFraudProof(bytes32 preStateRoot, bytes32 txHash) { uint256 startGas = gasleft(); _; uint256 gasSpent = startGas - gasleft(); iOVM_BondManager(resolve("OVM_BondManager")) .recordGasSpent(preStateRoot, txHash, msg.sender, gasSpent); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* External Imports */ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string indexed _name, address _newAddress, address _oldAddress ); /************* * Variables * *************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress( string memory _name, address _address ) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet( _name, _address, oldAddress ); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress( string memory _name ) external view returns ( address ) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash( string memory _name ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_name)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; /** * @title Lib_MerkleTrie */ library Lib_MerkleTrie { /******************* * Data Structures * *******************/ enum NodeType { BranchNode, ExtensionNode, LeafNode } struct TrieNode { bytes encoded; Lib_RLPReader.RLPItem[] decoded; } /********************** * Contract Constants * **********************/ // TREE_RADIX determines the number of elements per branch node. uint256 constant TREE_RADIX = 16; // Branch nodes have TREE_RADIX elements plus an additional `value` slot. uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1; // Leaf nodes and extension nodes always have two elements, a `path` and a `value`. uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2; // Prefixes are prepended to the `path` within a leaf or extension node and // allow us to differentiate between the two node types. `ODD` or `EVEN` is // determined by the number of nibbles within the unprefixed `path`. If the // number of nibbles if even, we need to insert an extra padding nibble so // the resulting prefixed `path` has an even number of nibbles. uint8 constant PREFIX_EXTENSION_EVEN = 0; uint8 constant PREFIX_EXTENSION_ODD = 1; uint8 constant PREFIX_LEAF_EVEN = 2; uint8 constant PREFIX_LEAF_ODD = 3; // Just a utility constant. RLP represents `NULL` as 0x80. bytes1 constant RLP_NULL = bytes1(0x80); bytes constant RLP_NULL_BYTES = hex'80'; bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES); /********************** * Internal Functions * **********************/ /** * @notice Verifies a proof that a given key/value pair is present in the * Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the desired node. Unlike * traditional Merkle trees, this proof is executed top-down and consists * of a list of RLP-encoded nodes that make a path down to the target node. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _verified `true` if the k/v pair exists in the trie, `false` otherwise. */ function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { ( bool exists, bytes memory value ) = get(_key, _proof, _root); return ( exists && Lib_BytesUtils.equal(_value, value) ); } /** * @notice Updates a Merkle trie and returns a new root hash. * @param _key Key of the node to update, as a hex string. * @param _value Value of the node to update, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. If the key exists, we can simply update the value. * Otherwise, we need to modify the trie to handle the new k/v pair. * @param _root Known root of the Merkle trie. Used to verify that the * included proof is correctly constructed. * @return _updatedRoot Root hash of the newly constructed trie. */ function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bytes32 _updatedRoot ) { // Special case when inserting the very first node. if (_root == KECCAK256_RLP_NULL_BYTES) { return getSingleNodeRootHash(_key, _value); } TrieNode[] memory proof = _parseProof(_proof); (uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root); TrieNode[] memory newPath = _getNewPath(proof, pathLength, _key, keyRemainder, _value); return _getUpdatedTrieRoot(newPath, _key); } /** * @notice Retrieves the value associated with a given key. * @param _key Key to search for, as hex bytes. * @param _proof Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * @return _exists Whether or not the key exists. * @return _value Value of the key if it exists. */ function get( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _exists, bytes memory _value ) { TrieNode[] memory proof = _parseProof(_proof); (uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = _walkNodePath(proof, _key, _root); bool exists = keyRemainder.length == 0; require( exists || isFinalNode, "Provided proof is invalid." ); bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes(""); return ( exists, value ); } /** * Computes the root hash for a trie with a single node. * @param _key Key for the single node. * @param _value Value for the single node. * @return _updatedRoot Hash of the trie. */ function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) internal pure returns ( bytes32 _updatedRoot ) { return keccak256(_makeLeafNode( Lib_BytesUtils.toNibbles(_key), _value ).encoded); } /********************* * Private Functions * *********************/ /** * @notice Walks through a proof using a provided key. * @param _proof Inclusion proof to walk through. * @param _key Key to use for the walk. * @param _root Known root of the trie. * @return _pathLength Length of the final path * @return _keyRemainder Portion of the key remaining after the walk. * @return _isFinalNode Whether or not we've hit a dead end. */ function _walkNodePath( TrieNode[] memory _proof, bytes memory _key, bytes32 _root ) private pure returns ( uint256 _pathLength, bytes memory _keyRemainder, bool _isFinalNode ) { uint256 pathLength = 0; bytes memory key = Lib_BytesUtils.toNibbles(_key); bytes32 currentNodeID = _root; uint256 currentKeyIndex = 0; uint256 currentKeyIncrement = 0; TrieNode memory currentNode; // Proof is top-down, so we start at the first element (root). for (uint256 i = 0; i < _proof.length; i++) { currentNode = _proof[i]; currentKeyIndex += currentKeyIncrement; // Keep track of the proof elements we actually need. // It's expensive to resize arrays, so this simply reduces gas costs. pathLength += 1; if (currentKeyIndex == 0) { // First proof element is always the root node. require( keccak256(currentNode.encoded) == currentNodeID, "Invalid root hash" ); } else if (currentNode.encoded.length >= 32) { // Nodes 32 bytes or larger are hashed inside branch nodes. require( keccak256(currentNode.encoded) == currentNodeID, "Invalid large internal hash" ); } else { // Nodes smaller than 31 bytes aren't hashed. require( Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID, "Invalid internal node hash" ); } if (currentNode.decoded.length == BRANCH_NODE_LENGTH) { if (currentKeyIndex == key.length) { // We've hit the end of the key // meaning the value should be within this branch node. break; } else { // We're not at the end of the key yet. // Figure out what the next node ID should be and continue. uint8 branchKey = uint8(key[currentKeyIndex]); Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey]; currentNodeID = _getNodeID(nextNode); currentKeyIncrement = 1; continue; } } else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { bytes memory path = _getNodePath(currentNode); uint8 prefix = uint8(path[0]); uint8 offset = 2 - prefix % 2; bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset); bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex); uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder); if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) { if ( pathRemainder.length == sharedNibbleLength && keyRemainder.length == sharedNibbleLength ) { // The key within this leaf matches our key exactly. // Increment the key index to reflect that we have no remainder. currentKeyIndex += sharedNibbleLength; } // We've hit a leaf node, so our next node should be NULL. currentNodeID = bytes32(RLP_NULL); break; } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) { if (sharedNibbleLength != pathRemainder.length) { // Our extension node is not identical to the remainder. // We've hit the end of this path // updates will need to modify this extension. currentNodeID = bytes32(RLP_NULL); break; } else { // Our extension shares some nibbles. // Carry on to the next node. currentNodeID = _getNodeID(currentNode.decoded[1]); currentKeyIncrement = sharedNibbleLength; continue; } } else { revert("Received a node with an unknown prefix"); } } else { revert("Received an unparseable node."); } } // If our node ID is NULL, then we're at a dead end. bool isFinalNode = currentNodeID == bytes32(RLP_NULL); return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode); } /** * @notice Creates new nodes to support a k/v pair insertion into a given Merkle trie path. * @param _path Path to the node nearest the k/v pair. * @param _pathLength Length of the path. Necessary because the provided path may include * additional nodes (e.g., it comes directly from a proof) and we can't resize in-memory * arrays without costly duplication. * @param _key Full original key. * @param _keyRemainder Portion of the initial key that must be inserted into the trie. * @param _value Value to insert at the given key. * @return _newPath A new path with the inserted k/v pair and extra supporting nodes. */ function _getNewPath( TrieNode[] memory _path, uint256 _pathLength, bytes memory _key, bytes memory _keyRemainder, bytes memory _value ) private pure returns ( TrieNode[] memory _newPath ) { bytes memory keyRemainder = _keyRemainder; // Most of our logic depends on the status of the last node in the path. TrieNode memory lastNode = _path[_pathLength - 1]; NodeType lastNodeType = _getNodeType(lastNode); // Create an array for newly created nodes. // We need up to three new nodes, depending on the contents of the last node. // Since array resizing is expensive, we'll keep track of the size manually. // We're using an explicit `totalNewNodes += 1` after insertions for clarity. TrieNode[] memory newNodes = new TrieNode[](3); uint256 totalNewNodes = 0; // solhint-disable-next-line max-line-length // Reference: https://github.com/ethereumjs/merkle-patricia-tree/blob/c0a10395aab37d42c175a47114ebfcbd7efcf059/src/baseTrie.ts#L294-L313 bool matchLeaf = false; if (lastNodeType == NodeType.LeafNode) { uint256 l = 0; if (_path.length > 0) { for (uint256 i = 0; i < _path.length - 1; i++) { if (_getNodeType(_path[i]) == NodeType.BranchNode) { l++; } else { l += _getNodeKey(_path[i]).length; } } } if ( _getSharedNibbleLength( _getNodeKey(lastNode), Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l) ) == _getNodeKey(lastNode).length && keyRemainder.length == 0 ) { matchLeaf = true; } } if (matchLeaf) { // We've found a leaf node with the given key. // Simply need to update the value of the node to match. newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value); totalNewNodes += 1; } else if (lastNodeType == NodeType.BranchNode) { if (keyRemainder.length == 0) { // We've found a branch node with the given key. // Simply need to update the value of the node to match. newNodes[totalNewNodes] = _editBranchValue(lastNode, _value); totalNewNodes += 1; } else { // We've found a branch node, but it doesn't contain our key. // Reinsert the old branch for now. newNodes[totalNewNodes] = lastNode; totalNewNodes += 1; // Create a new leaf node, slicing our remainder since the first byte points // to our branch node. newNodes[totalNewNodes] = _makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value); totalNewNodes += 1; } } else { // Our last node is either an extension node or a leaf node with a different key. bytes memory lastNodeKey = _getNodeKey(lastNode); uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder); if (sharedNibbleLength != 0) { // We've got some shared nibbles between the last node and our key remainder. // We'll need to insert an extension node that covers these shared nibbles. bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength); newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value)); totalNewNodes += 1; // Cut down the keys since we've just covered these shared nibbles. lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength); keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength); } // Create an empty branch to fill in. TrieNode memory newBranch = _makeEmptyBranchNode(); if (lastNodeKey.length == 0) { // Key remainder was larger than the key for our last node. // The value within our last node is therefore going to be shifted into // a branch value slot. newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode)); } else { // Last node key was larger than the key remainder. // We're going to modify some index of our branch. uint8 branchKey = uint8(lastNodeKey[0]); // Move on to the next nibble. lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1); if (lastNodeType == NodeType.LeafNode) { // We're dealing with a leaf node. // We'll modify the key and insert the old leaf node into the branch index. TrieNode memory modifiedLastNode = _makeLeafNode(lastNodeKey, _getNodeValue(lastNode)); newBranch = _editBranchIndex( newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded)); } else if (lastNodeKey.length != 0) { // We're dealing with a shrinking extension node. // We need to modify the node to decrease the size of the key. TrieNode memory modifiedLastNode = _makeExtensionNode(lastNodeKey, _getNodeValue(lastNode)); newBranch = _editBranchIndex( newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded)); } else { // We're dealing with an unnecessary extension node. // We're going to delete the node entirely. // Simply insert its current value into the branch index. newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode)); } } if (keyRemainder.length == 0) { // We've got nothing left in the key remainder. // Simply insert the value into the branch value slot. newBranch = _editBranchValue(newBranch, _value); // Push the branch into the list of new nodes. newNodes[totalNewNodes] = newBranch; totalNewNodes += 1; } else { // We've got some key remainder to work with. // We'll be inserting a leaf node into the trie. // First, move on to the next nibble. keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1); // Push the branch into the list of new nodes. newNodes[totalNewNodes] = newBranch; totalNewNodes += 1; // Push a new leaf node for our k/v pair. newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value); totalNewNodes += 1; } } // Finally, join the old path with our newly created nodes. // Since we're overwriting the last node in the path, we use `_pathLength - 1`. return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes); } /** * @notice Computes the trie root from a given path. * @param _nodes Path to some k/v pair. * @param _key Key for the k/v pair. * @return _updatedRoot Root hash for the updated trie. */ function _getUpdatedTrieRoot( TrieNode[] memory _nodes, bytes memory _key ) private pure returns ( bytes32 _updatedRoot ) { bytes memory key = Lib_BytesUtils.toNibbles(_key); // Some variables to keep track of during iteration. TrieNode memory currentNode; NodeType currentNodeType; bytes memory previousNodeHash; // Run through the path backwards to rebuild our root hash. for (uint256 i = _nodes.length; i > 0; i--) { // Pick out the current node. currentNode = _nodes[i - 1]; currentNodeType = _getNodeType(currentNode); if (currentNodeType == NodeType.LeafNode) { // Leaf nodes are already correctly encoded. // Shift the key over to account for the nodes key. bytes memory nodeKey = _getNodeKey(currentNode); key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length); } else if (currentNodeType == NodeType.ExtensionNode) { // Shift the key over to account for the nodes key. bytes memory nodeKey = _getNodeKey(currentNode); key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length); // If this node is the last element in the path, it'll be correctly encoded // and we can skip this part. if (previousNodeHash.length > 0) { // Re-encode the node based on the previous node. currentNode = _editExtensionNodeValue(currentNode, previousNodeHash); } } else if (currentNodeType == NodeType.BranchNode) { // If this node is the last element in the path, it'll be correctly encoded // and we can skip this part. if (previousNodeHash.length > 0) { // Re-encode the node based on the previous node. uint8 branchKey = uint8(key[key.length - 1]); key = Lib_BytesUtils.slice(key, 0, key.length - 1); currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash); } } // Compute the node hash for the next iteration. previousNodeHash = _getNodeHash(currentNode.encoded); } // Current node should be the root at this point. // Simply return the hash of its encoding. return keccak256(currentNode.encoded); } /** * @notice Parses an RLP-encoded proof into something more useful. * @param _proof RLP-encoded proof to parse. * @return _parsed Proof parsed into easily accessible structs. */ function _parseProof( bytes memory _proof ) private pure returns ( TrieNode[] memory _parsed ) { Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof); TrieNode[] memory proof = new TrieNode[](nodes.length); for (uint256 i = 0; i < nodes.length; i++) { bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]); proof[i] = TrieNode({ encoded: encoded, decoded: Lib_RLPReader.readList(encoded) }); } return proof; } /** * @notice Picks out the ID for a node. Node ID is referred to as the * "hash" within the specification, but nodes < 32 bytes are not actually * hashed. * @param _node Node to pull an ID for. * @return _nodeID ID for the node, depending on the size of its contents. */ function _getNodeID( Lib_RLPReader.RLPItem memory _node ) private pure returns ( bytes32 _nodeID ) { bytes memory nodeID; if (_node.length < 32) { // Nodes smaller than 32 bytes are RLP encoded. nodeID = Lib_RLPReader.readRawBytes(_node); } else { // Nodes 32 bytes or larger are hashed. nodeID = Lib_RLPReader.readBytes(_node); } return Lib_BytesUtils.toBytes32(nodeID); } /** * @notice Gets the path for a leaf or extension node. * @param _node Node to get a path for. * @return _path Node path, converted to an array of nibbles. */ function _getNodePath( TrieNode memory _node ) private pure returns ( bytes memory _path ) { return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0])); } /** * @notice Gets the key for a leaf or extension node. Keys are essentially * just paths without any prefix. * @param _node Node to get a key for. * @return _key Node key, converted to an array of nibbles. */ function _getNodeKey( TrieNode memory _node ) private pure returns ( bytes memory _key ) { return _removeHexPrefix(_getNodePath(_node)); } /** * @notice Gets the path for a node. * @param _node Node to get a value for. * @return _value Node value, as hex bytes. */ function _getNodeValue( TrieNode memory _node ) private pure returns ( bytes memory _value ) { return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]); } /** * @notice Computes the node hash for an encoded node. Nodes < 32 bytes * are not hashed, all others are keccak256 hashed. * @param _encoded Encoded node to hash. * @return _hash Hash of the encoded node. Simply the input if < 32 bytes. */ function _getNodeHash( bytes memory _encoded ) private pure returns ( bytes memory _hash ) { if (_encoded.length < 32) { return _encoded; } else { return abi.encodePacked(keccak256(_encoded)); } } /** * @notice Determines the type for a given node. * @param _node Node to determine a type for. * @return _type Type of the node; BranchNode/ExtensionNode/LeafNode. */ function _getNodeType( TrieNode memory _node ) private pure returns ( NodeType _type ) { if (_node.decoded.length == BRANCH_NODE_LENGTH) { return NodeType.BranchNode; } else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) { bytes memory path = _getNodePath(_node); uint8 prefix = uint8(path[0]); if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) { return NodeType.LeafNode; } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) { return NodeType.ExtensionNode; } } revert("Invalid node type"); } /** * @notice Utility; determines the number of nibbles shared between two * nibble arrays. * @param _a First nibble array. * @param _b Second nibble array. * @return _shared Number of shared nibbles. */ function _getSharedNibbleLength( bytes memory _a, bytes memory _b ) private pure returns ( uint256 _shared ) { uint256 i = 0; while (_a.length > i && _b.length > i && _a[i] == _b[i]) { i++; } return i; } /** * @notice Utility; converts an RLP-encoded node into our nice struct. * @param _raw RLP-encoded node to convert. * @return _node Node as a TrieNode struct. */ function _makeNode( bytes[] memory _raw ) private pure returns ( TrieNode memory _node ) { bytes memory encoded = Lib_RLPWriter.writeList(_raw); return TrieNode({ encoded: encoded, decoded: Lib_RLPReader.readList(encoded) }); } /** * @notice Utility; converts an RLP-decoded node into our nice struct. * @param _items RLP-decoded node to convert. * @return _node Node as a TrieNode struct. */ function _makeNode( Lib_RLPReader.RLPItem[] memory _items ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](_items.length); for (uint256 i = 0; i < _items.length; i++) { raw[i] = Lib_RLPReader.readRawBytes(_items[i]); } return _makeNode(raw); } /** * @notice Creates a new extension node. * @param _key Key for the extension node, unprefixed. * @param _value Value for the extension node. * @return _node New extension node with the given k/v pair. */ function _makeExtensionNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_key, false); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); raw[1] = Lib_RLPWriter.writeBytes(_value); return _makeNode(raw); } /** * Creates a new extension node with the same key but a different value. * @param _node Extension node to copy and modify. * @param _value New value for the extension node. * @return New node with the same key and different value. */ function _editExtensionNodeValue( TrieNode memory _node, bytes memory _value ) private pure returns ( TrieNode memory ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_getNodeKey(_node), false); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); if (_value.length < 32) { raw[1] = _value; } else { raw[1] = Lib_RLPWriter.writeBytes(_value); } return _makeNode(raw); } /** * @notice Creates a new leaf node. * @dev This function is essentially identical to `_makeExtensionNode`. * Although we could route both to a single method with a flag, it's * more gas efficient to keep them separate and duplicate the logic. * @param _key Key for the leaf node, unprefixed. * @param _value Value for the leaf node. * @return _node New leaf node with the given k/v pair. */ function _makeLeafNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](2); bytes memory key = _addHexPrefix(_key, true); raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key)); raw[1] = Lib_RLPWriter.writeBytes(_value); return _makeNode(raw); } /** * @notice Creates an empty branch node. * @return _node Empty branch node as a TrieNode struct. */ function _makeEmptyBranchNode() private pure returns ( TrieNode memory _node ) { bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH); for (uint256 i = 0; i < raw.length; i++) { raw[i] = RLP_NULL_BYTES; } return _makeNode(raw); } /** * @notice Modifies the value slot for a given branch. * @param _branch Branch node to modify. * @param _value Value to insert into the branch. * @return _updatedNode Modified branch node. */ function _editBranchValue( TrieNode memory _branch, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode ) { bytes memory encoded = Lib_RLPWriter.writeBytes(_value); _branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded); return _makeNode(_branch.decoded); } /** * @notice Modifies a slot at an index for a given branch. * @param _branch Branch node to modify. * @param _index Slot index to modify. * @param _value Value to insert into the slot. * @return _updatedNode Modified branch node. */ function _editBranchIndex( TrieNode memory _branch, uint8 _index, bytes memory _value ) private pure returns ( TrieNode memory _updatedNode ) { bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value); _branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded); return _makeNode(_branch.decoded); } /** * @notice Utility; adds a prefix to a key. * @param _key Key to prefix. * @param _isLeaf Whether or not the key belongs to a leaf. * @return _prefixedKey Prefixed key. */ function _addHexPrefix( bytes memory _key, bool _isLeaf ) private pure returns ( bytes memory _prefixedKey ) { uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00); uint8 offset = uint8(_key.length % 2); bytes memory prefixed = new bytes(2 - offset); prefixed[0] = bytes1(prefix + offset); return abi.encodePacked(prefixed, _key); } /** * @notice Utility; removes a prefix from a path. * @param _path Path to remove the prefix from. * @return _unprefixedKey Unprefixed key. */ function _removeHexPrefix( bytes memory _path ) private pure returns ( bytes memory _unprefixedKey ) { if (uint8(_path[0]) % 2 == 0) { return Lib_BytesUtils.slice(_path, 2); } else { return Lib_BytesUtils.slice(_path, 1); } } /** * @notice Utility; combines two node arrays. Array lengths are required * because the actual lengths may be longer than the filled lengths. * Array resizing is extremely costly and should be avoided. * @param _a First array to join. * @param _aLength Length of the first array. * @param _b Second array to join. * @param _bLength Length of the second array. * @return _joined Combined node array. */ function _joinNodeArrays( TrieNode[] memory _a, uint256 _aLength, TrieNode[] memory _b, uint256 _bLength ) private pure returns ( TrieNode[] memory _joined ) { TrieNode[] memory ret = new TrieNode[](_aLength + _bLength); // Copy elements from the first array. for (uint256 i = 0; i < _aLength; i++) { ret[i] = _a[i]; } // Copy elements from the second array. for (uint256 i = 0; i < _bLength; i++) { ret[i + _aLength] = _b[i]; } return ret; } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol"; import { iOVM_StateTransitionerFactory } from "../../iOVM/verification/iOVM_StateTransitionerFactory.sol"; import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; /* Contract Imports */ import { OVM_StateTransitioner } from "./OVM_StateTransitioner.sol"; /** * @title OVM_StateTransitionerFactory * @dev The State Transitioner Factory is used by the Fraud Verifier to create a new State * Transitioner during the initialization of a fraud proof. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateTransitionerFactory is iOVM_StateTransitionerFactory, Lib_AddressResolver { /*************** * Constructor * ***************/ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /******************** * Public Functions * ********************/ /** * Creates a new OVM_StateTransitioner * @param _libAddressManager Address of the Address Manager. * @param _stateTransitionIndex Index of the state transition being verified. * @param _preStateRoot State root before the transition was executed. * @param _transactionHash Hash of the executed transaction. * @return New OVM_StateTransitioner instance. */ function create( address _libAddressManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) override public returns ( iOVM_StateTransitioner ) { require( msg.sender == resolve("OVM_FraudVerifier"), "Create can only be done by the OVM_FraudVerifier." ); return new OVM_StateTransitioner( _libAddressManager, _stateTransitionIndex, _preStateRoot, _transactionHash ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol"; /** * @title iOVM_StateTransitionerFactory */ interface iOVM_StateTransitionerFactory { /*************************************** * Public Functions: Contract Creation * ***************************************/ function create( address _proxyManager, uint256 _stateTransitionIndex, bytes32 _preStateRoot, bytes32 _transactionHash ) external returns ( iOVM_StateTransitioner _ovmStateTransitioner ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol"; /** * @title iOVM_FraudVerifier */ interface iOVM_FraudVerifier { /********** * Events * **********/ event FraudProofInitialized( bytes32 _preStateRoot, uint256 _preStateRootIndex, bytes32 _transactionHash, address _who ); event FraudProofFinalized( bytes32 _preStateRoot, uint256 _preStateRootIndex, bytes32 _transactionHash, address _who ); /*************************************** * Public Functions: Transition Status * ***************************************/ function getStateTransitioner(bytes32 _preStateRoot, bytes32 _txHash) external view returns (iOVM_StateTransitioner _transitioner); /**************************************** * Public Functions: Fraud Verification * ****************************************/ function initializeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof, Lib_OVMCodec.Transaction calldata _transaction, Lib_OVMCodec.TransactionChainElement calldata _txChainElement, Lib_OVMCodec.ChainBatchHeader calldata _transactionBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _transactionProof ) external; function finalizeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof, bytes32 _txHash, bytes32 _postStateRoot, Lib_OVMCodec.ChainBatchHeader calldata _postStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof calldata _postStateRootProof ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol"; import { iOVM_StateTransitionerFactory } from "../../iOVM/verification/iOVM_StateTransitionerFactory.sol"; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_StateCommitmentChain } from "../../iOVM/chain/iOVM_StateCommitmentChain.sol"; import { iOVM_CanonicalTransactionChain } from "../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; /* Contract Imports */ import { Abs_FraudContributor } from "./Abs_FraudContributor.sol"; /** * @title OVM_FraudVerifier * @dev The Fraud Verifier contract coordinates the entire fraud proof verification process. * If the fraud proof was successful it prunes any state batches from State Commitment Chain * which were published after the fraudulent state root. * * Compiler used: solc * Runtime target: EVM */ contract OVM_FraudVerifier is Lib_AddressResolver, Abs_FraudContributor, iOVM_FraudVerifier { /******************************************* * Contract Variables: Internal Accounting * *******************************************/ mapping (bytes32 => iOVM_StateTransitioner) internal transitioners; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /*************************************** * Public Functions: Transition Status * ***************************************/ /** * Retrieves the state transitioner for a given root. * @param _preStateRoot State root to query a transitioner for. * @return _transitioner Corresponding state transitioner contract. */ function getStateTransitioner( bytes32 _preStateRoot, bytes32 _txHash ) override public view returns ( iOVM_StateTransitioner _transitioner ) { return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))]; } /**************************************** * Public Functions: Fraud Verification * ****************************************/ /** * Begins the fraud verification process. * @param _preStateRoot State root before the fraudulent transaction. * @param _preStateRootBatchHeader Batch header for the provided pre-state root. * @param _preStateRootProof Inclusion proof for the provided pre-state root. * @param _transaction OVM transaction claimed to be fraudulent. * @param _txChainElement OVM transaction chain element. * @param _transactionBatchHeader Batch header for the provided transaction. * @param _transactionProof Inclusion proof for the provided transaction. */ function initializeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof, Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _transactionBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _transactionProof ) override public contributesToFraudProof(_preStateRoot, Lib_OVMCodec.hashTransaction(_transaction)) { bytes32 _txHash = Lib_OVMCodec.hashTransaction(_transaction); if (_hasStateTransitioner(_preStateRoot, _txHash)) { return; } iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain")); iOVM_CanonicalTransactionChain ovmCanonicalTransactionChain = iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")); require( ovmStateCommitmentChain.verifyStateCommitment( _preStateRoot, _preStateRootBatchHeader, _preStateRootProof ), "Invalid pre-state root inclusion proof." ); require( ovmCanonicalTransactionChain.verifyTransaction( _transaction, _txChainElement, _transactionBatchHeader, _transactionProof ), "Invalid transaction inclusion proof." ); require ( // solhint-disable-next-line max-line-length _preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1 == _transactionBatchHeader.prevTotalElements + _transactionProof.index, "Pre-state root global index must equal to the transaction root global index." ); _deployTransitioner(_preStateRoot, _txHash, _preStateRootProof.index); emit FraudProofInitialized( _preStateRoot, _preStateRootProof.index, _txHash, msg.sender ); } /** * Finalizes the fraud verification process. * @param _preStateRoot State root before the fraudulent transaction. * @param _preStateRootBatchHeader Batch header for the provided pre-state root. * @param _preStateRootProof Inclusion proof for the provided pre-state root. * @param _txHash The transaction for the state root * @param _postStateRoot State root after the fraudulent transaction. * @param _postStateRootBatchHeader Batch header for the provided post-state root. * @param _postStateRootProof Inclusion proof for the provided post-state root. */ function finalizeFraudVerification( bytes32 _preStateRoot, Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof, bytes32 _txHash, bytes32 _postStateRoot, Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader, Lib_OVMCodec.ChainInclusionProof memory _postStateRootProof ) override public contributesToFraudProof(_preStateRoot, _txHash) { iOVM_StateTransitioner transitioner = getStateTransitioner(_preStateRoot, _txHash); iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain")); require( transitioner.isComplete() == true, "State transition process must be completed prior to finalization." ); require ( // solhint-disable-next-line max-line-length _postStateRootBatchHeader.prevTotalElements + _postStateRootProof.index == _preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1, "Post-state root global index must equal to the pre state root global index plus one." ); require( ovmStateCommitmentChain.verifyStateCommitment( _preStateRoot, _preStateRootBatchHeader, _preStateRootProof ), "Invalid pre-state root inclusion proof." ); require( ovmStateCommitmentChain.verifyStateCommitment( _postStateRoot, _postStateRootBatchHeader, _postStateRootProof ), "Invalid post-state root inclusion proof." ); // If the post state root did not match, then there was fraud and we should delete the batch require( _postStateRoot != transitioner.getPostStateRoot(), "State transition has not been proven fraudulent." ); _cancelStateTransition(_postStateRootBatchHeader, _preStateRoot); // TEMPORARY: Remove the transitioner; for minnet. transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] = iOVM_StateTransitioner(0x0000000000000000000000000000000000000000); emit FraudProofFinalized( _preStateRoot, _preStateRootProof.index, _txHash, msg.sender ); } /************************************ * Internal Functions: Verification * ************************************/ /** * Checks whether a transitioner already exists for a given pre-state root. * @param _preStateRoot Pre-state root to check. * @return _exists Whether or not we already have a transitioner for the root. */ function _hasStateTransitioner( bytes32 _preStateRoot, bytes32 _txHash ) internal view returns ( bool _exists ) { return address(getStateTransitioner(_preStateRoot, _txHash)) != address(0); } /** * Deploys a new state transitioner. * @param _preStateRoot Pre-state root to initialize the transitioner with. * @param _txHash Hash of the transaction this transitioner will execute. * @param _stateTransitionIndex Index of the transaction in the chain. */ function _deployTransitioner( bytes32 _preStateRoot, bytes32 _txHash, uint256 _stateTransitionIndex ) internal { transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] = iOVM_StateTransitionerFactory( resolve("OVM_StateTransitionerFactory") ).create( address(libAddressManager), _stateTransitionIndex, _preStateRoot, _txHash ); } /** * Removes a state transition from the state commitment chain. * @param _postStateRootBatchHeader Header for the post-state root. * @param _preStateRoot Pre-state root hash. */ function _cancelStateTransition( Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader, bytes32 _preStateRoot ) internal { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain")); iOVM_BondManager ovmBondManager = iOVM_BondManager(resolve("OVM_BondManager")); // Delete the state batch. ovmStateCommitmentChain.deleteStateBatch( _postStateRootBatchHeader ); // Get the timestamp and publisher for that block. (uint256 timestamp, address publisher) = abi.decode(_postStateRootBatchHeader.extraData, (uint256, address)); // Slash the bonds at the bond manager. ovmBondManager.finalize( _preStateRoot, publisher, timestamp ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateCommitmentChain */ interface iOVM_StateCommitmentChain { /********** * Events * **********/ event StateBatchAppended( uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); event StateBatchDeleted( uint256 indexed _batchIndex, bytes32 _batchRoot ); /******************** * Public Functions * ********************/ /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns ( uint256 _totalBatches ); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestamp() external view returns ( uint256 _lastSequencerTimestamp ); /** * Appends a batch of state roots to the chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatch( bytes32[] calldata _batch, uint256 _shouldStartAtElement ) external; /** * Deletes all state roots after (and including) a given batch. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatch( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external; /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns ( bool _verified ); /** * Checks whether a given batch is still inside its fraud proof window. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindow( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external view returns ( bool _inside ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_ChainStorageContainer } from "./iOVM_ChainStorageContainer.sol"; /** * @title iOVM_CanonicalTransactionChain */ interface iOVM_CanonicalTransactionChain { /********** * Events * **********/ event TransactionEnqueued( address _l1TxOrigin, address _target, uint256 _gasLimit, bytes _data, uint256 _queueIndex, uint256 _timestamp ); event QueueBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event SequencerBatchAppended( uint256 _startingQueueIndex, uint256 _numQueueElements, uint256 _totalElements ); event TransactionBatchAppended( uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); /*********** * Structs * ***********/ struct BatchContext { uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 timestamp; uint256 blockNumber; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() external view returns ( iOVM_ChainStorageContainer ); /** * Accesses the queue storage container. * @return Reference to the queue storage container. */ function queue() external view returns ( iOVM_ChainStorageContainer ); /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns ( uint256 _totalBatches ); /** * Returns the index of the next element to be enqueued. * @return Index for the next queue element. */ function getNextQueueIndex() external view returns ( uint40 ); /** * Gets the queue element at a particular index. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function getQueueElement( uint256 _index ) external view returns ( Lib_OVMCodec.QueueElement memory _element ); /** * Returns the timestamp of the last transaction. * @return Timestamp for the last transaction. */ function getLastTimestamp() external view returns ( uint40 ); /** * Returns the blocknumber of the last transaction. * @return Blocknumber for the last transaction. */ function getLastBlockNumber() external view returns ( uint40 ); /** * Get the number of queue elements which have not yet been included. * @return Number of pending queue elements. */ function getNumPendingQueueElements() external view returns ( uint40 ); /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @return Length of the queue. */ function getQueueLength() external view returns ( uint40 ); /** * Adds a transaction to the queue. * @param _target Target contract to send the transaction to. * @param _gasLimit Gas limit for the given transaction. * @param _data Transaction data. */ function enqueue( address _target, uint256 _gasLimit, bytes memory _data ) external; /** * Appends a given number of queued transactions as a single batch. * @param _numQueuedTransactions Number of transactions to append. */ function appendQueueBatch( uint256 _numQueuedTransactions ) external; /** * Allows the sequencer to append a batch of transactions. * @dev This function uses a custom encoding scheme for efficiency reasons. * .param _shouldStartAtElement Specific batch we expect to start appending to. * .param _totalElementsToAppend Total number of batch elements we expect to append. * .param _contexts Array of batch contexts. * .param _transactionDataFields Array of raw transaction data. */ function appendSequencerBatch( // uint40 _shouldStartAtElement, // uint24 _totalElementsToAppend, // BatchContext[] _contexts, // bytes[] _transactionDataFields ) external; /** * Verifies whether a transaction is included in the chain. * @param _transaction Transaction to verify. * @param _txChainElement Transaction chain element corresponding to the transaction. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof Inclusion proof for the provided transaction chain element. * @return True if the transaction exists in the CTC, false if not. */ function verifyTransaction( Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) external view returns ( bool ); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_ChainStorageContainer */ interface iOVM_ChainStorageContainer { /******************** * Public Functions * ********************/ /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadata( bytes27 _globalMetadata ) external; /** * Retrieves the container's global metadata field. * @return Container global metadata field. */ function getGlobalMetadata() external view returns ( bytes27 ); /** * Retrieves the number of objects stored in the container. * @return Number of objects in the container. */ function length() external view returns ( uint256 ); /** * Pushes an object into the container. * @param _object A 32 byte value to insert into the container. */ function push( bytes32 _object ) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function push( bytes32 _object, bytes27 _globalMetadata ) external; /** * Retrieves an object from the container. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function get( uint256 _index ) external view returns ( bytes32 ); /** * Removes all objects after and including a given index. * @param _index Object index to delete from. */ function deleteElementsAfterInclusive( uint256 _index ) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusive( uint256 _index, bytes27 _globalMetadata ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_BondManager, Errors, ERC20 } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; /** * @title OVM_BondManager * @dev The Bond Manager contract handles deposits in the form of an ERC20 token from bonded * Proposers. It also handles the accounting of gas costs spent by a Verifier during the course of a * fraud proof. In the event of a successful fraud proof, the fraudulent Proposer's bond is slashed, * and the Verifier's gas costs are refunded. * * Compiler used: solc * Runtime target: EVM */ contract OVM_BondManager is iOVM_BondManager, Lib_AddressResolver { /**************************** * Constants and Parameters * ****************************/ /// The period to find the earliest fraud proof for a publisher uint256 public constant multiFraudProofPeriod = 7 days; /// The dispute period uint256 public constant disputePeriodSeconds = 7 days; /// The minimum collateral a sequencer must post uint256 public constant requiredCollateral = 1 ether; /******************************************* * Contract Variables: Contract References * *******************************************/ /// The bond token ERC20 immutable public token; /******************************************** * Contract Variables: Internal Accounting * *******************************************/ /// The bonds posted by each proposer mapping(address => Bond) public bonds; /// For each pre-state root, there's an array of witnessProviders that must be rewarded /// for posting witnesses mapping(bytes32 => Rewards) public witnessProviders; /*************** * Constructor * ***************/ /// Initializes with a ERC20 token to be used for the fidelity bonds /// and with the Address Manager constructor( ERC20 _token, address _libAddressManager ) Lib_AddressResolver(_libAddressManager) { token = _token; } /******************** * Public Functions * ********************/ /// Adds `who` to the list of witnessProviders for the provided `preStateRoot`. function recordGasSpent(bytes32 _preStateRoot, bytes32 _txHash, address who, uint256 gasSpent) override public { // The sender must be the transitioner that corresponds to the claimed pre-state root address transitioner = address(iOVM_FraudVerifier(resolve("OVM_FraudVerifier")) .getStateTransitioner(_preStateRoot, _txHash)); require(transitioner == msg.sender, Errors.ONLY_TRANSITIONER); witnessProviders[_preStateRoot].total += gasSpent; witnessProviders[_preStateRoot].gasSpent[who] += gasSpent; } /// Slashes + distributes rewards or frees up the sequencer's bond, only called by /// `FraudVerifier.finalizeFraudVerification` function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) override public { require(msg.sender == resolve("OVM_FraudVerifier"), Errors.ONLY_FRAUD_VERIFIER); require(witnessProviders[_preStateRoot].canClaim == false, Errors.ALREADY_FINALIZED); // allow users to claim from that state root's // pool of collateral (effectively slashing the sequencer) witnessProviders[_preStateRoot].canClaim = true; Bond storage bond = bonds[publisher]; if (bond.firstDisputeAt == 0) { bond.firstDisputeAt = block.timestamp; bond.earliestDisputedStateRoot = _preStateRoot; bond.earliestTimestamp = timestamp; } else if ( // only update the disputed state root for the publisher if it's within // the dispute period _and_ if it's before the previous one block.timestamp < bond.firstDisputeAt + multiFraudProofPeriod && timestamp < bond.earliestTimestamp ) { bond.earliestDisputedStateRoot = _preStateRoot; bond.earliestTimestamp = timestamp; } // if the fraud proof's dispute period does not intersect with the // withdrawal's timestamp, then the user should not be slashed // e.g if a user at day 10 submits a withdrawal, and a fraud proof // from day 1 gets published, the user won't be slashed since day 8 (1d + 7d) // is before the user started their withdrawal. on the contrary, if the user // had started their withdrawal at, say, day 6, they would be slashed if ( bond.withdrawalTimestamp != 0 && uint256(bond.withdrawalTimestamp) > timestamp + disputePeriodSeconds && bond.state == State.WITHDRAWING ) { return; } // slash! bond.state = State.NOT_COLLATERALIZED; } /// Sequencers call this function to post collateral which will be used for /// the `appendBatch` call function deposit() override public { require( token.transferFrom(msg.sender, address(this), requiredCollateral), Errors.ERC20_ERR ); // This cannot overflow bonds[msg.sender].state = State.COLLATERALIZED; } /// Starts the withdrawal for a publisher function startWithdrawal() override public { Bond storage bond = bonds[msg.sender]; require(bond.withdrawalTimestamp == 0, Errors.WITHDRAWAL_PENDING); require(bond.state == State.COLLATERALIZED, Errors.WRONG_STATE); bond.state = State.WITHDRAWING; bond.withdrawalTimestamp = uint32(block.timestamp); } /// Finalizes a pending withdrawal from a publisher function finalizeWithdrawal() override public { Bond storage bond = bonds[msg.sender]; require( block.timestamp >= uint256(bond.withdrawalTimestamp) + disputePeriodSeconds, Errors.TOO_EARLY ); require(bond.state == State.WITHDRAWING, Errors.SLASHED); // refunds! bond.state = State.NOT_COLLATERALIZED; bond.withdrawalTimestamp = 0; require( token.transfer(msg.sender, requiredCollateral), Errors.ERC20_ERR ); } /// Claims the user's reward for the witnesses they provided for the earliest /// disputed state root of the designated publisher function claim(address who) override public { Bond storage bond = bonds[who]; require( block.timestamp >= bond.firstDisputeAt + multiFraudProofPeriod, Errors.WAIT_FOR_DISPUTES ); // reward the earliest state root for this publisher bytes32 _preStateRoot = bond.earliestDisputedStateRoot; Rewards storage rewards = witnessProviders[_preStateRoot]; // only allow claiming if fraud was proven in `finalize` require(rewards.canClaim, Errors.CANNOT_CLAIM); // proportional allocation - only reward 50% (rest gets locked in the // contract forever uint256 amount = (requiredCollateral * rewards.gasSpent[msg.sender]) / (2 * rewards.total); // reset the user's spent gas so they cannot double claim rewards.gasSpent[msg.sender] = 0; // transfer require(token.transfer(msg.sender, amount), Errors.ERC20_ERR); } /// Checks if the user is collateralized function isCollateralized(address who) override public view returns (bool) { return bonds[who].state == State.COLLATERALIZED; } /// Gets how many witnesses the user has provided for the state root function getGasSpent(bytes32 preStateRoot, address who) override public view returns (uint256) { return witnessProviders[preStateRoot].gasSpent[who]; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; import { OVM_BondManager } from "./../optimistic-ethereum/OVM/verification/OVM_BondManager.sol"; contract Mock_FraudVerifier { OVM_BondManager bondManager; mapping (bytes32 => address) transitioners; function setBondManager(OVM_BondManager _bondManager) public { bondManager = _bondManager; } function setStateTransitioner(bytes32 preStateRoot, bytes32 txHash, address addr) public { transitioners[keccak256(abi.encodePacked(preStateRoot, txHash))] = addr; } function getStateTransitioner( bytes32 _preStateRoot, bytes32 _txHash ) public view returns ( address ) { return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))]; } function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) public { bondManager.finalize(_preStateRoot, publisher, timestamp); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol"; /* Interface Imports */ import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol"; import { iOVM_StateCommitmentChain } from "../../iOVM/chain/iOVM_StateCommitmentChain.sol"; import { iOVM_CanonicalTransactionChain } from "../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol"; /* External Imports */ import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title OVM_StateCommitmentChain * @dev The State Commitment Chain (SCC) contract contains a list of proposed state roots which * Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC). * Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique * state root calculated off-chain by applying the canonical transactions one by one. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateCommitmentChain is iOVM_StateCommitmentChain, Lib_AddressResolver { /************* * Constants * *************/ uint256 public FRAUD_PROOF_WINDOW; uint256 public SEQUENCER_PUBLISH_WINDOW; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, uint256 _fraudProofWindow, uint256 _sequencerPublishWindow ) Lib_AddressResolver(_libAddressManager) { FRAUD_PROOF_WINDOW = _fraudProofWindow; SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() public view returns ( iOVM_ChainStorageContainer ) { return iOVM_ChainStorageContainer( resolve("OVM_ChainStorageContainer-SCC-batches") ); } /** * @inheritdoc iOVM_StateCommitmentChain */ function getTotalElements() override public view returns ( uint256 _totalElements ) { (uint40 totalElements, ) = _getBatchExtraData(); return uint256(totalElements); } /** * @inheritdoc iOVM_StateCommitmentChain */ function getTotalBatches() override public view returns ( uint256 _totalBatches ) { return batches().length(); } /** * @inheritdoc iOVM_StateCommitmentChain */ function getLastSequencerTimestamp() override public view returns ( uint256 _lastSequencerTimestamp ) { (, uint40 lastSequencerTimestamp) = _getBatchExtraData(); return uint256(lastSequencerTimestamp); } /** * @inheritdoc iOVM_StateCommitmentChain */ function appendStateBatch( bytes32[] memory _batch, uint256 _shouldStartAtElement ) override public { // Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the // publication of batches by some other user. require( _shouldStartAtElement == getTotalElements(), "Actual batch start index does not match expected start index." ); // Proposers must have previously staked at the BondManager require( iOVM_BondManager(resolve("OVM_BondManager")).isCollateralized(msg.sender), "Proposer does not have enough collateral posted" ); require( _batch.length > 0, "Cannot submit an empty state batch." ); require( getTotalElements() + _batch.length <= iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain")) .getTotalElements(), "Number of state roots cannot exceed the number of canonical transactions." ); // Pass the block's timestamp and the publisher of the data // to be used in the fraud proofs _appendBatch( _batch, abi.encode(block.timestamp, msg.sender) ); } /** * @inheritdoc iOVM_StateCommitmentChain */ function deleteStateBatch( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public { require( msg.sender == resolve("OVM_FraudVerifier"), "State batches can only be deleted by the OVM_FraudVerifier." ); require( _isValidBatchHeader(_batchHeader), "Invalid batch header." ); require( insideFraudProofWindow(_batchHeader), "State batches can only be deleted within the fraud proof window." ); _deleteBatch(_batchHeader); } /** * @inheritdoc iOVM_StateCommitmentChain */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) override public view returns ( bool ) { require( _isValidBatchHeader(_batchHeader), "Invalid batch header." ); require( Lib_MerkleTree.verify( _batchHeader.batchRoot, _element, _proof.index, _proof.siblings, _batchHeader.batchSize ), "Invalid inclusion proof." ); return true; } /** * @inheritdoc iOVM_StateCommitmentChain */ function insideFraudProofWindow( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public view returns ( bool _inside ) { (uint256 timestamp,) = abi.decode( _batchHeader.extraData, (uint256, address) ); require( timestamp != 0, "Batch header timestamp cannot be zero" ); return SafeMath.add(timestamp, FRAUD_PROOF_WINDOW) > block.timestamp; } /********************** * Internal Functions * **********************/ /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Timestamp of the last batch submitted by the sequencer. */ function _getBatchExtraData() internal view returns ( uint40, uint40 ) { bytes27 extraData = batches().getGlobalMetadata(); // solhint-disable max-line-length uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) lastSequencerTimestamp := shr(40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)) } // solhint-enable max-line-length return ( totalElements, lastSequencerTimestamp ); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. * @return Encoded batch context. */ function _makeBatchExtraData( uint40 _totalElements, uint40 _lastSequencerTimestamp ) internal pure returns ( bytes27 ) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } /** * Appends a batch to the chain. * @param _batch Elements within the batch. * @param _extraData Any extra data to append to the batch. */ function _appendBatch( bytes32[] memory _batch, bytes memory _extraData ) internal { address sequencer = resolve("OVM_Proposer"); (uint40 totalElements, uint40 lastSequencerTimestamp) = _getBatchExtraData(); if (msg.sender == sequencer) { lastSequencerTimestamp = uint40(block.timestamp); } else { // We keep track of the last batch submitted by the sequencer so there's a window in // which only the sequencer can publish state roots. A window like this just reduces // the chance of "system breaking" state roots being published while we're still in // testing mode. This window should be removed or significantly reduced in the future. require( lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp, "Cannot publish state roots within the sequencer publication window." ); } // For efficiency reasons getMerkleRoot modifies the `_batch` argument in place // while calculating the root hash therefore any arguments passed to it must not // be used again afterwards Lib_OVMCodec.ChainBatchHeader memory batchHeader = Lib_OVMCodec.ChainBatchHeader({ batchIndex: getTotalBatches(), batchRoot: Lib_MerkleTree.getMerkleRoot(_batch), batchSize: _batch.length, prevTotalElements: totalElements, extraData: _extraData }); emit StateBatchAppended( batchHeader.batchIndex, batchHeader.batchRoot, batchHeader.batchSize, batchHeader.prevTotalElements, batchHeader.extraData ); batches().push( Lib_OVMCodec.hashBatchHeader(batchHeader), _makeBatchExtraData( uint40(batchHeader.prevTotalElements + batchHeader.batchSize), lastSequencerTimestamp ) ); } /** * Removes a batch and all subsequent batches from the chain. * @param _batchHeader Header of the batch to remove. */ function _deleteBatch( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal { require( _batchHeader.batchIndex < batches().length(), "Invalid batch index." ); require( _isValidBatchHeader(_batchHeader), "Invalid batch header." ); batches().deleteElementsAfterInclusive( _batchHeader.batchIndex, _makeBatchExtraData( uint40(_batchHeader.prevTotalElements), 0 ) ); emit StateBatchDeleted( _batchHeader.batchIndex, _batchHeader.batchRoot ); } /** * Checks that a batch header matches the stored hash for the given index. * @param _batchHeader Batch header to validate. * @return Whether or not the header matches the stored one. */ function _isValidBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal view returns ( bool ) { return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(_batchHeader.batchIndex); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_MerkleTree * @author River Keefer */ library Lib_MerkleTree { /********************** * Internal Functions * **********************/ /** * Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number * of leaves passed in is not a power of two, it pads out the tree with zero hashes. * If you do not know the original length of elements for the tree you are verifying, then * this may allow empty leaves past _elements.length to pass a verification check down the line. * Note that the _elements argument is modified, therefore it must not be used again afterwards * @param _elements Array of hashes from which to generate a merkle root. * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above). */ function getMerkleRoot( bytes32[] memory _elements ) internal pure returns ( bytes32 ) { require( _elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash." ); if (_elements.length == 1) { return _elements[0]; } uint256[16] memory defaults = [ 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563, 0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d, 0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d, 0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8, 0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da, 0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5, 0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7, 0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead, 0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10, 0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82, 0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516, 0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c, 0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e, 0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab, 0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862, 0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10 ]; // Reserve memory space for our hashes. bytes memory buf = new bytes(64); // We'll need to keep track of left and right siblings. bytes32 leftSibling; bytes32 rightSibling; // Number of non-empty nodes at the current depth. uint256 rowSize = _elements.length; // Current depth, counting from 0 at the leaves uint256 depth = 0; // Common sub-expressions uint256 halfRowSize; // rowSize / 2 bool rowSizeIsOdd; // rowSize % 2 == 1 while (rowSize > 1) { halfRowSize = rowSize / 2; rowSizeIsOdd = rowSize % 2 == 1; for (uint256 i = 0; i < halfRowSize; i++) { leftSibling = _elements[(2 * i) ]; rightSibling = _elements[(2 * i) + 1]; assembly { mstore(add(buf, 32), leftSibling ) mstore(add(buf, 64), rightSibling) } _elements[i] = keccak256(buf); } if (rowSizeIsOdd) { leftSibling = _elements[rowSize - 1]; rightSibling = bytes32(defaults[depth]); assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[halfRowSize] = keccak256(buf); } rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0); depth++; } return _elements[0]; } /** * Verifies a merkle branch for the given leaf hash. Assumes the original length * of leaves generated is a known, correct input, and does not return true for indices * extending past that index (even if _siblings would be otherwise valid.) * @param _root The Merkle root to verify against. * @param _leaf The leaf hash to verify inclusion of. * @param _index The index in the tree of this leaf. * @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0 * (bottom of the tree). * @param _totalLeaves The total number of leaves originally passed into. * @return Whether or not the merkle branch and leaf passes verification. */ function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) internal pure returns ( bool ) { require( _totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero." ); require( _index < _totalLeaves, "Lib_MerkleTree: Index out of bounds." ); require( _siblings.length == _ceilLog2(_totalLeaves), "Lib_MerkleTree: Total siblings does not correctly correspond to total leaves." ); bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { if ((_index & 1) == 1) { computedRoot = keccak256( abi.encodePacked( _siblings[i], computedRoot ) ); } else { computedRoot = keccak256( abi.encodePacked( computedRoot, _siblings[i] ) ); } _index >>= 1; } return _root == computedRoot; } /********************* * Private Functions * *********************/ /** * Calculates the integer ceiling of the log base 2 of an input. * @param _in Unsigned input to calculate the log. * @return ceil(log_base_2(_in)) */ function _ceilLog2( uint256 _in ) private pure returns ( uint256 ) { require( _in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0." ); if (_in == 1) { return 0; } // Find the highest set bit (will be floor(log_2)). // Borrowed with <3 from https://github.com/ethereum/solidity-examples uint256 val = _in; uint256 highest = 0; for (uint256 i = 128; i >= 1; i >>= 1) { if (val & (uint(1) << i) - 1 << i != 0) { highest += i; val >>= i; } } // Increment by one if this is not a perfect logarithm. if ((uint(1) << highest) != _in) { highest += 1; } return highest; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Buffer } from "../../libraries/utils/Lib_Buffer.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /* Interface Imports */ import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol"; /** * @title OVM_ChainStorageContainer * @dev The Chain Storage Container provides its owner contract with read, write and delete * functionality. This provides gas efficiency gains by enabling it to overwrite storage slots which * can no longer be used in a fraud proof due to the fraud window having passed, and the associated * chain state or transactions being finalized. * Three distinct Chain Storage Containers will be deployed on Layer 1: * 1. Stores transaction batches for the Canonical Transaction Chain * 2. Stores queued transactions for the Canonical Transaction Chain * 3. Stores chain state batches for the State Commitment Chain * * Compiler used: solc * Runtime target: EVM */ contract OVM_ChainStorageContainer is iOVM_ChainStorageContainer, Lib_AddressResolver { /************* * Libraries * *************/ using Lib_Buffer for Lib_Buffer.Buffer; /************* * Variables * *************/ string public owner; Lib_Buffer.Buffer internal buffer; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. * @param _owner Name of the contract that owns this container (will be resolved later). */ constructor( address _libAddressManager, string memory _owner ) Lib_AddressResolver(_libAddressManager) { owner = _owner; } /********************** * Function Modifiers * **********************/ modifier onlyOwner() { require( msg.sender == resolve(owner), "OVM_ChainStorageContainer: Function can only be called by the owner." ); _; } /******************** * Public Functions * ********************/ /** * @inheritdoc iOVM_ChainStorageContainer */ function setGlobalMetadata( bytes27 _globalMetadata ) override public onlyOwner { return buffer.setExtraData(_globalMetadata); } /** * @inheritdoc iOVM_ChainStorageContainer */ function getGlobalMetadata() override public view returns ( bytes27 ) { return buffer.getExtraData(); } /** * @inheritdoc iOVM_ChainStorageContainer */ function length() override public view returns ( uint256 ) { return uint256(buffer.getLength()); } /** * @inheritdoc iOVM_ChainStorageContainer */ function push( bytes32 _object ) override public onlyOwner { buffer.push(_object); } /** * @inheritdoc iOVM_ChainStorageContainer */ function push( bytes32 _object, bytes27 _globalMetadata ) override public onlyOwner { buffer.push(_object, _globalMetadata); } /** * @inheritdoc iOVM_ChainStorageContainer */ function get( uint256 _index ) override public view returns ( bytes32 ) { return buffer.get(uint40(_index)); } /** * @inheritdoc iOVM_ChainStorageContainer */ function deleteElementsAfterInclusive( uint256 _index ) override public onlyOwner { buffer.deleteElementsAfterInclusive( uint40(_index) ); } /** * @inheritdoc iOVM_ChainStorageContainer */ function deleteElementsAfterInclusive( uint256 _index, bytes27 _globalMetadata ) override public onlyOwner { buffer.deleteElementsAfterInclusive( uint40(_index), _globalMetadata ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_Buffer * @dev This library implements a bytes32 storage array with some additional gas-optimized * functionality. In particular, it encodes its length as a uint40, and tightly packs this with an * overwritable "extra data" field so we can store more information with a single SSTORE. */ library Lib_Buffer { /************* * Libraries * *************/ using Lib_Buffer for Buffer; /*********** * Structs * ***********/ struct Buffer { bytes32 context; mapping (uint256 => bytes32) buf; } struct BufferContext { // Stores the length of the array. Uint40 is way more elements than we'll ever reasonably // need in an array and we get an extra 27 bytes of extra data to play with. uint40 length; // Arbitrary extra data that can be modified whenever the length is updated. Useful for // squeezing out some gas optimizations. bytes27 extraData; } /********************** * Internal Functions * **********************/ /** * Pushes a single element to the buffer. * @param _self Buffer to access. * @param _value Value to push to the buffer. * @param _extraData Global extra data. */ function push( Buffer storage _self, bytes32 _value, bytes27 _extraData ) internal { BufferContext memory ctx = _self.getContext(); _self.buf[ctx.length] = _value; // Bump the global index and insert our extra data, then save the context. ctx.length++; ctx.extraData = _extraData; _self.setContext(ctx); } /** * Pushes a single element to the buffer. * @param _self Buffer to access. * @param _value Value to push to the buffer. */ function push( Buffer storage _self, bytes32 _value ) internal { BufferContext memory ctx = _self.getContext(); _self.push( _value, ctx.extraData ); } /** * Retrieves an element from the buffer. * @param _self Buffer to access. * @param _index Element index to retrieve. * @return Value of the element at the given index. */ function get( Buffer storage _self, uint256 _index ) internal view returns ( bytes32 ) { BufferContext memory ctx = _self.getContext(); require( _index < ctx.length, "Index out of bounds." ); return _self.buf[_index]; } /** * Deletes all elements after (and including) a given index. * @param _self Buffer to access. * @param _index Index of the element to delete from (inclusive). * @param _extraData Optional global extra data. */ function deleteElementsAfterInclusive( Buffer storage _self, uint40 _index, bytes27 _extraData ) internal { BufferContext memory ctx = _self.getContext(); require( _index < ctx.length, "Index out of bounds." ); // Set our length and extra data, save the context. ctx.length = _index; ctx.extraData = _extraData; _self.setContext(ctx); } /** * Deletes all elements after (and including) a given index. * @param _self Buffer to access. * @param _index Index of the element to delete from (inclusive). */ function deleteElementsAfterInclusive( Buffer storage _self, uint40 _index ) internal { BufferContext memory ctx = _self.getContext(); _self.deleteElementsAfterInclusive( _index, ctx.extraData ); } /** * Retrieves the current global index. * @param _self Buffer to access. * @return Current global index. */ function getLength( Buffer storage _self ) internal view returns ( uint40 ) { BufferContext memory ctx = _self.getContext(); return ctx.length; } /** * Changes current global extra data. * @param _self Buffer to access. * @param _extraData New global extra data. */ function setExtraData( Buffer storage _self, bytes27 _extraData ) internal { BufferContext memory ctx = _self.getContext(); ctx.extraData = _extraData; _self.setContext(ctx); } /** * Retrieves the current global extra data. * @param _self Buffer to access. * @return Current global extra data. */ function getExtraData( Buffer storage _self ) internal view returns ( bytes27 ) { BufferContext memory ctx = _self.getContext(); return ctx.extraData; } /** * Sets the current buffer context. * @param _self Buffer to access. * @param _ctx Current buffer context. */ function setContext( Buffer storage _self, BufferContext memory _ctx ) internal { bytes32 context; uint40 length = _ctx.length; bytes27 extraData = _ctx.extraData; assembly { context := length context := or(context, extraData) } if (_self.context != context) { _self.context = context; } } /** * Retrieves the current buffer context. * @param _self Buffer to access. * @return Current buffer context. */ function getContext( Buffer storage _self ) internal view returns ( BufferContext memory ) { bytes32 context = _self.context; uint40 length; bytes27 extraData; assembly { // solhint-disable-next-line max-line-length length := and(context, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) // solhint-disable-next-line max-line-length extraData := and(context, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000) } return BufferContext({ length: length, extraData: extraData }); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_Buffer } from "../../optimistic-ethereum/libraries/utils/Lib_Buffer.sol"; /** * @title TestLib_Buffer */ contract TestLib_Buffer { using Lib_Buffer for Lib_Buffer.Buffer; Lib_Buffer.Buffer internal buf; function push( bytes32 _value, bytes27 _extraData ) public { buf.push( _value, _extraData ); } function get( uint256 _index ) public view returns ( bytes32 ) { return buf.get(_index); } function deleteElementsAfterInclusive( uint40 _index ) public { return buf.deleteElementsAfterInclusive( _index ); } function deleteElementsAfterInclusive( uint40 _index, bytes27 _extraData ) public { return buf.deleteElementsAfterInclusive( _index, _extraData ); } function getLength() public view returns ( uint40 ) { return buf.getLength(); } function setExtraData( bytes27 _extraData ) public { return buf.setExtraData( _extraData ); } function getExtraData() public view returns ( bytes27 ) { return buf.getExtraData(); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol"; /* Interface Imports */ import { iOVM_CanonicalTransactionChain } from "../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol"; /* Contract Imports */ import { OVM_ExecutionManager } from "../execution/OVM_ExecutionManager.sol"; /* External Imports */ import { Math } from "@openzeppelin/contracts/math/Math.sol"; /** * @title OVM_CanonicalTransactionChain * @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions * which must be applied to the rollup state. It defines the ordering of rollup transactions by * writing them to the 'CTC:batches' instance of the Chain Storage Container. * The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the * Sequencer will eventually append it to the rollup state. * If the Sequencer does not include an enqueued transaction within the 'force inclusion period', * then any account may force it to be included by calling appendQueueBatch(). * * Compiler used: solc * Runtime target: EVM */ contract OVM_CanonicalTransactionChain is iOVM_CanonicalTransactionChain, Lib_AddressResolver { /************* * Constants * *************/ // L2 tx gas-related uint256 constant public MIN_ROLLUP_TX_GAS = 100000; uint256 constant public MAX_ROLLUP_TX_SIZE = 50000; uint256 constant public L2_GAS_DISCOUNT_DIVISOR = 32; // Encoding-related (all in bytes) uint256 constant internal BATCH_CONTEXT_SIZE = 16; uint256 constant internal BATCH_CONTEXT_LENGTH_POS = 12; uint256 constant internal BATCH_CONTEXT_START_POS = 15; uint256 constant internal TX_DATA_HEADER_SIZE = 3; uint256 constant internal BYTES_TILL_TX_DATA = 65; /************* * Variables * *************/ uint256 public forceInclusionPeriodSeconds; uint256 public forceInclusionPeriodBlocks; uint256 public maxTransactionGasLimit; /*************** * Constructor * ***************/ constructor( address _libAddressManager, uint256 _forceInclusionPeriodSeconds, uint256 _forceInclusionPeriodBlocks, uint256 _maxTransactionGasLimit ) Lib_AddressResolver(_libAddressManager) { forceInclusionPeriodSeconds = _forceInclusionPeriodSeconds; forceInclusionPeriodBlocks = _forceInclusionPeriodBlocks; maxTransactionGasLimit = _maxTransactionGasLimit; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() override public view returns ( iOVM_ChainStorageContainer ) { return iOVM_ChainStorageContainer( resolve("OVM_ChainStorageContainer-CTC-batches") ); } /** * Accesses the queue storage container. * @return Reference to the queue storage container. */ function queue() override public view returns ( iOVM_ChainStorageContainer ) { return iOVM_ChainStorageContainer( resolve("OVM_ChainStorageContainer-CTC-queue") ); } /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() override public view returns ( uint256 _totalElements ) { (uint40 totalElements,,,) = _getBatchExtraData(); return uint256(totalElements); } /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() override public view returns ( uint256 _totalBatches ) { return batches().length(); } /** * Returns the index of the next element to be enqueued. * @return Index for the next queue element. */ function getNextQueueIndex() override public view returns ( uint40 ) { (,uint40 nextQueueIndex,,) = _getBatchExtraData(); return nextQueueIndex; } /** * Returns the timestamp of the last transaction. * @return Timestamp for the last transaction. */ function getLastTimestamp() override public view returns ( uint40 ) { (,,uint40 lastTimestamp,) = _getBatchExtraData(); return lastTimestamp; } /** * Returns the blocknumber of the last transaction. * @return Blocknumber for the last transaction. */ function getLastBlockNumber() override public view returns ( uint40 ) { (,,,uint40 lastBlockNumber) = _getBatchExtraData(); return lastBlockNumber; } /** * Gets the queue element at a particular index. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function getQueueElement( uint256 _index ) override public view returns ( Lib_OVMCodec.QueueElement memory _element ) { return _getQueueElement( _index, queue() ); } /** * Get the number of queue elements which have not yet been included. * @return Number of pending queue elements. */ function getNumPendingQueueElements() override public view returns ( uint40 ) { return getQueueLength() - getNextQueueIndex(); } /** * Retrieves the length of the queue, including * both pending and canonical transactions. * @return Length of the queue. */ function getQueueLength() override public view returns ( uint40 ) { return _getQueueLength( queue() ); } /** * Adds a transaction to the queue. * @param _target Target L2 contract to send the transaction to. * @param _gasLimit Gas limit for the enqueued L2 transaction. * @param _data Transaction data. */ function enqueue( address _target, uint256 _gasLimit, bytes memory _data ) override public { require( _data.length <= MAX_ROLLUP_TX_SIZE, "Transaction data size exceeds maximum for rollup transaction." ); require( _gasLimit <= maxTransactionGasLimit, "Transaction gas limit exceeds maximum for rollup transaction." ); require( _gasLimit >= MIN_ROLLUP_TX_GAS, "Transaction gas limit too low to enqueue." ); // We need to consume some amount of L1 gas in order to rate limit transactions going into // L2. However, L2 is cheaper than L1 so we only need to burn some small proportion of the // provided L1 gas. uint256 gasToConsume = _gasLimit/L2_GAS_DISCOUNT_DIVISOR; uint256 startingGas = gasleft(); // Although this check is not necessary (burn below will run out of gas if not true), it // gives the user an explicit reason as to why the enqueue attempt failed. require( startingGas > gasToConsume, "Insufficient gas for L2 rate limiting burn." ); // Here we do some "dumb" work in order to burn gas, although we should probably replace // this with something like minting gas token later on. uint256 i; while(startingGas - gasleft() < gasToConsume) { i++; } bytes32 transactionHash = keccak256( abi.encode( msg.sender, _target, _gasLimit, _data ) ); bytes32 timestampAndBlockNumber; assembly { timestampAndBlockNumber := timestamp() timestampAndBlockNumber := or(timestampAndBlockNumber, shl(40, number())) } iOVM_ChainStorageContainer queueRef = queue(); queueRef.push(transactionHash); queueRef.push(timestampAndBlockNumber); // The underlying queue data structure stores 2 elements // per insertion, so to get the real queue length we need // to divide by 2 and subtract 1. uint256 queueIndex = queueRef.length() / 2 - 1; emit TransactionEnqueued( msg.sender, _target, _gasLimit, _data, queueIndex, block.timestamp ); } /** * Appends a given number of queued transactions as a single batch. * param _numQueuedTransactions Number of transactions to append. */ function appendQueueBatch( uint256 // _numQueuedTransactions ) override public pure { // TEMPORARY: Disable `appendQueueBatch` for minnet revert("appendQueueBatch is currently disabled."); // solhint-disable max-line-length // _numQueuedTransactions = Math.min(_numQueuedTransactions, getNumPendingQueueElements()); // require( // _numQueuedTransactions > 0, // "Must append more than zero transactions." // ); // bytes32[] memory leaves = new bytes32[](_numQueuedTransactions); // uint40 nextQueueIndex = getNextQueueIndex(); // for (uint256 i = 0; i < _numQueuedTransactions; i++) { // if (msg.sender != resolve("OVM_Sequencer")) { // Lib_OVMCodec.QueueElement memory el = getQueueElement(nextQueueIndex); // require( // el.timestamp + forceInclusionPeriodSeconds < block.timestamp, // "Queue transactions cannot be submitted during the sequencer inclusion period." // ); // } // leaves[i] = _getQueueLeafHash(nextQueueIndex); // nextQueueIndex++; // } // Lib_OVMCodec.QueueElement memory lastElement = getQueueElement(nextQueueIndex - 1); // _appendBatch( // Lib_MerkleTree.getMerkleRoot(leaves), // _numQueuedTransactions, // _numQueuedTransactions, // lastElement.timestamp, // lastElement.blockNumber // ); // emit QueueBatchAppended( // nextQueueIndex - _numQueuedTransactions, // _numQueuedTransactions, // getTotalElements() // ); // solhint-enable max-line-length } /** * Allows the sequencer to append a batch of transactions. * @dev This function uses a custom encoding scheme for efficiency reasons. * .param _shouldStartAtElement Specific batch we expect to start appending to. * .param _totalElementsToAppend Total number of batch elements we expect to append. * .param _contexts Array of batch contexts. * .param _transactionDataFields Array of raw transaction data. */ function appendSequencerBatch() override public { uint40 shouldStartAtElement; uint24 totalElementsToAppend; uint24 numContexts; assembly { shouldStartAtElement := shr(216, calldataload(4)) totalElementsToAppend := shr(232, calldataload(9)) numContexts := shr(232, calldataload(12)) } require( shouldStartAtElement == getTotalElements(), "Actual batch start index does not match expected start index." ); require( msg.sender == resolve("OVM_Sequencer"), "Function can only be called by the Sequencer." ); require( numContexts > 0, "Must provide at least one batch context." ); require( totalElementsToAppend > 0, "Must append at least one element." ); uint40 nextTransactionPtr = uint40( BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts ); require( msg.data.length >= nextTransactionPtr, "Not enough BatchContexts provided." ); // Take a reference to the queue and its length so we don't have to keep resolving it. // Length isn't going to change during the course of execution, so it's fine to simply // resolve this once at the start. Saves gas. iOVM_ChainStorageContainer queueRef = queue(); uint40 queueLength = _getQueueLength(queueRef); // Reserve some memory to save gas on hashing later on. This is a relatively safe estimate // for the average transaction size that will prevent having to resize this chunk of memory // later on. Saves gas. bytes memory hashMemory = new bytes((msg.data.length / totalElementsToAppend) * 2); // Initialize the array of canonical chain leaves that we will append. bytes32[] memory leaves = new bytes32[](totalElementsToAppend); // Each leaf index corresponds to a tx, either sequenced or enqueued. uint32 leafIndex = 0; // Counter for number of sequencer transactions appended so far. uint32 numSequencerTransactions = 0; // We will sequentially append leaves which are pointers to the queue. // The initial queue index is what is currently in storage. uint40 nextQueueIndex = getNextQueueIndex(); BatchContext memory curContext; for (uint32 i = 0; i < numContexts; i++) { BatchContext memory nextContext = _getBatchContext(i); if (i == 0) { // Execute a special check for the first batch. _validateFirstBatchContext(nextContext); } // Execute this check on every single batch, including the first one. _validateNextBatchContext( curContext, nextContext, nextQueueIndex, queueRef ); // Now we can update our current context. curContext = nextContext; // Process sequencer transactions first. for (uint32 j = 0; j < curContext.numSequencedTransactions; j++) { uint256 txDataLength; assembly { txDataLength := shr(232, calldataload(nextTransactionPtr)) } require( txDataLength <= MAX_ROLLUP_TX_SIZE, "Transaction data size exceeds maximum for rollup transaction." ); leaves[leafIndex] = _getSequencerLeafHash( curContext, nextTransactionPtr, txDataLength, hashMemory ); nextTransactionPtr += uint40(TX_DATA_HEADER_SIZE + txDataLength); numSequencerTransactions++; leafIndex++; } // Now process any subsequent queue transactions. for (uint32 j = 0; j < curContext.numSubsequentQueueTransactions; j++) { require( nextQueueIndex < queueLength, "Not enough queued transactions to append." ); leaves[leafIndex] = _getQueueLeafHash(nextQueueIndex); nextQueueIndex++; leafIndex++; } } _validateFinalBatchContext( curContext, nextQueueIndex, queueLength, queueRef ); require( msg.data.length == nextTransactionPtr, "Not all sequencer transactions were processed." ); require( leafIndex == totalElementsToAppend, "Actual transaction index does not match expected total elements to append." ); // Generate the required metadata that we need to append this batch uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions; uint40 blockTimestamp; uint40 blockNumber; if (curContext.numSubsequentQueueTransactions == 0) { // The last element is a sequencer tx, therefore pull timestamp and block number from // the last context. blockTimestamp = uint40(curContext.timestamp); blockNumber = uint40(curContext.blockNumber); } else { // The last element is a queue tx, therefore pull timestamp and block number from the // queue element. // curContext.numSubsequentQueueTransactions > 0 which means that we've processed at // least one queue element. We increment nextQueueIndex after processing each queue // element, so the index of the last element we processed is nextQueueIndex - 1. Lib_OVMCodec.QueueElement memory lastElement = _getQueueElement( nextQueueIndex - 1, queueRef ); blockTimestamp = lastElement.timestamp; blockNumber = lastElement.blockNumber; } // For efficiency reasons getMerkleRoot modifies the `leaves` argument in place // while calculating the root hash therefore any arguments passed to it must not // be used again afterwards _appendBatch( Lib_MerkleTree.getMerkleRoot(leaves), totalElementsToAppend, numQueuedTransactions, blockTimestamp, blockNumber ); emit SequencerBatchAppended( nextQueueIndex - numQueuedTransactions, numQueuedTransactions, getTotalElements() ); } /** * Verifies whether a transaction is included in the chain. * @param _transaction Transaction to verify. * @param _txChainElement Transaction chain element corresponding to the transaction. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof Inclusion proof for the provided transaction chain element. * @return True if the transaction exists in the CTC, false if not. */ function verifyTransaction( Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) override public view returns ( bool ) { if (_txChainElement.isSequenced == true) { return _verifySequencerTransaction( _transaction, _txChainElement, _batchHeader, _inclusionProof ); } else { return _verifyQueueTransaction( _transaction, _txChainElement.queueIndex, _batchHeader, _inclusionProof ); } } /********************** * Internal Functions * **********************/ /** * Returns the BatchContext located at a particular index. * @param _index The index of the BatchContext * @return The BatchContext at the specified index. */ function _getBatchContext( uint256 _index ) internal pure returns ( BatchContext memory ) { uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE; uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 ctxTimestamp; uint256 ctxBlockNumber; assembly { numSequencedTransactions := shr(232, calldataload(contextPtr)) numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3))) ctxTimestamp := shr(216, calldataload(add(contextPtr, 6))) ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11))) } return BatchContext({ numSequencedTransactions: numSequencedTransactions, numSubsequentQueueTransactions: numSubsequentQueueTransactions, timestamp: ctxTimestamp, blockNumber: ctxBlockNumber }); } /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Index of the next queue element. */ function _getBatchExtraData() internal view returns ( uint40, uint40, uint40, uint40 ) { bytes27 extraData = batches().getGlobalMetadata(); uint40 totalElements; uint40 nextQueueIndex; uint40 lastTimestamp; uint40 lastBlockNumber; // solhint-disable max-line-length assembly { extraData := shr(40, extraData) totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) nextQueueIndex := shr(40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000)) lastTimestamp := shr(80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000)) lastBlockNumber := shr(120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000)) } // solhint-enable max-line-length return ( totalElements, nextQueueIndex, lastTimestamp, lastBlockNumber ); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _nextQueueIndex Index of the next queue element. * @param _timestamp Timestamp for the last batch. * @param _blockNumber Block number of the last batch. * @return Encoded batch context. */ function _makeBatchExtraData( uint40 _totalElements, uint40 _nextQueueIndex, uint40 _timestamp, uint40 _blockNumber ) internal pure returns ( bytes27 ) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _nextQueueIndex)) extraData := or(extraData, shl(80, _timestamp)) extraData := or(extraData, shl(120, _blockNumber)) extraData := shl(40, extraData) } return extraData; } /** * Retrieves the hash of a queue element. * @param _index Index of the queue element to retrieve a hash for. * @return Hash of the queue element. */ function _getQueueLeafHash( uint256 _index ) internal pure returns ( bytes32 ) { return _hashTransactionChainElement( Lib_OVMCodec.TransactionChainElement({ isSequenced: false, queueIndex: _index, timestamp: 0, blockNumber: 0, txData: hex"" }) ); } /** * Gets the queue element at a particular index. * @param _index Index of the queue element to access. * @return _element Queue element at the given index. */ function _getQueueElement( uint256 _index, iOVM_ChainStorageContainer _queueRef ) internal view returns ( Lib_OVMCodec.QueueElement memory _element ) { // The underlying queue data structure stores 2 elements // per insertion, so to get the actual desired queue index // we need to multiply by 2. uint40 trueIndex = uint40(_index * 2); bytes32 transactionHash = _queueRef.get(trueIndex); bytes32 timestampAndBlockNumber = _queueRef.get(trueIndex + 1); uint40 elementTimestamp; uint40 elementBlockNumber; // solhint-disable max-line-length assembly { elementTimestamp := and(timestampAndBlockNumber, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) elementBlockNumber := shr(40, and(timestampAndBlockNumber, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)) } // solhint-enable max-line-length return Lib_OVMCodec.QueueElement({ transactionHash: transactionHash, timestamp: elementTimestamp, blockNumber: elementBlockNumber }); } /** * Retrieves the length of the queue. * @return Length of the queue. */ function _getQueueLength( iOVM_ChainStorageContainer _queueRef ) internal view returns ( uint40 ) { // The underlying queue data structure stores 2 elements // per insertion, so to get the real queue length we need // to divide by 2. return uint40(_queueRef.length() / 2); } /** * Retrieves the hash of a sequencer element. * @param _context Batch context for the given element. * @param _nextTransactionPtr Pointer to the next transaction in the calldata. * @param _txDataLength Length of the transaction item. * @return Hash of the sequencer element. */ function _getSequencerLeafHash( BatchContext memory _context, uint256 _nextTransactionPtr, uint256 _txDataLength, bytes memory _hashMemory ) internal pure returns ( bytes32 ) { // Only allocate more memory if we didn't reserve enough to begin with. if (BYTES_TILL_TX_DATA + _txDataLength > _hashMemory.length) { _hashMemory = new bytes(BYTES_TILL_TX_DATA + _txDataLength); } uint256 ctxTimestamp = _context.timestamp; uint256 ctxBlockNumber = _context.blockNumber; bytes32 leafHash; assembly { let chainElementStart := add(_hashMemory, 0x20) // Set the first byte equal to `1` to indicate this is a sequencer chain element. // This distinguishes sequencer ChainElements from queue ChainElements because // all queue ChainElements are ABI encoded and the first byte of ABI encoded // elements is always zero mstore8(chainElementStart, 1) mstore(add(chainElementStart, 1), ctxTimestamp) mstore(add(chainElementStart, 33), ctxBlockNumber) // solhint-disable-next-line max-line-length calldatacopy(add(chainElementStart, BYTES_TILL_TX_DATA), add(_nextTransactionPtr, 3), _txDataLength) leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, _txDataLength)) } return leafHash; } /** * Retrieves the hash of a sequencer element. * @param _txChainElement The chain element which is hashed to calculate the leaf. * @return Hash of the sequencer element. */ function _getSequencerLeafHash( Lib_OVMCodec.TransactionChainElement memory _txChainElement ) internal view returns( bytes32 ) { bytes memory txData = _txChainElement.txData; uint256 txDataLength = _txChainElement.txData.length; bytes memory chainElement = new bytes(BYTES_TILL_TX_DATA + txDataLength); uint256 ctxTimestamp = _txChainElement.timestamp; uint256 ctxBlockNumber = _txChainElement.blockNumber; bytes32 leafHash; assembly { let chainElementStart := add(chainElement, 0x20) // Set the first byte equal to `1` to indicate this is a sequencer chain element. // This distinguishes sequencer ChainElements from queue ChainElements because // all queue ChainElements are ABI encoded and the first byte of ABI encoded // elements is always zero mstore8(chainElementStart, 1) mstore(add(chainElementStart, 1), ctxTimestamp) mstore(add(chainElementStart, 33), ctxBlockNumber) // solhint-disable-next-line max-line-length pop(staticcall(gas(), 0x04, add(txData, 0x20), txDataLength, add(chainElementStart, BYTES_TILL_TX_DATA), txDataLength)) leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, txDataLength)) } return leafHash; } /** * Inserts a batch into the chain of batches. * @param _transactionRoot Root of the transaction tree for this batch. * @param _batchSize Number of elements in the batch. * @param _numQueuedTransactions Number of queue transactions in the batch. * @param _timestamp The latest batch timestamp. * @param _blockNumber The latest batch blockNumber. */ function _appendBatch( bytes32 _transactionRoot, uint256 _batchSize, uint256 _numQueuedTransactions, uint40 _timestamp, uint40 _blockNumber ) internal { iOVM_ChainStorageContainer batchesRef = batches(); (uint40 totalElements, uint40 nextQueueIndex,,) = _getBatchExtraData(); Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({ batchIndex: batchesRef.length(), batchRoot: _transactionRoot, batchSize: _batchSize, prevTotalElements: totalElements, extraData: hex"" }); emit TransactionBatchAppended( header.batchIndex, header.batchRoot, header.batchSize, header.prevTotalElements, header.extraData ); bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header); bytes27 latestBatchContext = _makeBatchExtraData( totalElements + uint40(header.batchSize), nextQueueIndex + uint40(_numQueuedTransactions), _timestamp, _blockNumber ); batchesRef.push(batchHeaderHash, latestBatchContext); } /** * Checks that the first batch context in a sequencer submission is valid * @param _firstContext The batch context to validate. */ function _validateFirstBatchContext( BatchContext memory _firstContext ) internal view { // If there are existing elements, this batch must have the same context // or a later timestamp and block number. if (getTotalElements() > 0) { (,, uint40 lastTimestamp, uint40 lastBlockNumber) = _getBatchExtraData(); require( _firstContext.blockNumber >= lastBlockNumber, "Context block number is lower than last submitted." ); require( _firstContext.timestamp >= lastTimestamp, "Context timestamp is lower than last submitted." ); } // Sequencer cannot submit contexts which are more than the force inclusion period old. require( _firstContext.timestamp + forceInclusionPeriodSeconds >= block.timestamp, "Context timestamp too far in the past." ); require( _firstContext.blockNumber + forceInclusionPeriodBlocks >= block.number, "Context block number too far in the past." ); } /** * Checks that a given batch context has a time context which is below a given que element * @param _context The batch context to validate has values lower. * @param _queueIndex Index of the queue element we are validating came later than the context. * @param _queueRef The storage container for the queue. */ function _validateContextBeforeEnqueue( BatchContext memory _context, uint40 _queueIndex, iOVM_ChainStorageContainer _queueRef ) internal view { Lib_OVMCodec.QueueElement memory nextQueueElement = _getQueueElement( _queueIndex, _queueRef ); // If the force inclusion period has passed for an enqueued transaction, it MUST be the // next chain element. require( block.timestamp < nextQueueElement.timestamp + forceInclusionPeriodSeconds, // solhint-disable-next-line max-line-length "Previously enqueued batches have expired and must be appended before a new sequencer batch." ); // Just like sequencer transaction times must be increasing relative to each other, // We also require that they be increasing relative to any interspersed queue elements. require( _context.timestamp <= nextQueueElement.timestamp, "Sequencer transaction timestamp exceeds that of next queue element." ); require( _context.blockNumber <= nextQueueElement.blockNumber, "Sequencer transaction blockNumber exceeds that of next queue element." ); } /** * Checks that a given batch context is valid based on its previous context, and the next queue * elemtent. * @param _prevContext The previously validated batch context. * @param _nextContext The batch context to validate with this call. * @param _nextQueueIndex Index of the next queue element to process for the _nextContext's * subsequentQueueElements. * @param _queueRef The storage container for the queue. */ function _validateNextBatchContext( BatchContext memory _prevContext, BatchContext memory _nextContext, uint40 _nextQueueIndex, iOVM_ChainStorageContainer _queueRef ) internal view { // All sequencer transactions' times must be greater than or equal to the previous ones. require( _nextContext.timestamp >= _prevContext.timestamp, "Context timestamp values must monotonically increase." ); require( _nextContext.blockNumber >= _prevContext.blockNumber, "Context blockNumber values must monotonically increase." ); // If there is going to be a queue element pulled in from this context: if (_nextContext.numSubsequentQueueTransactions > 0) { _validateContextBeforeEnqueue( _nextContext, _nextQueueIndex, _queueRef ); } } /** * Checks that the final batch context in a sequencer submission is valid. * @param _finalContext The batch context to validate. * @param _queueLength The length of the queue at the start of the batchAppend call. * @param _nextQueueIndex The next element in the queue that will be pulled into the CTC. * @param _queueRef The storage container for the queue. */ function _validateFinalBatchContext( BatchContext memory _finalContext, uint40 _nextQueueIndex, uint40 _queueLength, iOVM_ChainStorageContainer _queueRef ) internal view { // If the queue is not now empty, check the mononoticity of whatever the next batch that // will come in is. if (_queueLength - _nextQueueIndex > 0 && _finalContext.numSubsequentQueueTransactions == 0) { _validateContextBeforeEnqueue( _finalContext, _nextQueueIndex, _queueRef ); } // Batches cannot be added from the future, or subsequent enqueue() contexts would violate // monotonicity. require(_finalContext.timestamp <= block.timestamp, "Context timestamp is from the future."); require(_finalContext.blockNumber <= block.number, "Context block number is from the future."); } /** * Hashes a transaction chain element. * @param _element Chain element to hash. * @return Hash of the chain element. */ function _hashTransactionChainElement( Lib_OVMCodec.TransactionChainElement memory _element ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _element.isSequenced, _element.queueIndex, _element.timestamp, _element.blockNumber, _element.txData ) ); } /** * Verifies a sequencer transaction, returning true if it was indeed included in the CTC * @param _transaction The transaction we are verifying inclusion of. * @param _txChainElement The chain element that the transaction is claimed to be a part of. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof An inclusion proof into the CTC at a particular index. * @return True if the transaction was included in the specified location, else false. */ function _verifySequencerTransaction( Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) internal view returns ( bool ) { OVM_ExecutionManager ovmExecutionManager = OVM_ExecutionManager(resolve("OVM_ExecutionManager")); uint256 gasLimit = ovmExecutionManager.getMaxTransactionGasLimit(); bytes32 leafHash = _getSequencerLeafHash(_txChainElement); require( _verifyElement( leafHash, _batchHeader, _inclusionProof ), "Invalid Sequencer transaction inclusion proof." ); require( _transaction.blockNumber == _txChainElement.blockNumber && _transaction.timestamp == _txChainElement.timestamp && _transaction.entrypoint == resolve("OVM_DecompressionPrecompileAddress") && _transaction.gasLimit == gasLimit && _transaction.l1TxOrigin == address(0) && _transaction.l1QueueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE && keccak256(_transaction.data) == keccak256(_txChainElement.txData), "Invalid Sequencer transaction." ); return true; } /** * Verifies a queue transaction, returning true if it was indeed included in the CTC * @param _transaction The transaction we are verifying inclusion of. * @param _queueIndex The queueIndex of the queued transaction. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionProof An inclusion proof into the CTC at a particular index (should point to * queue tx). * @return True if the transaction was included in the specified location, else false. */ function _verifyQueueTransaction( Lib_OVMCodec.Transaction memory _transaction, uint256 _queueIndex, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) internal view returns ( bool ) { bytes32 leafHash = _getQueueLeafHash(_queueIndex); require( _verifyElement( leafHash, _batchHeader, _inclusionProof ), "Invalid Queue transaction inclusion proof." ); bytes32 transactionHash = keccak256( abi.encode( _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ) ); Lib_OVMCodec.QueueElement memory el = getQueueElement(_queueIndex); require( el.transactionHash == transactionHash && el.timestamp == _transaction.timestamp && el.blockNumber == _transaction.blockNumber, "Invalid Queue transaction." ); return true; } /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function _verifyElement( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) internal view returns ( bool ) { require( Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(uint32(_batchHeader.batchIndex)), "Invalid batch header." ); require( Lib_MerkleTree.verify( _batchHeader.batchRoot, _element, _proof.index, _proof.siblings, _batchHeader.batchSize ), "Invalid inclusion proof." ); return true; } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol"; import { Lib_ErrorUtils } from "../../libraries/utils/Lib_ErrorUtils.sol"; import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol"; /* Interface Imports */ import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol"; /* Contract Imports */ import { OVM_DeployerWhitelist } from "../predeploys/OVM_DeployerWhitelist.sol"; /* External Imports */ import { Math } from "@openzeppelin/contracts/math/Math.sol"; /** * @title OVM_ExecutionManager * @dev The Execution Manager (EM) is the core of our OVM implementation, and provides a sandboxed * environment allowing us to execute OVM transactions deterministically on either Layer 1 or * Layer 2. * The EM's run() function is the first function called during the execution of any * transaction on L2. * For each context-dependent EVM operation the EM has a function which implements a corresponding * OVM operation, which will read state from the State Manager contract. * The EM relies on the Safety Checker to verify that code deployed to Layer 2 does not contain any * context-dependent operations. * * Compiler used: solc * Runtime target: EVM */ contract OVM_ExecutionManager is iOVM_ExecutionManager, Lib_AddressResolver { /******************************** * External Contract References * ********************************/ iOVM_SafetyChecker internal ovmSafetyChecker; iOVM_StateManager internal ovmStateManager; /******************************* * Execution Context Variables * *******************************/ GasMeterConfig internal gasMeterConfig; GlobalContext internal globalContext; TransactionContext internal transactionContext; MessageContext internal messageContext; TransactionRecord internal transactionRecord; MessageRecord internal messageRecord; /************************** * Gas Metering Constants * **************************/ address constant GAS_METADATA_ADDRESS = 0x06a506A506a506A506a506a506A506A506A506A5; uint256 constant NUISANCE_GAS_SLOAD = 20000; uint256 constant NUISANCE_GAS_SSTORE = 20000; uint256 constant MIN_NUISANCE_GAS_PER_CONTRACT = 30000; uint256 constant NUISANCE_GAS_PER_CONTRACT_BYTE = 100; uint256 constant MIN_GAS_FOR_INVALID_STATE_ACCESS = 30000; /************************** * Native Value Constants * **************************/ // Public so we can access and make assertions in integration tests. uint256 public constant CALL_WITH_VALUE_INTRINSIC_GAS = 90000; /************************** * Default Context Values * **************************/ uint256 constant DEFAULT_UINT256 = 0xdefa017defa017defa017defa017defa017defa017defa017defa017defa017d; address constant DEFAULT_ADDRESS = 0xdEfa017defA017DeFA017DEfa017DeFA017DeFa0; /************************************* * Container Contract Address Prefix * *************************************/ /** * @dev The Execution Manager and State Manager each have this 30 byte prefix, * and are uncallable. */ address constant CONTAINER_CONTRACT_PREFIX = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, GasMeterConfig memory _gasMeterConfig, GlobalContext memory _globalContext ) Lib_AddressResolver(_libAddressManager) { ovmSafetyChecker = iOVM_SafetyChecker(resolve("OVM_SafetyChecker")); gasMeterConfig = _gasMeterConfig; globalContext = _globalContext; _resetContext(); } /********************** * Function Modifiers * **********************/ /** * Applies dynamically-sized refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of the ovmOPCODE is fixed. * @param _cost Desired gas cost for the function after the refund. */ modifier netGasCost( uint256 _cost ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund everything *except* the specified cost. if (_cost < gasUsed) { transactionRecord.ovmGasRefund += gasUsed - _cost; } } /** * Applies a fixed-size gas refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of an ovmOPCODE can be lowered. * @param _discount Amount of gas cost to refund for the ovmOPCODE. */ modifier fixedGasDiscount( uint256 _discount ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund the specified _discount, unless this risks underflow. if (_discount < gasUsed) { transactionRecord.ovmGasRefund += _discount; } else { // refund all we can without risking underflow. transactionRecord.ovmGasRefund += gasUsed; } } /** * Makes sure we're not inside a static context. */ modifier notStatic() { if (messageContext.isStatic == true) { _revertWithFlag(RevertFlag.STATIC_VIOLATION); } _; } /************************************ * Transaction Execution Entrypoint * ************************************/ /** * Starts the execution of a transaction via the OVM_ExecutionManager. * @param _transaction Transaction data to be executed. * @param _ovmStateManager iOVM_StateManager implementation providing account state. */ function run( Lib_OVMCodec.Transaction memory _transaction, address _ovmStateManager ) override external returns ( bytes memory ) { // Make sure that run() is not re-enterable. This condition should always be satisfied // Once run has been called once, due to the behavior of _isValidInput(). if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return bytes(""); } // Store our OVM_StateManager instance (significantly easier than attempting to pass the // address around in calldata). ovmStateManager = iOVM_StateManager(_ovmStateManager); // Make sure this function can't be called by anyone except the owner of the // OVM_StateManager (expected to be an OVM_StateTransitioner). We can revert here because // this would make the `run` itself invalid. require( // This method may return false during fraud proofs, but always returns true in // L2 nodes' State Manager precompile. ovmStateManager.isAuthenticated(msg.sender), "Only authenticated addresses in ovmStateManager can call this function" ); // Initialize the execution context, must be initialized before we perform any gas metering // or we'll throw a nuisance gas error. _initContext(_transaction); // TEMPORARY: Gas metering is disabled for minnet. // // Check whether we need to start a new epoch, do so if necessary. // _checkNeedsNewEpoch(_transaction.timestamp); // Make sure the transaction's gas limit is valid. We don't revert here because we reserve // reverts for INVALID_STATE_ACCESS. if (_isValidInput(_transaction) == false) { _resetContext(); return bytes(""); } // TEMPORARY: Gas metering is disabled for minnet. // // Check gas right before the call to get total gas consumed by OVM transaction. // uint256 gasProvided = gasleft(); // Run the transaction, make sure to meter the gas usage. (, bytes memory returndata) = ovmCALL( _transaction.gasLimit - gasMeterConfig.minTransactionGasLimit, _transaction.entrypoint, 0, _transaction.data ); // TEMPORARY: Gas metering is disabled for minnet. // // Update the cumulative gas based on the amount of gas used. // uint256 gasUsed = gasProvided - gasleft(); // _updateCumulativeGas(gasUsed, _transaction.l1QueueOrigin); // Wipe the execution context. _resetContext(); return returndata; } /****************************** * Opcodes: Execution Context * ******************************/ /** * @notice Overrides CALLER. * @return _CALLER Address of the CALLER within the current message context. */ function ovmCALLER() override external view returns ( address _CALLER ) { return messageContext.ovmCALLER; } /** * @notice Overrides ADDRESS. * @return _ADDRESS Active ADDRESS within the current message context. */ function ovmADDRESS() override public view returns ( address _ADDRESS ) { return messageContext.ovmADDRESS; } /** * @notice Overrides CALLVALUE. * @return _CALLVALUE Value sent along with the call according to the current message context. */ function ovmCALLVALUE() override public view returns ( uint256 _CALLVALUE ) { return messageContext.ovmCALLVALUE; } /** * @notice Overrides TIMESTAMP. * @return _TIMESTAMP Value of the TIMESTAMP within the transaction context. */ function ovmTIMESTAMP() override external view returns ( uint256 _TIMESTAMP ) { return transactionContext.ovmTIMESTAMP; } /** * @notice Overrides NUMBER. * @return _NUMBER Value of the NUMBER within the transaction context. */ function ovmNUMBER() override external view returns ( uint256 _NUMBER ) { return transactionContext.ovmNUMBER; } /** * @notice Overrides GASLIMIT. * @return _GASLIMIT Value of the block's GASLIMIT within the transaction context. */ function ovmGASLIMIT() override external view returns ( uint256 _GASLIMIT ) { return transactionContext.ovmGASLIMIT; } /** * @notice Overrides CHAINID. * @return _CHAINID Value of the chain's CHAINID within the global context. */ function ovmCHAINID() override external view returns ( uint256 _CHAINID ) { return globalContext.ovmCHAINID; } /********************************* * Opcodes: L2 Execution Context * *********************************/ /** * @notice Specifies from which source (Sequencer or Queue) this transaction originated from. * @return _queueOrigin Enum indicating the ovmL1QUEUEORIGIN within the current message context. */ function ovmL1QUEUEORIGIN() override external view returns ( Lib_OVMCodec.QueueOrigin _queueOrigin ) { return transactionContext.ovmL1QUEUEORIGIN; } /** * @notice Specifies which L1 account, if any, sent this transaction by calling enqueue(). * @return _l1TxOrigin Address of the account which sent the tx into L2 from L1. */ function ovmL1TXORIGIN() override external view returns ( address _l1TxOrigin ) { return transactionContext.ovmL1TXORIGIN; } /******************** * Opcodes: Halting * ********************/ /** * @notice Overrides REVERT. * @param _data Bytes data to pass along with the REVERT. */ function ovmREVERT( bytes memory _data ) override public { _revertWithFlag(RevertFlag.INTENTIONAL_REVERT, _data); } /****************************** * Opcodes: Contract Creation * ******************************/ /** * @notice Overrides CREATE. * @param _bytecode Code to be used to CREATE a new contract. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE( bytes memory _bytecode ) override public notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE address. address contractAddress = Lib_EthUtils.getAddressForCREATE( creator, _getAccountNonce(creator) ); return _createContract( contractAddress, _bytecode, MessageType.ovmCREATE ); } /** * @notice Overrides CREATE2. * @param _bytecode Code to be used to CREATE2 a new contract. * @param _salt Value used to determine the contract's address. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE2( bytes memory _bytecode, bytes32 _salt ) override external notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE2 address. address contractAddress = Lib_EthUtils.getAddressForCREATE2( creator, _bytecode, _salt ); return _createContract( contractAddress, _bytecode, MessageType.ovmCREATE2 ); } /******************************* * Account Abstraction Opcodes * ******************************/ /** * Retrieves the nonce of the current ovmADDRESS. * @return _nonce Nonce of the current contract. */ function ovmGETNONCE() override external returns ( uint256 _nonce ) { return _getAccountNonce(ovmADDRESS()); } /** * Bumps the nonce of the current ovmADDRESS by one. */ function ovmINCREMENTNONCE() override external notStatic { address account = ovmADDRESS(); uint256 nonce = _getAccountNonce(account); // Prevent overflow. if (nonce + 1 > nonce) { _setAccountNonce(account, nonce + 1); } } /** * Creates a new EOA contract account, for account abstraction. * @dev Essentially functions like ovmCREATE or ovmCREATE2, but we can bypass a lot of checks * because the contract we're creating is trusted (no need to do safety checking or to * handle unexpected reverts). Doesn't need to return an address because the address is * assumed to be the user's actual address. * @param _messageHash Hash of a message signed by some user, for verification. * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) override public notStatic { // Recover the EOA address from the message hash and signature parameters. Since we do the // hashing in advance, we don't have handle different message hashing schemes. Even if this // function were to return the wrong address (rather than explicitly returning the zero // address), the rest of the transaction would simply fail (since there's no EOA account to // actually execute the transaction). address eoa = ecrecover( _messageHash, _v + 27, _r, _s ); // Invalid signature is a case we proactively handle with a revert. We could alternatively // have this function return a `success` boolean, but this is just easier. if (eoa == address(0)) { ovmREVERT(bytes("Signature provided for EOA contract creation is invalid.")); } // If the user already has an EOA account, then there's no need to perform this operation. if (_hasEmptyAccount(eoa) == false) { return; } // We always need to initialize the contract with the default account values. _initPendingAccount(eoa); // Temporarily set the current address so it's easier to access on L2. address prevADDRESS = messageContext.ovmADDRESS; messageContext.ovmADDRESS = eoa; // Creates a duplicate of the OVM_ProxyEOA located at 0x42....09. Uses the following // "magic" prefix to deploy an exact copy of the code: // PUSH1 0x0D # size of this prefix in bytes // CODESIZE // SUB # subtract prefix size from codesize // DUP1 // PUSH1 0x0D // PUSH1 0x00 // CODECOPY # copy everything after prefix into memory at pos 0 // PUSH1 0x00 // RETURN # return the copied code address proxyEOA = Lib_EthUtils.createContract(abi.encodePacked( hex"600D380380600D6000396000f3", ovmEXTCODECOPY( Lib_PredeployAddresses.PROXY_EOA, 0, ovmEXTCODESIZE(Lib_PredeployAddresses.PROXY_EOA) ) )); // Reset the address now that we're done deploying. messageContext.ovmADDRESS = prevADDRESS; // Commit the account with its final values. _commitPendingAccount( eoa, address(proxyEOA), keccak256(Lib_EthUtils.getCode(address(proxyEOA))) ); _setAccountNonce(eoa, 0); } /********************************* * Opcodes: Contract Interaction * *********************************/ /** * @notice Overrides CALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _value ETH value to pass with the call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata ) override public fixedGasDiscount(100000) returns ( bool _success, bytes memory _returndata ) { // CALL updates the CALLER and ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.ovmCALLVALUE = _value; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmCALL ); } /** * @notice Overrides STATICCALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmSTATICCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(80000) returns ( bool _success, bytes memory _returndata ) { // STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static, // valueless context. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.isStatic = true; nextMessageContext.ovmCALLVALUE = 0; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmSTATICCALL ); } /** * @notice Overrides DELEGATECALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmDELEGATECALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(40000) returns ( bool _success, bytes memory _returndata ) { // DELEGATECALL does not change anything about the message context. MessageContext memory nextMessageContext = messageContext; return _callContract( nextMessageContext, _gasLimit, _address, _calldata, MessageType.ovmDELEGATECALL ); } /** * @notice Legacy ovmCALL function which did not support ETH value; this maintains backwards * compatibility. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public returns( bool _success, bytes memory _returndata ) { // Legacy ovmCALL assumed always-0 value. return ovmCALL( _gasLimit, _address, 0, _calldata ); } /************************************ * Opcodes: Contract Storage Access * ************************************/ /** * @notice Overrides SLOAD. * @param _key 32 byte key of the storage slot to load. * @return _value 32 byte value of the requested storage slot. */ function ovmSLOAD( bytes32 _key ) override external netGasCost(40000) returns ( bytes32 _value ) { // We always SLOAD from the storage of ADDRESS. address contractAddress = ovmADDRESS(); return _getContractStorage( contractAddress, _key ); } /** * @notice Overrides SSTORE. * @param _key 32 byte key of the storage slot to set. * @param _value 32 byte value for the storage slot. */ function ovmSSTORE( bytes32 _key, bytes32 _value ) override external notStatic netGasCost(60000) { // We always SSTORE to the storage of ADDRESS. address contractAddress = ovmADDRESS(); _putContractStorage( contractAddress, _key, _value ); } /********************************* * Opcodes: Contract Code Access * *********************************/ /** * @notice Overrides EXTCODECOPY. * @param _contract Address of the contract to copy code from. * @param _offset Offset in bytes from the start of contract code to copy beyond. * @param _length Total number of bytes to copy from the contract's code. * @return _code Bytes of code copied from the requested contract. */ function ovmEXTCODECOPY( address _contract, uint256 _offset, uint256 _length ) override public returns ( bytes memory _code ) { return Lib_EthUtils.getCode( _getAccountEthAddress(_contract), _offset, _length ); } /** * @notice Overrides EXTCODESIZE. * @param _contract Address of the contract to query the size of. * @return _EXTCODESIZE Size of the requested contract in bytes. */ function ovmEXTCODESIZE( address _contract ) override public returns ( uint256 _EXTCODESIZE ) { return Lib_EthUtils.getCodeSize( _getAccountEthAddress(_contract) ); } /** * @notice Overrides EXTCODEHASH. * @param _contract Address of the contract to query the hash of. * @return _EXTCODEHASH Hash of the requested contract. */ function ovmEXTCODEHASH( address _contract ) override external returns ( bytes32 _EXTCODEHASH ) { return Lib_EthUtils.getCodeHash( _getAccountEthAddress(_contract) ); } /*************************************** * Public Functions: ETH Value Opcodes * ***************************************/ /** * @notice Overrides BALANCE. * NOTE: In the future, this could be optimized to directly invoke EM._getContractStorage(...). * @param _contract Address of the contract to query the OVM_ETH balance of. * @return _BALANCE OVM_ETH balance of the requested contract. */ function ovmBALANCE( address _contract ) override public returns ( uint256 _BALANCE ) { // Easiest way to get the balance is query OVM_ETH as normal. bytes memory balanceOfCalldata = abi.encodeWithSignature( "balanceOf(address)", _contract ); // Static call because this should be a read-only query. (bool success, bytes memory returndata) = ovmSTATICCALL( gasleft(), Lib_PredeployAddresses.OVM_ETH, balanceOfCalldata ); // All balanceOf queries should successfully return a uint, otherwise this must be an OOG. if (!success || returndata.length != 32) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // Return the decoded balance. return abi.decode(returndata, (uint256)); } /** * @notice Overrides SELFBALANCE. * @return _BALANCE OVM_ETH balance of the requesting contract. */ function ovmSELFBALANCE() override external returns ( uint256 _BALANCE ) { return ovmBALANCE(ovmADDRESS()); } /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view override returns ( uint256 _maxTransactionGasLimit ) { return gasMeterConfig.maxTransactionGasLimit; } /******************************************** * Public Functions: Deployment Whitelisting * ********************************************/ /** * Checks whether the given address is on the whitelist to ovmCREATE/ovmCREATE2, * and reverts if not. * @param _deployerAddress Address attempting to deploy a contract. */ function _checkDeployerAllowed( address _deployerAddress ) internal { // From an OVM semantics perspective, this will appear identical to // the deployer ovmCALLing the whitelist. This is fine--in a sense, we are forcing them to. (bool success, bytes memory data) = ovmSTATICCALL( gasleft(), Lib_PredeployAddresses.DEPLOYER_WHITELIST, abi.encodeWithSelector( OVM_DeployerWhitelist.isDeployerAllowed.selector, _deployerAddress ) ); bool isAllowed = abi.decode(data, (bool)); if (!isAllowed || !success) { _revertWithFlag(RevertFlag.CREATOR_NOT_ALLOWED); } } /******************************************** * Internal Functions: Contract Interaction * ********************************************/ /** * Creates a new contract and associates it with some contract address. * @param _contractAddress Address to associate the created contract with. * @param _bytecode Bytecode to be used to create the contract. * @return Final OVM contract address. * @return Revertdata, if and only if the creation threw an exception. */ function _createContract( address _contractAddress, bytes memory _bytecode, MessageType _messageType ) internal returns ( address, bytes memory ) { // We always update the nonce of the creating account, even if the creation fails. _setAccountNonce(ovmADDRESS(), _getAccountNonce(ovmADDRESS()) + 1); // We're stepping into a CREATE or CREATE2, so we need to update ADDRESS to point // to the contract's associated address and CALLER to point to the previous ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = messageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _contractAddress; // Run the common logic which occurs between call-type and create-type messages, // passing in the creation bytecode and `true` to trigger create-specific logic. (bool success, bytes memory data) = _handleExternalMessage( nextMessageContext, gasleft(), _contractAddress, _bytecode, _messageType ); // Yellow paper requires that address returned is zero if the contract deployment fails. return ( success ? _contractAddress : address(0), data ); } /** * Calls the deployed contract associated with a given address. * @param _nextMessageContext Message context to be used for the call. * @param _gasLimit Amount of gas to be passed into this call. * @param _contract OVM address to be called. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function _callContract( MessageContext memory _nextMessageContext, uint256 _gasLimit, address _contract, bytes memory _calldata, MessageType _messageType ) internal returns ( bool _success, bytes memory _returndata ) { // We reserve addresses of the form 0xdeaddeaddead...NNNN for the container contracts in L2 // geth. So, we block calls to these addresses since they are not safe to run as an OVM // contract itself. if ( (uint256(_contract) & uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000)) == uint256(CONTAINER_CONTRACT_PREFIX) ) { // solhint-disable-next-line max-line-length // EVM does not return data in the success case, see: https://github.com/ethereum/go-ethereum/blob/aae7660410f0ef90279e14afaaf2f429fdc2a186/core/vm/instructions.go#L600-L604 return (true, hex''); } // Both 0x0000... and the EVM precompiles have the same address on L1 and L2 --> // no trie lookup needed. address codeContractAddress = uint(_contract) < 100 ? _contract : _getAccountEthAddress(_contract); return _handleExternalMessage( _nextMessageContext, _gasLimit, codeContractAddress, _calldata, _messageType ); } /** * Handles all interactions which involve the execution manager calling out to untrusted code * (both calls and creates). Ensures that OVM-related measures are enforced, including L2 gas * refunds, nuisance gas, and flagged reversions. * * @param _nextMessageContext Message context to be used for the external message. * @param _gasLimit Amount of gas to be passed into this message. NOTE: this argument is * overwritten in some cases to avoid stack-too-deep. * @param _contract OVM address being called or deployed to * @param _data Data for the message (either calldata or creation code) * @param _messageType What type of ovmOPCODE this message corresponds to. * @return Whether or not the message (either a call or deployment) succeeded. * @return Data returned by the message. */ function _handleExternalMessage( MessageContext memory _nextMessageContext, // NOTE: this argument is overwritten in some cases to avoid stack-too-deep. uint256 _gasLimit, address _contract, bytes memory _data, MessageType _messageType ) internal returns ( bool, bytes memory ) { uint256 messageValue = _nextMessageContext.ovmCALLVALUE; // If there is value in this message, we need to transfer the ETH over before switching // contexts. if ( messageValue > 0 && _isValueType(_messageType) ) { // Handle out-of-intrinsic gas consistent with EVM behavior -- the subcall "appears to // revert" if we don't have enough gas to transfer the ETH. // Similar to dynamic gas cost of value exceeding gas here: // solhint-disable-next-line max-line-length // https://github.com/ethereum/go-ethereum/blob/c503f98f6d5e80e079c1d8a3601d188af2a899da/core/vm/interpreter.go#L268-L273 if (gasleft() < CALL_WITH_VALUE_INTRINSIC_GAS) { return (false, hex""); } // If there *is* enough gas to transfer ETH, then we need to make sure this amount of // gas is reserved (i.e. not given to the _contract.call below) to guarantee that // _handleExternalMessage can't run out of gas. In particular, in the event that // the call fails, we will need to transfer the ETH back to the sender. // Taking the lesser of _gasLimit and gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS // guarantees that the second _attemptForcedEthTransfer below, if needed, always has // enough gas to succeed. _gasLimit = Math.min( _gasLimit, gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS // Cannot overflow due to the above check. ); // Now transfer the value of the call. // The target is interpreted to be the next message's ovmADDRESS account. bool transferredOvmEth = _attemptForcedEthTransfer( _nextMessageContext.ovmADDRESS, messageValue ); // If the ETH transfer fails (should only be possible in the case of insufficient // balance), then treat this as a revert. This mirrors EVM behavior, see // solhint-disable-next-line max-line-length // https://github.com/ethereum/go-ethereum/blob/2dee31930c9977af2a9fcb518fb9838aa609a7cf/core/vm/evm.go#L298 if (!transferredOvmEth) { return (false, hex""); } } // We need to switch over to our next message context for the duration of this call. MessageContext memory prevMessageContext = messageContext; _switchMessageContext(prevMessageContext, _nextMessageContext); // Nuisance gas is a system used to bound the ability for an attacker to make fraud proofs // expensive by touching a lot of different accounts or storage slots. Since most contracts // only use a few storage slots during any given transaction, this shouldn't be a limiting // factor. uint256 prevNuisanceGasLeft = messageRecord.nuisanceGasLeft; uint256 nuisanceGasLimit = _getNuisanceGasLimit(_gasLimit); messageRecord.nuisanceGasLeft = nuisanceGasLimit; // Make the call and make sure to pass in the gas limit. Another instance of hidden // complexity. `_contract` is guaranteed to be a safe contract, meaning its return/revert // behavior can be controlled. In particular, we enforce that flags are passed through // revert data as to retrieve execution metadata that would normally be reverted out of // existence. bool success; bytes memory returndata; if (_isCreateType(_messageType)) { // safeCREATE() is a function which replicates a CREATE message, but uses return values // Which match that of CALL (i.e. bool, bytes). This allows many security checks to be // to be shared between untrusted call and create call frames. (success, returndata) = address(this).call{gas: _gasLimit}( abi.encodeWithSelector( this.safeCREATE.selector, _data, _contract ) ); } else { (success, returndata) = _contract.call{gas: _gasLimit}(_data); } // If the message threw an exception, its value should be returned back to the sender. // So, we force it back, BEFORE returning the messageContext to the previous addresses. // This operation is part of the reason we "reserved the intrinsic gas" above. if ( messageValue > 0 && _isValueType(_messageType) && !success ) { bool transferredOvmEth = _attemptForcedEthTransfer( prevMessageContext.ovmADDRESS, messageValue ); // Since we transferred it in above and the call reverted, the transfer back should // always pass. This code path should NEVER be triggered since we sent `messageValue` // worth of OVM_ETH into the target and reserved sufficient gas to execute the transfer, // but in case there is some edge case which has been missed, we revert the entire frame // (and its parent) to make sure the ETH gets sent back. if (!transferredOvmEth) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } } // Switch back to the original message context now that we're out of the call and all // OVM_ETH is in the right place. _switchMessageContext(_nextMessageContext, prevMessageContext); // Assuming there were no reverts, the message record should be accurate here. We'll update // this value in the case of a revert. uint256 nuisanceGasLeft = messageRecord.nuisanceGasLeft; // Reverts at this point are completely OK, but we need to make a few updates based on the // information passed through the revert. if (success == false) { ( RevertFlag flag, uint256 nuisanceGasLeftPostRevert, uint256 ovmGasRefund, bytes memory returndataFromFlag ) = _decodeRevertData(returndata); // INVALID_STATE_ACCESS is the only flag that triggers an immediate abort of the // parent EVM message. This behavior is necessary because INVALID_STATE_ACCESS must // halt any further transaction execution that could impact the execution result. if (flag == RevertFlag.INVALID_STATE_ACCESS) { _revertWithFlag(flag); } // INTENTIONAL_REVERT, UNSAFE_BYTECODE, STATIC_VIOLATION, and CREATOR_NOT_ALLOWED aren't // dependent on the input state, so we can just handle them like standard reverts. // Our only change here is to record the gas refund reported by the call (enforced by // safety checking). if ( flag == RevertFlag.INTENTIONAL_REVERT || flag == RevertFlag.UNSAFE_BYTECODE || flag == RevertFlag.STATIC_VIOLATION || flag == RevertFlag.CREATOR_NOT_ALLOWED ) { transactionRecord.ovmGasRefund = ovmGasRefund; } // INTENTIONAL_REVERT needs to pass up the user-provided return data encoded into the // flag, *not* the full encoded flag. Additionally, we surface custom error messages // to developers in the case of unsafe creations for improved devex. // All other revert types return no data. if ( flag == RevertFlag.INTENTIONAL_REVERT || flag == RevertFlag.UNSAFE_BYTECODE ) { returndata = returndataFromFlag; } else { returndata = hex''; } // Reverts mean we need to use up whatever "nuisance gas" was used by the call. // EXCEEDS_NUISANCE_GAS explicitly reduces the remaining nuisance gas for this message // to zero. OUT_OF_GAS is a "pseudo" flag given that messages return no data when they // run out of gas, so we have to treat this like EXCEEDS_NUISANCE_GAS. All other flags // will simply pass up the remaining nuisance gas. nuisanceGasLeft = nuisanceGasLeftPostRevert; } // We need to reset the nuisance gas back to its original value minus the amount used here. messageRecord.nuisanceGasLeft = prevNuisanceGasLeft - (nuisanceGasLimit - nuisanceGasLeft); return ( success, returndata ); } /** * Handles the creation-specific safety measures required for OVM contract deployment. * This function sanitizes the return types for creation messages to match calls (bool, bytes), * by being an external function which the EM can call, that mimics the success/fail case of the * CREATE. * This allows for consistent handling of both types of messages in _handleExternalMessage(). * Having this step occur as a separate call frame also allows us to easily revert the * contract deployment in the event that the code is unsafe. * * @param _creationCode Code to pass into CREATE for deployment. * @param _address OVM address being deployed to. */ function safeCREATE( bytes memory _creationCode, address _address ) external { // The only way this should callable is from within _createContract(), // and it should DEFINITELY not be callable by a non-EM code contract. if (msg.sender != address(this)) { return; } // Check that there is not already code at this address. if (_hasEmptyAccount(_address) == false) { // Note: in the EVM, this case burns all allotted gas. For improved // developer experience, we do return the remaining gas. _revertWithFlag( RevertFlag.CREATE_COLLISION ); } // Check the creation bytecode against the OVM_SafetyChecker. if (ovmSafetyChecker.isBytecodeSafe(_creationCode) == false) { // Note: in the EVM, this case burns all allotted gas. For improved // developer experience, we do return the remaining gas. _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, // solhint-disable-next-line max-line-length Lib_ErrorUtils.encodeRevertString("Contract creation code contains unsafe opcodes. Did you use the right compiler or pass an unsafe constructor argument?") ); } // We always need to initialize the contract with the default account values. _initPendingAccount(_address); // Actually execute the EVM create message. // NOTE: The inline assembly below means we can NOT make any evm calls between here and then address ethAddress = Lib_EthUtils.createContract(_creationCode); if (ethAddress == address(0)) { // If the creation fails, the EVM lets us grab its revert data. This may contain a // revert flag to be used above in _handleExternalMessage, so we pass the revert data // back up unmodified. assembly { returndatacopy(0,0,returndatasize()) revert(0, returndatasize()) } } // Again simply checking that the deployed code is safe too. Contracts can generate // arbitrary deployment code, so there's no easy way to analyze this beforehand. bytes memory deployedCode = Lib_EthUtils.getCode(ethAddress); if (ovmSafetyChecker.isBytecodeSafe(deployedCode) == false) { _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, // solhint-disable-next-line max-line-length Lib_ErrorUtils.encodeRevertString("Constructor attempted to deploy unsafe bytecode.") ); } // Contract creation didn't need to be reverted and the bytecode is safe. We finish up by // associating the desired address with the newly created contract's code hash and address. _commitPendingAccount( _address, ethAddress, Lib_EthUtils.getCodeHash(ethAddress) ); } /****************************************** * Internal Functions: Value Manipulation * ******************************************/ /** * Invokes an ovmCALL to OVM_ETH.transfer on behalf of the current ovmADDRESS, allowing us to * force movement of OVM_ETH in correspondence with ETH's native value functionality. * WARNING: this will send on behalf of whatever the messageContext.ovmADDRESS is in storage * at the time of the call. * NOTE: In the future, this could be optimized to directly invoke EM._setContractStorage(...). * @param _to Amount of OVM_ETH to be sent. * @param _value Amount of OVM_ETH to send. * @return _success Whether or not the transfer worked. */ function _attemptForcedEthTransfer( address _to, uint256 _value ) internal returns( bool _success ) { bytes memory transferCalldata = abi.encodeWithSignature( "transfer(address,uint256)", _to, _value ); // OVM_ETH inherits from the UniswapV2ERC20 standard. In this implementation, its return // type is a boolean. However, the implementation always returns true if it does not revert // Thus, success of the call frame is sufficient to infer success of the transfer itself. (bool success, ) = ovmCALL( gasleft(), Lib_PredeployAddresses.OVM_ETH, 0, transferCalldata ); return success; } /****************************************** * Internal Functions: State Manipulation * ******************************************/ /** * Checks whether an account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account exists. */ function _hasAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasAccount(_address); } /** * Checks whether a known empty account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account empty exists. */ function _hasEmptyAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasEmptyAccount(_address); } /** * Sets the nonce of an account. * @param _address Address of the account to modify. * @param _nonce New account nonce. */ function _setAccountNonce( address _address, uint256 _nonce ) internal { _checkAccountChange(_address); ovmStateManager.setAccountNonce(_address, _nonce); } /** * Gets the nonce of an account. * @param _address Address of the account to access. * @return _nonce Nonce of the account. */ function _getAccountNonce( address _address ) internal returns ( uint256 _nonce ) { _checkAccountLoad(_address); return ovmStateManager.getAccountNonce(_address); } /** * Retrieves the Ethereum address of an account. * @param _address Address of the account to access. * @return _ethAddress Corresponding Ethereum address. */ function _getAccountEthAddress( address _address ) internal returns ( address _ethAddress ) { _checkAccountLoad(_address); return ovmStateManager.getAccountEthAddress(_address); } /** * Creates the default account object for the given address. * @param _address Address of the account create. */ function _initPendingAccount( address _address ) internal { // Although it seems like `_checkAccountChange` would be more appropriate here, we don't // actually consider an account "changed" until it's inserted into the state (in this case // by `_commitPendingAccount`). _checkAccountLoad(_address); ovmStateManager.initPendingAccount(_address); } /** * Stores additional relevant data for a new account, thereby "committing" it to the state. * This function is only called during `ovmCREATE` and `ovmCREATE2` after a successful contract * creation. * @param _address Address of the account to commit. * @param _ethAddress Address of the associated deployed contract. * @param _codeHash Hash of the code stored at the address. */ function _commitPendingAccount( address _address, address _ethAddress, bytes32 _codeHash ) internal { _checkAccountChange(_address); ovmStateManager.commitPendingAccount( _address, _ethAddress, _codeHash ); } /** * Retrieves the value of a storage slot. * @param _contract Address of the contract to query. * @param _key 32 byte key of the storage slot. * @return _value 32 byte storage slot value. */ function _getContractStorage( address _contract, bytes32 _key ) internal returns ( bytes32 _value ) { _checkContractStorageLoad(_contract, _key); return ovmStateManager.getContractStorage(_contract, _key); } /** * Sets the value of a storage slot. * @param _contract Address of the contract to modify. * @param _key 32 byte key of the storage slot. * @param _value 32 byte storage slot value. */ function _putContractStorage( address _contract, bytes32 _key, bytes32 _value ) internal { // We don't set storage if the value didn't change. Although this acts as a convenient // optimization, it's also necessary to avoid the case in which a contract with no storage // attempts to store the value "0" at any key. Putting this value (and therefore requiring // that the value be committed into the storage trie after execution) would incorrectly // modify the storage root. if (_getContractStorage(_contract, _key) == _value) { return; } _checkContractStorageChange(_contract, _key); ovmStateManager.putContractStorage(_contract, _key, _value); } /** * Validation whenever a contract needs to be loaded. Checks that the account exists, charges * nuisance gas if the account hasn't been loaded before. * @param _address Address of the account to load. */ function _checkAccountLoad( address _address ) internal { // See `_checkContractStorageLoad` for more information. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // See `_checkContractStorageLoad` for more information. if (ovmStateManager.hasAccount(_address) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the account has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that an account is loaded. ( bool _wasAccountAlreadyLoaded ) = ovmStateManager.testAndSetAccountLoaded(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyLoaded == false) { _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a contract needs to be changed. Checks that the account exists, charges * nuisance gas if the account hasn't been changed before. * @param _address Address of the account to change. */ function _checkAccountChange( address _address ) internal { // Start by checking for a load as we only want to charge nuisance gas proportional to // contract size once. _checkAccountLoad(_address); // Check whether the account has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that an account is changed. ( bool _wasAccountAlreadyChanged ) = ovmStateManager.testAndSetAccountChanged(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyChanged == false) { ovmStateManager.incrementTotalUncommittedAccounts(); _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a slot needs to be loaded. Checks that the account exists, charges * nuisance gas if the slot hasn't been loaded before. * @param _contract Address of the account to load from. * @param _key 32 byte key to load. */ function _checkContractStorageLoad( address _contract, bytes32 _key ) internal { // Another case of hidden complexity. If we didn't enforce this requirement, then a // contract could pass in just enough gas to cause the INVALID_STATE_ACCESS check to fail // on L1 but not on L2. A contract could use this behavior to prevent the // OVM_ExecutionManager from detecting an invalid state access. Reverting with OUT_OF_GAS // allows us to also charge for the full message nuisance gas, because you deserve that for // trying to break the contract in this way. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // We need to make sure that the transaction isn't trying to access storage that hasn't // been provided to the OVM_StateManager. We'll immediately abort if this is the case. // We know that we have enough gas to do this check because of the above test. if (ovmStateManager.hasContractStorage(_contract, _key) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the slot has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that a slot is loaded. ( bool _wasContractStorageAlreadyLoaded ) = ovmStateManager.testAndSetContractStorageLoaded(_contract, _key); // If we hadn't already loaded the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyLoaded == false) { _useNuisanceGas(NUISANCE_GAS_SLOAD); } } /** * Validation whenever a slot needs to be changed. Checks that the account exists, charges * nuisance gas if the slot hasn't been changed before. * @param _contract Address of the account to change. * @param _key 32 byte key to change. */ function _checkContractStorageChange( address _contract, bytes32 _key ) internal { // Start by checking for load to make sure we have the storage slot and that we charge the // "nuisance gas" necessary to prove the storage slot state. _checkContractStorageLoad(_contract, _key); // Check whether the slot has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that a slot is changed. ( bool _wasContractStorageAlreadyChanged ) = ovmStateManager.testAndSetContractStorageChanged(_contract, _key); // If we hadn't already changed the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyChanged == false) { // Changing a storage slot means that we're also going to have to change the // corresponding account, so do an account change check. _checkAccountChange(_contract); ovmStateManager.incrementTotalUncommittedContractStorage(); _useNuisanceGas(NUISANCE_GAS_SSTORE); } } /************************************ * Internal Functions: Revert Logic * ************************************/ /** * Simple encoding for revert data. * @param _flag Flag to revert with. * @param _data Additional user-provided revert data. * @return _revertdata Encoded revert data. */ function _encodeRevertData( RevertFlag _flag, bytes memory _data ) internal view returns ( bytes memory _revertdata ) { // Out of gas and create exceptions will fundamentally return no data, so simulating it // shouldn't either. if ( _flag == RevertFlag.OUT_OF_GAS ) { return bytes(""); } // INVALID_STATE_ACCESS doesn't need to return any data other than the flag. if (_flag == RevertFlag.INVALID_STATE_ACCESS) { return abi.encode( _flag, 0, 0, bytes("") ); } // Just ABI encode the rest of the parameters. return abi.encode( _flag, messageRecord.nuisanceGasLeft, transactionRecord.ovmGasRefund, _data ); } /** * Simple decoding for revert data. * @param _revertdata Revert data to decode. * @return _flag Flag used to revert. * @return _nuisanceGasLeft Amount of nuisance gas unused by the message. * @return _ovmGasRefund Amount of gas refunded during the message. * @return _data Additional user-provided revert data. */ function _decodeRevertData( bytes memory _revertdata ) internal pure returns ( RevertFlag _flag, uint256 _nuisanceGasLeft, uint256 _ovmGasRefund, bytes memory _data ) { // A length of zero means the call ran out of gas, just return empty data. if (_revertdata.length == 0) { return ( RevertFlag.OUT_OF_GAS, 0, 0, bytes("") ); } // ABI decode the incoming data. return abi.decode(_revertdata, (RevertFlag, uint256, uint256, bytes)); } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. * @param _data Additional user-provided data. */ function _revertWithFlag( RevertFlag _flag, bytes memory _data ) internal view { bytes memory revertdata = _encodeRevertData( _flag, _data ); assembly { revert(add(revertdata, 0x20), mload(revertdata)) } } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. */ function _revertWithFlag( RevertFlag _flag ) internal { _revertWithFlag(_flag, bytes("")); } /****************************************** * Internal Functions: Nuisance Gas Logic * ******************************************/ /** * Computes the nuisance gas limit from the gas limit. * @dev This function is currently using a naive implementation whereby the nuisance gas limit * is set to exactly equal the lesser of the gas limit or remaining gas. It's likely that * this implementation is perfectly fine, but we may change this formula later. * @param _gasLimit Gas limit to compute from. * @return _nuisanceGasLimit Computed nuisance gas limit. */ function _getNuisanceGasLimit( uint256 _gasLimit ) internal view returns ( uint256 _nuisanceGasLimit ) { return _gasLimit < gasleft() ? _gasLimit : gasleft(); } /** * Uses a certain amount of nuisance gas. * @param _amount Amount of nuisance gas to use. */ function _useNuisanceGas( uint256 _amount ) internal { // Essentially the same as a standard OUT_OF_GAS, except we also retain a record of the gas // refund to be given at the end of the transaction. if (messageRecord.nuisanceGasLeft < _amount) { _revertWithFlag(RevertFlag.EXCEEDS_NUISANCE_GAS); } messageRecord.nuisanceGasLeft -= _amount; } /************************************ * Internal Functions: Gas Metering * ************************************/ /** * Checks whether a transaction needs to start a new epoch and does so if necessary. * @param _timestamp Transaction timestamp. */ function _checkNeedsNewEpoch( uint256 _timestamp ) internal { if ( _timestamp >= ( _getGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP) + gasMeterConfig.secondsPerEpoch ) ) { _putGasMetadata( GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP, _timestamp ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS ) ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS ) ); } } /** * Validates the input values of a transaction. * @return _valid Whether or not the transaction data is valid. */ function _isValidInput( Lib_OVMCodec.Transaction memory _transaction ) view internal returns ( bool ) { // Prevent reentrancy to run(): // This check prevents calling run with the default ovmNumber. // Combined with the first check in run(): // if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; } // It should be impossible to re-enter since run() returns before any other call frames are // created. Since this value is already being written to storage, we save much gas compared // to using the standard nonReentrant pattern. if (_transaction.blockNumber == DEFAULT_UINT256) { return false; } if (_isValidGasLimit(_transaction.gasLimit, _transaction.l1QueueOrigin) == false) { return false; } return true; } /** * Validates the gas limit for a given transaction. * @param _gasLimit Gas limit provided by the transaction. * param _queueOrigin Queue from which the transaction originated. * @return _valid Whether or not the gas limit is valid. */ function _isValidGasLimit( uint256 _gasLimit, Lib_OVMCodec.QueueOrigin // _queueOrigin ) view internal returns ( bool _valid ) { // Always have to be below the maximum gas limit. if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) { return false; } // Always have to be above the minimum gas limit. if (_gasLimit < gasMeterConfig.minTransactionGasLimit) { return false; } // TEMPORARY: Gas metering is disabled for minnet. return true; // GasMetadataKey cumulativeGasKey; // GasMetadataKey prevEpochGasKey; // if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS; // } else { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS; // } // return ( // ( // _getGasMetadata(cumulativeGasKey) // - _getGasMetadata(prevEpochGasKey) // + _gasLimit // ) < gasMeterConfig.maxGasPerQueuePerEpoch // ); } /** * Updates the cumulative gas after a transaction. * @param _gasUsed Gas used by the transaction. * @param _queueOrigin Queue from which the transaction originated. */ function _updateCumulativeGas( uint256 _gasUsed, Lib_OVMCodec.QueueOrigin _queueOrigin ) internal { GasMetadataKey cumulativeGasKey; if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; } else { cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; } _putGasMetadata( cumulativeGasKey, ( _getGasMetadata(cumulativeGasKey) + gasMeterConfig.minTransactionGasLimit + _gasUsed - transactionRecord.ovmGasRefund ) ); } /** * Retrieves the value of a gas metadata key. * @param _key Gas metadata key to retrieve. * @return _value Value stored at the given key. */ function _getGasMetadata( GasMetadataKey _key ) internal returns ( uint256 _value ) { return uint256(_getContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)) )); } /** * Sets the value of a gas metadata key. * @param _key Gas metadata key to set. * @param _value Value to store at the given key. */ function _putGasMetadata( GasMetadataKey _key, uint256 _value ) internal { _putContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)), bytes32(uint256(_value)) ); } /***************************************** * Internal Functions: Execution Context * *****************************************/ /** * Swaps over to a new message context. * @param _prevMessageContext Context we're switching from. * @param _nextMessageContext Context we're switching to. */ function _switchMessageContext( MessageContext memory _prevMessageContext, MessageContext memory _nextMessageContext ) internal { // These conditionals allow us to avoid unneccessary SSTOREs. However, they do mean that // the current storage value for the messageContext MUST equal the _prevMessageContext // argument, or an SSTORE might be erroneously skipped. if (_prevMessageContext.ovmCALLER != _nextMessageContext.ovmCALLER) { messageContext.ovmCALLER = _nextMessageContext.ovmCALLER; } if (_prevMessageContext.ovmADDRESS != _nextMessageContext.ovmADDRESS) { messageContext.ovmADDRESS = _nextMessageContext.ovmADDRESS; } if (_prevMessageContext.isStatic != _nextMessageContext.isStatic) { messageContext.isStatic = _nextMessageContext.isStatic; } if (_prevMessageContext.ovmCALLVALUE != _nextMessageContext.ovmCALLVALUE) { messageContext.ovmCALLVALUE = _nextMessageContext.ovmCALLVALUE; } } /** * Initializes the execution context. * @param _transaction OVM transaction being executed. */ function _initContext( Lib_OVMCodec.Transaction memory _transaction ) internal { transactionContext.ovmTIMESTAMP = _transaction.timestamp; transactionContext.ovmNUMBER = _transaction.blockNumber; transactionContext.ovmTXGASLIMIT = _transaction.gasLimit; transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin; transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin; transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch; messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit); } /** * Resets the transaction and message context. */ function _resetContext() internal { transactionContext.ovmL1TXORIGIN = DEFAULT_ADDRESS; transactionContext.ovmTIMESTAMP = DEFAULT_UINT256; transactionContext.ovmNUMBER = DEFAULT_UINT256; transactionContext.ovmGASLIMIT = DEFAULT_UINT256; transactionContext.ovmTXGASLIMIT = DEFAULT_UINT256; transactionContext.ovmL1QUEUEORIGIN = Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE; transactionRecord.ovmGasRefund = DEFAULT_UINT256; messageContext.ovmCALLER = DEFAULT_ADDRESS; messageContext.ovmADDRESS = DEFAULT_ADDRESS; messageContext.isStatic = false; messageRecord.nuisanceGasLeft = DEFAULT_UINT256; // Reset the ovmStateManager. ovmStateManager = iOVM_StateManager(address(0)); } /****************************************** * Internal Functions: Message Typechecks * ******************************************/ /** * Returns whether or not the given message type is a CREATE-type. * @param _messageType the message type in question. */ function _isCreateType( MessageType _messageType ) internal pure returns( bool ) { return ( _messageType == MessageType.ovmCREATE || _messageType == MessageType.ovmCREATE2 ); } /** * Returns whether or not the given message type (potentially) requires the transfer of ETH * value along with the message. * @param _messageType the message type in question. */ function _isValueType( MessageType _messageType ) internal pure returns( bool ) { // ovmSTATICCALL and ovmDELEGATECALL types do not accept or transfer value. return ( _messageType == MessageType.ovmCALL || _messageType == MessageType.ovmCREATE || _messageType == MessageType.ovmCREATE2 ); } /***************************** * L2-only Helper Functions * *****************************/ /** * Unreachable helper function for simulating eth_calls with an OVM message context. * This function will throw an exception in all cases other than when used as a custom * entrypoint in L2 Geth to simulate eth_call. * @param _transaction the message transaction to simulate. * @param _from the OVM account the simulated call should be from. * @param _value the amount of ETH value to send. * @param _ovmStateManager the address of the OVM_StateManager precompile in the L2 state. */ function simulateMessage( Lib_OVMCodec.Transaction memory _transaction, address _from, uint256 _value, iOVM_StateManager _ovmStateManager ) external returns ( bytes memory ) { // Prevent this call from having any effect unless in a custom-set VM frame require(msg.sender == address(0)); // Initialize the EM's internal state, ignoring nuisance gas. ovmStateManager = _ovmStateManager; _initContext(_transaction); messageRecord.nuisanceGasLeft = uint(-1); // Set the ovmADDRESS to the _from so that the subsequent call frame "comes from" them. messageContext.ovmADDRESS = _from; // Execute the desired message. bool isCreate = _transaction.entrypoint == address(0); if (isCreate) { (address created, bytes memory revertData) = ovmCREATE(_transaction.data); if (created == address(0)) { return abi.encode(false, revertData); } else { // The eth_call RPC endpoint for to = undefined will return the deployed bytecode // in the success case, differing from standard create messages. return abi.encode(true, Lib_EthUtils.getCode(created)); } } else { (bool success, bytes memory returndata) = ovmCALL( _transaction.gasLimit, _transaction.entrypoint, _value, _transaction.data ); return abi.encode(success, returndata); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_SafetyChecker */ interface iOVM_SafetyChecker { /******************** * Public Functions * ********************/ function isBytecodeSafe(bytes calldata _bytecode) external pure returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_DeployerWhitelist } from "../../iOVM/predeploys/iOVM_DeployerWhitelist.sol"; /** * @title OVM_DeployerWhitelist * @dev The Deployer Whitelist is a temporary predeploy used to provide additional safety during the * initial phases of our mainnet roll out. It is owned by the Optimism team, and defines accounts * which are allowed to deploy contracts on Layer2. The Execution Manager will only allow an * ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_DeployerWhitelist is iOVM_DeployerWhitelist { /********************** * Contract Constants * **********************/ bool public initialized; bool public allowArbitraryDeployment; address override public owner; mapping (address => bool) public whitelist; /********************** * Function Modifiers * **********************/ /** * Blocks functions to anyone except the contract owner. */ modifier onlyOwner() { require( msg.sender == owner, "Function can only be called by the owner of this contract." ); _; } /******************** * Public Functions * ********************/ /** * Initializes the whitelist. * @param _owner Address of the owner for this contract. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function initialize( address _owner, bool _allowArbitraryDeployment ) override external { if (initialized == true) { return; } initialized = true; allowArbitraryDeployment = _allowArbitraryDeployment; owner = _owner; } /** * Adds or removes an address from the deployment whitelist. * @param _deployer Address to update permissions for. * @param _isWhitelisted Whether or not the address is whitelisted. */ function setWhitelistedDeployer( address _deployer, bool _isWhitelisted ) override external onlyOwner { whitelist[_deployer] = _isWhitelisted; } /** * Updates the owner of this contract. * @param _owner Address of the new owner. */ function setOwner( address _owner ) override public onlyOwner { owner = _owner; } /** * Updates the arbitrary deployment flag. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function setAllowArbitraryDeployment( bool _allowArbitraryDeployment ) override public onlyOwner { allowArbitraryDeployment = _allowArbitraryDeployment; } /** * Permanently enables arbitrary contract deployment and deletes the owner. */ function enableArbitraryContractDeployment() override external onlyOwner { setAllowArbitraryDeployment(true); setOwner(address(0)); } /** * Checks whether an address is allowed to deploy contracts. * @param _deployer Address to check. * @return _allowed Whether or not the address can deploy contracts. */ function isDeployerAllowed( address _deployer ) override external returns ( bool ) { return ( initialized == false || allowArbitraryDeployment == true || whitelist[_deployer] ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_DeployerWhitelist */ interface iOVM_DeployerWhitelist { /******************** * Public Functions * ********************/ function initialize(address _owner, bool _allowArbitraryDeployment) external; function owner() external returns (address _owner); function setWhitelistedDeployer(address _deployer, bool _isWhitelisted) external; function setOwner(address _newOwner) external; function setAllowArbitraryDeployment(bool _allowArbitraryDeployment) external; function enableArbitraryContractDeployment() external; function isDeployerAllowed(address _deployer) external returns (bool _allowed); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol"; /** * @title OVM_SafetyChecker * @dev The Safety Checker verifies that contracts deployed on L2 do not contain any * "unsafe" operations. An operation is considered unsafe if it would access state variables which * are specific to the environment (ie. L1 or L2) in which it is executed, as this could be used * to "escape the sandbox" of the OVM, resulting in non-deterministic fraud proofs. * That is, an attacker would be able to "prove fraud" on an honestly applied transaction. * Note that a "safe" contract requires opcodes to appear in a particular pattern; * omission of "unsafe" opcodes is necessary, but not sufficient. * * Compiler used: solc * Runtime target: EVM */ contract OVM_SafetyChecker is iOVM_SafetyChecker { /******************** * Public Functions * ********************/ /** * Returns whether or not all of the provided bytecode is safe. * @param _bytecode The bytecode to safety check. * @return `true` if the bytecode is safe, `false` otherwise. */ function isBytecodeSafe( bytes memory _bytecode ) override external pure returns ( bool ) { // autogenerated by gen_safety_checker_constants.py // number of bytes to skip for each opcode uint256[8] memory opcodeSkippableBytes = [ uint256(0x0001010101010101010101010000000001010101010101010101010101010000), uint256(0x0100000000000000000000000000000000000000010101010101000000010100), uint256(0x0000000000000000000000000000000001010101000000010101010100000000), uint256(0x0203040500000000000000000000000000000000000000000000000000000000), uint256(0x0101010101010101010101010101010101010101010101010101010101010101), uint256(0x0101010101000000000000000000000000000000000000000000000000000000), uint256(0x0000000000000000000000000000000000000000000000000000000000000000), uint256(0x0000000000000000000000000000000000000000000000000000000000000000) ]; // Mask to gate opcode specific cases // solhint-disable-next-line max-line-length uint256 opcodeGateMask = ~uint256(0xffffffffffffffffffffffe000000000fffffffff070ffff9c0ffffec000f001); // Halting opcodes // solhint-disable-next-line max-line-length uint256 opcodeHaltingMask = ~uint256(0x4008000000000000000000000000000000000000004000000000000000000001); // PUSH opcodes uint256 opcodePushMask = ~uint256(0xffffffff000000000000000000000000); uint256 codeLength; uint256 _pc; assembly { _pc := add(_bytecode, 0x20) } codeLength = _pc + _bytecode.length; do { // current opcode: 0x00...0xff uint256 opNum; /* solhint-disable max-line-length */ // inline assembly removes the extra add + bounds check assembly { let word := mload(_pc) //load the next 32 bytes at pc into word // Look up number of bytes to skip from opcodeSkippableBytes and then update indexInWord // E.g. the 02030405 in opcodeSkippableBytes is the number of bytes to skip for PUSH1->4 // We repeat this 6 times, thus we can only skip bytes for up to PUSH4 ((1+4) * 6 = 30 < 32). // If we see an opcode that is listed as 0 skippable bytes e.g. PUSH5, // then we will get stuck on that indexInWord and then opNum will be set to the PUSH5 opcode. let indexInWord := byte(0, mload(add(opcodeSkippableBytes, byte(0, word)))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) _pc := add(_pc, indexInWord) opNum := byte(indexInWord, word) } /* solhint-enable max-line-length */ // + push opcodes // + stop opcodes [STOP(0x00),JUMP(0x56),RETURN(0xf3),INVALID(0xfe)] // + caller opcode CALLER(0x33) // + blacklisted opcodes uint256 opBit = 1 << opNum; if (opBit & opcodeGateMask == 0) { if (opBit & opcodePushMask == 0) { // all pushes are valid opcodes // subsequent bytes are not opcodes. Skip them. _pc += (opNum - 0x5e); // PUSH1 is 0x60, so opNum-0x5f = PUSHed bytes and we // +1 to skip the _pc++; line below in order to save gas ((-0x5f + 1) = -0x5e) continue; } else if (opBit & opcodeHaltingMask == 0) { // STOP or JUMP or RETURN or INVALID (Note: REVERT is blacklisted, so not // included here) // We are now inside unreachable code until we hit a JUMPDEST! do { _pc++; assembly { opNum := byte(0, mload(_pc)) } // encountered a JUMPDEST if (opNum == 0x5b) break; // skip PUSHed bytes // opNum-0x5f = PUSHed bytes (PUSH1 is 0x60) if ((1 << opNum) & opcodePushMask == 0) _pc += (opNum - 0x5f); } while (_pc < codeLength); // opNum is 0x5b, so we don't continue here since the pc++ is fine } else if (opNum == 0x33) { // Caller opcode uint256 firstOps; // next 32 bytes of bytecode uint256 secondOps; // following 32 bytes of bytecode assembly { firstOps := mload(_pc) // 37 bytes total, 5 left over --> 32 - 5 bytes = 27 bytes = 216 bits secondOps := shr(216, mload(add(_pc, 0x20))) } // Call identity precompile // CALLER POP PUSH1 0x00 PUSH1 0x04 GAS CALL // 32 - 8 bytes = 24 bytes = 192 if ((firstOps >> 192) == 0x3350600060045af1) { _pc += 8; // Call EM and abort execution if instructed // CALLER PUSH1 0x00 SWAP1 GAS CALL PC PUSH1 0x0E ADD JUMPI RETURNDATASIZE // PUSH1 0x00 DUP1 RETURNDATACOPY RETURNDATASIZE PUSH1 0x00 REVERT JUMPDEST // RETURNDATASIZE PUSH1 0x01 EQ ISZERO PC PUSH1 0x0a ADD JUMPI PUSH1 0x01 PUSH1 // 0x00 RETURN JUMPDEST // solhint-disable-next-line max-line-length } else if (firstOps == 0x336000905af158600e01573d6000803e3d6000fd5b3d6001141558600a015760 && secondOps == 0x016000f35b) { _pc += 37; } else { return false; } continue; } else { // encountered a non-whitelisted opcode! return false; } } _pc++; } while (_pc < codeLength); return true; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol"; /* Contract Imports */ import { OVM_StateManager } from "./OVM_StateManager.sol"; /** * @title OVM_StateManagerFactory * @dev The State Manager Factory is called by a State Transitioner's init code, to create a new * State Manager for use in the Fraud Verification process. * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateManagerFactory is iOVM_StateManagerFactory { /******************** * Public Functions * ********************/ /** * Creates a new OVM_StateManager * @param _owner Owner of the created contract. * @return New OVM_StateManager instance. */ function create( address _owner ) override public returns ( iOVM_StateManager ) { return new OVM_StateManager(_owner); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; /** * @title OVM_StateManager * @dev The State Manager contract holds all storage values for contracts in the OVM. It can only be * written to by the Execution Manager and State Transitioner. It runs on L1 during the setup and * execution of a fraud proof. * The same logic runs on L2, but has been implemented as a precompile in the L2 go-ethereum client * (see https://github.com/ethereum-optimism/go-ethereum/blob/master/core/vm/ovm_state_manager.go). * * Compiler used: solc * Runtime target: EVM */ contract OVM_StateManager is iOVM_StateManager { /************* * Constants * *************/ bytes32 constant internal EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421; bytes32 constant internal EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; bytes32 constant internal STORAGE_XOR_VALUE = 0xFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEF; /************* * Variables * *************/ address override public owner; address override public ovmExecutionManager; mapping (address => Lib_OVMCodec.Account) internal accounts; mapping (address => mapping (bytes32 => bytes32)) internal contractStorage; mapping (address => mapping (bytes32 => bool)) internal verifiedContractStorage; mapping (bytes32 => ItemState) internal itemStates; uint256 internal totalUncommittedAccounts; uint256 internal totalUncommittedContractStorage; /*************** * Constructor * ***************/ /** * @param _owner Address of the owner of this contract. */ constructor( address _owner ) { owner = _owner; } /********************** * Function Modifiers * **********************/ /** * Simple authentication, this contract should only be accessible to the owner * (which is expected to be the State Transitioner during `PRE_EXECUTION` * or the OVM_ExecutionManager during transaction execution. */ modifier authenticated() { // owner is the State Transitioner require( msg.sender == owner || msg.sender == ovmExecutionManager, "Function can only be called by authenticated addresses" ); _; } /******************** * Public Functions * ********************/ /** * Checks whether a given address is allowed to modify this contract. * @param _address Address to check. * @return Whether or not the address can modify this contract. */ function isAuthenticated( address _address ) override public view returns ( bool ) { return (_address == owner || _address == ovmExecutionManager); } /** * Sets the address of the OVM_ExecutionManager. * @param _ovmExecutionManager Address of the OVM_ExecutionManager. */ function setExecutionManager( address _ovmExecutionManager ) override public authenticated { ovmExecutionManager = _ovmExecutionManager; } /** * Inserts an account into the state. * @param _address Address of the account to insert. * @param _account Account to insert for the given address. */ function putAccount( address _address, Lib_OVMCodec.Account memory _account ) override public authenticated { accounts[_address] = _account; } /** * Marks an account as empty. * @param _address Address of the account to mark. */ function putEmptyAccount( address _address ) override public authenticated { Lib_OVMCodec.Account storage account = accounts[_address]; account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT; account.codeHash = EMPTY_ACCOUNT_CODE_HASH; } /** * Retrieves an account from the state. * @param _address Address of the account to retrieve. * @return Account for the given address. */ function getAccount( address _address ) override public view returns ( Lib_OVMCodec.Account memory ) { return accounts[_address]; } /** * Checks whether the state has a given account. * @param _address Address of the account to check. * @return Whether or not the state has the account. */ function hasAccount( address _address ) override public view returns ( bool ) { return accounts[_address].codeHash != bytes32(0); } /** * Checks whether the state has a given known empty account. * @param _address Address of the account to check. * @return Whether or not the state has the empty account. */ function hasEmptyAccount( address _address ) override public view returns ( bool ) { return ( accounts[_address].codeHash == EMPTY_ACCOUNT_CODE_HASH && accounts[_address].nonce == 0 ); } /** * Sets the nonce of an account. * @param _address Address of the account to modify. * @param _nonce New account nonce. */ function setAccountNonce( address _address, uint256 _nonce ) override public authenticated { accounts[_address].nonce = _nonce; } /** * Gets the nonce of an account. * @param _address Address of the account to access. * @return Nonce of the account. */ function getAccountNonce( address _address ) override public view returns ( uint256 ) { return accounts[_address].nonce; } /** * Retrieves the Ethereum address of an account. * @param _address Address of the account to access. * @return Corresponding Ethereum address. */ function getAccountEthAddress( address _address ) override public view returns ( address ) { return accounts[_address].ethAddress; } /** * Retrieves the storage root of an account. * @param _address Address of the account to access. * @return Corresponding storage root. */ function getAccountStorageRoot( address _address ) override public view returns ( bytes32 ) { return accounts[_address].storageRoot; } /** * Initializes a pending account (during CREATE or CREATE2) with the default values. * @param _address Address of the account to initialize. */ function initPendingAccount( address _address ) override public authenticated { Lib_OVMCodec.Account storage account = accounts[_address]; account.nonce = 1; account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT; account.codeHash = EMPTY_ACCOUNT_CODE_HASH; account.isFresh = true; } /** * Finalizes the creation of a pending account (during CREATE or CREATE2). * @param _address Address of the account to finalize. * @param _ethAddress Address of the account's associated contract on Ethereum. * @param _codeHash Hash of the account's code. */ function commitPendingAccount( address _address, address _ethAddress, bytes32 _codeHash ) override public authenticated { Lib_OVMCodec.Account storage account = accounts[_address]; account.ethAddress = _ethAddress; account.codeHash = _codeHash; } /** * Checks whether an account has already been retrieved, and marks it as retrieved if not. * @param _address Address of the account to check. * @return Whether or not the account was already loaded. */ function testAndSetAccountLoaded( address _address ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_address), ItemState.ITEM_LOADED ); } /** * Checks whether an account has already been modified, and marks it as modified if not. * @param _address Address of the account to check. * @return Whether or not the account was already modified. */ function testAndSetAccountChanged( address _address ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_address), ItemState.ITEM_CHANGED ); } /** * Attempts to mark an account as committed. * @param _address Address of the account to commit. * @return Whether or not the account was committed. */ function commitAccount( address _address ) override public authenticated returns ( bool ) { bytes32 item = _getItemHash(_address); if (itemStates[item] != ItemState.ITEM_CHANGED) { return false; } itemStates[item] = ItemState.ITEM_COMMITTED; totalUncommittedAccounts -= 1; return true; } /** * Increments the total number of uncommitted accounts. */ function incrementTotalUncommittedAccounts() override public authenticated { totalUncommittedAccounts += 1; } /** * Gets the total number of uncommitted accounts. * @return Total uncommitted accounts. */ function getTotalUncommittedAccounts() override public view returns ( uint256 ) { return totalUncommittedAccounts; } /** * Checks whether a given account was changed during execution. * @param _address Address to check. * @return Whether or not the account was changed. */ function wasAccountChanged( address _address ) override public view returns ( bool ) { bytes32 item = _getItemHash(_address); return itemStates[item] >= ItemState.ITEM_CHANGED; } /** * Checks whether a given account was committed after execution. * @param _address Address to check. * @return Whether or not the account was committed. */ function wasAccountCommitted( address _address ) override public view returns ( bool ) { bytes32 item = _getItemHash(_address); return itemStates[item] >= ItemState.ITEM_COMMITTED; } /************************************ * Public Functions: Storage Access * ************************************/ /** * Changes a contract storage slot value. * @param _contract Address of the contract to modify. * @param _key 32 byte storage slot key. * @param _value 32 byte storage slot value. */ function putContractStorage( address _contract, bytes32 _key, bytes32 _value ) override public authenticated { // A hilarious optimization. `SSTORE`ing a value of `bytes32(0)` is common enough that it's // worth populating this with a non-zero value in advance (during the fraud proof // initialization phase) to cut the execution-time cost down to 5000 gas. contractStorage[_contract][_key] = _value ^ STORAGE_XOR_VALUE; // Only used when initially populating the contract storage. OVM_ExecutionManager will // perform a `hasContractStorage` INVALID_STATE_ACCESS check before putting any contract // storage because writing to zero when the actual value is nonzero causes a gas // discrepancy. Could be moved into a new `putVerifiedContractStorage` function, or // something along those lines. if (verifiedContractStorage[_contract][_key] == false) { verifiedContractStorage[_contract][_key] = true; } } /** * Retrieves a contract storage slot value. * @param _contract Address of the contract to access. * @param _key 32 byte storage slot key. * @return 32 byte storage slot value. */ function getContractStorage( address _contract, bytes32 _key ) override public view returns ( bytes32 ) { // Storage XOR system doesn't work for newly created contracts that haven't set this // storage slot value yet. if ( verifiedContractStorage[_contract][_key] == false && accounts[_contract].isFresh ) { return bytes32(0); } // See `putContractStorage` for more information about the XOR here. return contractStorage[_contract][_key] ^ STORAGE_XOR_VALUE; } /** * Checks whether a contract storage slot exists in the state. * @param _contract Address of the contract to access. * @param _key 32 byte storage slot key. * @return Whether or not the key was set in the state. */ function hasContractStorage( address _contract, bytes32 _key ) override public view returns ( bool ) { return verifiedContractStorage[_contract][_key] || accounts[_contract].isFresh; } /** * Checks whether a storage slot has already been retrieved, and marks it as retrieved if not. * @param _contract Address of the contract to check. * @param _key 32 byte storage slot key. * @return Whether or not the slot was already loaded. */ function testAndSetContractStorageLoaded( address _contract, bytes32 _key ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_contract, _key), ItemState.ITEM_LOADED ); } /** * Checks whether a storage slot has already been modified, and marks it as modified if not. * @param _contract Address of the contract to check. * @param _key 32 byte storage slot key. * @return Whether or not the slot was already modified. */ function testAndSetContractStorageChanged( address _contract, bytes32 _key ) override public authenticated returns ( bool ) { return _testAndSetItemState( _getItemHash(_contract, _key), ItemState.ITEM_CHANGED ); } /** * Attempts to mark a storage slot as committed. * @param _contract Address of the account to commit. * @param _key 32 byte slot key to commit. * @return Whether or not the slot was committed. */ function commitContractStorage( address _contract, bytes32 _key ) override public authenticated returns ( bool ) { bytes32 item = _getItemHash(_contract, _key); if (itemStates[item] != ItemState.ITEM_CHANGED) { return false; } itemStates[item] = ItemState.ITEM_COMMITTED; totalUncommittedContractStorage -= 1; return true; } /** * Increments the total number of uncommitted storage slots. */ function incrementTotalUncommittedContractStorage() override public authenticated { totalUncommittedContractStorage += 1; } /** * Gets the total number of uncommitted storage slots. * @return Total uncommitted storage slots. */ function getTotalUncommittedContractStorage() override public view returns ( uint256 ) { return totalUncommittedContractStorage; } /** * Checks whether a given storage slot was changed during execution. * @param _contract Address to check. * @param _key Key of the storage slot to check. * @return Whether or not the storage slot was changed. */ function wasContractStorageChanged( address _contract, bytes32 _key ) override public view returns ( bool ) { bytes32 item = _getItemHash(_contract, _key); return itemStates[item] >= ItemState.ITEM_CHANGED; } /** * Checks whether a given storage slot was committed after execution. * @param _contract Address to check. * @param _key Key of the storage slot to check. * @return Whether or not the storage slot was committed. */ function wasContractStorageCommitted( address _contract, bytes32 _key ) override public view returns ( bool ) { bytes32 item = _getItemHash(_contract, _key); return itemStates[item] >= ItemState.ITEM_COMMITTED; } /********************** * Internal Functions * **********************/ /** * Generates a unique hash for an address. * @param _address Address to generate a hash for. * @return Unique hash for the given address. */ function _getItemHash( address _address ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_address)); } /** * Generates a unique hash for an address/key pair. * @param _contract Address to generate a hash for. * @param _key Key to generate a hash for. * @return Unique hash for the given pair. */ function _getItemHash( address _contract, bytes32 _key ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked( _contract, _key )); } /** * Checks whether an item is in a particular state (ITEM_LOADED or ITEM_CHANGED) and sets the * item to the provided state if not. * @param _item 32 byte item ID to check. * @param _minItemState Minimum state that must be satisfied by the item. * @return Whether or not the item was already in the state. */ function _testAndSetItemState( bytes32 _item, ItemState _minItemState ) internal returns ( bool ) { bool wasItemState = itemStates[_item] >= _minItemState; if (wasItemState == false) { itemStates[_item] = _minItemState; } return wasItemState; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../optimistic-ethereum/libraries/codec/Lib_OVMCodec.sol"; /** * @title TestLib_OVMCodec */ contract TestLib_OVMCodec { function encodeTransaction( Lib_OVMCodec.Transaction memory _transaction ) public pure returns ( bytes memory _encoded ) { return Lib_OVMCodec.encodeTransaction(_transaction); } function hashTransaction( Lib_OVMCodec.Transaction memory _transaction ) public pure returns ( bytes32 _hash ) { return Lib_OVMCodec.hashTransaction(_transaction); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressManager } from "../../../libraries/resolver/Lib_AddressManager.sol"; import { Lib_SecureMerkleTrie } from "../../../libraries/trie/Lib_SecureMerkleTrie.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; import { Lib_CrossDomainUtils } from "../../../libraries/bridge/Lib_CrossDomainUtils.sol"; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; import { iOVM_CanonicalTransactionChain } from "../../../iOVM/chain/iOVM_CanonicalTransactionChain.sol"; import { iOVM_StateCommitmentChain } from "../../../iOVM/chain/iOVM_StateCommitmentChain.sol"; /* External Imports */ import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; /** * @title OVM_L1CrossDomainMessenger * @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages * from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2 * epoch gas limit, it can be resubmitted via this contract's replay function. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1CrossDomainMessenger is iOVM_L1CrossDomainMessenger, Lib_AddressResolver, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { /********** * Events * **********/ event MessageBlocked( bytes32 indexed _xDomainCalldataHash ); event MessageAllowed( bytes32 indexed _xDomainCalldataHash ); /************* * Constants * *************/ // The default x-domain message sender being set to a non-zero value makes // deployment a bit more expensive, but in exchange the refund on every call to // `relayMessage` by the L1 and L2 messengers will be higher. address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD; /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public blockedMessages; mapping (bytes32 => bool) public relayedMessages; mapping (bytes32 => bool) public successfulMessages; address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; /*************** * Constructor * ***************/ /** * This contract is intended to be behind a delegate proxy. * We pass the zero address to the address resolver just to satisfy the constructor. * We still need to set this value in initialize(). */ constructor() Lib_AddressResolver(address(0)) {} /********************** * Function Modifiers * **********************/ /** * Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may * successfully call a method. */ modifier onlyRelayer() { address relayer = resolve("OVM_L2MessageRelayer"); if (relayer != address(0)) { require( msg.sender == relayer, "Only OVM_L2MessageRelayer can relay L2-to-L1 messages." ); } _; } /******************** * Public Functions * ********************/ /** * @param _libAddressManager Address of the Address Manager. */ function initialize( address _libAddressManager ) public initializer { require( address(libAddressManager) == address(0), "L1CrossDomainMessenger already intialized." ); libAddressManager = Lib_AddressManager(_libAddressManager); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Initialize upgradable OZ contracts __Context_init_unchained(); // Context is a dependency for both Ownable and Pausable __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); } /** * Pause relaying. */ function pause() external onlyOwner { _pause(); } /** * Block a message. * @param _xDomainCalldataHash Hash of the message to block. */ function blockMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = true; emit MessageBlocked(_xDomainCalldataHash); } /** * Allow a message. * @param _xDomainCalldataHash Hash of the message to block. */ function allowMessage( bytes32 _xDomainCalldataHash ) external onlyOwner { blockedMessages[_xDomainCalldataHash] = false; emit MessageAllowed(_xDomainCalldataHash); } function xDomainMessageSender() public override view returns ( address ) { require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set"); return xDomainMsgSender; } /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes memory _message, uint32 _gasLimit ) override public { address ovmCanonicalTransactionChain = resolve("OVM_CanonicalTransactionChain"); // Use the CTC queue length as nonce uint40 nonce = iOVM_CanonicalTransactionChain(ovmCanonicalTransactionChain).getQueueLength(); bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, msg.sender, _message, nonce ); address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger"); _sendXDomainMessage( ovmCanonicalTransactionChain, l2CrossDomainMessenger, xDomainCalldata, _gasLimit ); emit SentMessage(xDomainCalldata); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L1CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) override public nonReentrant onlyRelayer whenNotPaused { bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, _sender, _message, _messageNonce ); require( _verifyXDomainMessage( xDomainCalldata, _proof ) == true, "Provided message could not be verified." ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); require( blockedMessages[xDomainCalldataHash] == false, "Provided message has been blocked." ); require( _target != resolve("OVM_CanonicalTransactionChain"), "Cannot send L2->L1 messages to L1 system contracts." ); xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /** * Replays a cross domain message to the target messenger. * @inheritdoc iOVM_L1CrossDomainMessenger */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _queueIndex, uint32 _gasLimit ) override public { // Verify that the message is in the queue: address canonicalTransactionChain = resolve("OVM_CanonicalTransactionChain"); Lib_OVMCodec.QueueElement memory element = iOVM_CanonicalTransactionChain(canonicalTransactionChain).getQueueElement(_queueIndex); address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger"); // Compute the transactionHash bytes32 transactionHash = keccak256( abi.encode( address(this), l2CrossDomainMessenger, _gasLimit, _message ) ); require( transactionHash == element.transactionHash, "Provided message has not been enqueued." ); bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, _sender, _message, _queueIndex ); _sendXDomainMessage( canonicalTransactionChain, l2CrossDomainMessenger, xDomainCalldata, _gasLimit ); } /********************** * Internal Functions * **********************/ /** * Verifies that the given message is valid. * @param _xDomainCalldata Calldata to verify. * @param _proof Inclusion proof for the message. * @return Whether or not the provided message is valid. */ function _verifyXDomainMessage( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { return ( _verifyStateRootProof(_proof) && _verifyStorageProof(_xDomainCalldata, _proof) ); } /** * Verifies that the state root within an inclusion proof is valid. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStateRootProof( L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain( resolve("OVM_StateCommitmentChain") ); return ( ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false && ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); } /** * Verifies that the storage proof within an inclusion proof is valid. * @param _xDomainCalldata Encoded message calldata. * @param _proof Message inclusion proof. * @return Whether or not the provided proof is valid. */ function _verifyStorageProof( bytes memory _xDomainCalldata, L2MessageInclusionProof memory _proof ) internal view returns ( bool ) { bytes32 storageKey = keccak256( abi.encodePacked( keccak256( abi.encodePacked( _xDomainCalldata, resolve("OVM_L2CrossDomainMessenger") ) ), uint256(0) ) ); ( bool exists, bytes memory encodedMessagePassingAccount ) = Lib_SecureMerkleTrie.get( abi.encodePacked(Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER), _proof.stateTrieWitness, _proof.stateRoot ); require( exists == true, "Message passing predeploy has not been initialized or invalid proof provided." ); Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount( encodedMessagePassingAccount ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encodePacked(storageKey), abi.encodePacked(uint8(1)), _proof.storageTrieWitness, account.storageRoot ); } /** * Sends a cross domain message. * @param _canonicalTransactionChain Address of the OVM_CanonicalTransactionChain instance. * @param _l2CrossDomainMessenger Address of the OVM_L2CrossDomainMessenger instance. * @param _message Message to send. * @param _gasLimit OVM gas limit for the message. */ function _sendXDomainMessage( address _canonicalTransactionChain, address _l2CrossDomainMessenger, bytes memory _message, uint256 _gasLimit ) internal { iOVM_CanonicalTransactionChain(_canonicalTransactionChain).enqueue( _l2CrossDomainMessenger, _gasLimit, _message ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; /** * @title Lib_CrossDomainUtils */ library Lib_CrossDomainUtils { /** * Generates the correct cross domain calldata for a message. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. * @return ABI encoded cross domain calldata. */ function encodeXDomainCalldata( address _target, address _sender, bytes memory _message, uint256 _messageNonce ) internal pure returns ( bytes memory ) { return abi.encodeWithSignature( "relayMessage(address,address,bytes,uint256)", _target, _sender, _message, _messageNonce ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol"; /** * @title iOVM_L1CrossDomainMessenger */ interface iOVM_L1CrossDomainMessenger is iOVM_CrossDomainMessenger { /******************* * Data Structures * *******************/ struct L2MessageInclusionProof { bytes32 stateRoot; Lib_OVMCodec.ChainBatchHeader stateRootBatchHeader; Lib_OVMCodec.ChainInclusionProof stateRootProof; bytes stateTrieWitness; bytes storageTrieWitness; } /******************** * Public Functions * ********************/ /** * Relays a cross domain message to a contract. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. * @param _proof Inclusion proof for the given message. */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) external; /** * Replays a cross domain message to the target messenger. * @param _target Target contract address. * @param _sender Original sender address. * @param _message Message to send to the target. * @param _queueIndex CTC Queue index for the message to replay. * @param _gasLimit Gas limit for the provided message. */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _queueIndex, uint32 _gasLimit ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT 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 // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; import { iOVM_L1MultiMessageRelayer } from "../../../iOVM/bridge/messaging/iOVM_L1MultiMessageRelayer.sol"; /* Library Imports */ import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; /** * @title OVM_L1MultiMessageRelayer * @dev The L1 Multi-Message Relayer contract is a gas efficiency optimization which enables the * relayer to submit multiple messages in a single transaction to be relayed by the L1 Cross Domain * Message Sender. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1MultiMessageRelayer is iOVM_L1MultiMessageRelayer, Lib_AddressResolver { /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /********************** * Function Modifiers * **********************/ modifier onlyBatchRelayer() { require( msg.sender == resolve("OVM_L2BatchMessageRelayer"), // solhint-disable-next-line max-line-length "OVM_L1MultiMessageRelayer: Function can only be called by the OVM_L2BatchMessageRelayer" ); _; } /******************** * Public Functions * ********************/ /** * @notice Forwards multiple cross domain messages to the L1 Cross Domain Messenger for relaying * @param _messages An array of L2 to L1 messages */ function batchRelayMessages( L2ToL1Message[] calldata _messages ) override external onlyBatchRelayer { iOVM_L1CrossDomainMessenger messenger = iOVM_L1CrossDomainMessenger( resolve("Proxy__OVM_L1CrossDomainMessenger") ); for (uint256 i = 0; i < _messages.length; i++) { L2ToL1Message memory message = _messages[i]; messenger.relayMessage( message.target, message.sender, message.message, message.messageNonce, message.proof ); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; interface iOVM_L1MultiMessageRelayer { struct L2ToL1Message { address target; address sender; bytes message; uint256 messageNonce; iOVM_L1CrossDomainMessenger.L2MessageInclusionProof proof; } function batchRelayMessages(L2ToL1Message[] calldata _messages) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_CrossDomainUtils } from "../../../libraries/bridge/Lib_CrossDomainUtils.sol"; /* Interface Imports */ import { iOVM_L2CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L2CrossDomainMessenger.sol"; import { iOVM_L1MessageSender } from "../../../iOVM/predeploys/iOVM_L1MessageSender.sol"; import { iOVM_L2ToL1MessagePasser } from "../../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol"; /* External Imports */ import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /* External Imports */ import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /** * @title OVM_L2CrossDomainMessenger * @dev The L2 Cross Domain Messenger contract sends messages from L2 to L1, and is the entry point * for L2 messages sent via the L1 Cross Domain Messenger. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_L2CrossDomainMessenger is iOVM_L2CrossDomainMessenger, Lib_AddressResolver, ReentrancyGuard { /************* * Constants * *************/ // The default x-domain message sender being set to a non-zero value makes // deployment a bit more expensive, but in exchange the refund on every call to // `relayMessage` by the L1 and L2 messengers will be higher. address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD; /************* * Variables * *************/ mapping (bytes32 => bool) public relayedMessages; mapping (bytes32 => bool) public successfulMessages; mapping (bytes32 => bool) public sentMessages; uint256 public messageNonce; address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor(address _libAddressManager) Lib_AddressResolver(_libAddressManager) ReentrancyGuard() {} /******************** * Public Functions * ********************/ function xDomainMessageSender() public override view returns ( address ) { require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set"); return xDomainMsgSender; } /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes memory _message, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, msg.sender, _message, messageNonce ); messageNonce += 1; sentMessages[keccak256(xDomainCalldata)] = true; _sendXDomainMessage(xDomainCalldata, _gasLimit); emit SentMessage(xDomainCalldata); } /** * Relays a cross domain message to a contract. * @inheritdoc iOVM_L2CrossDomainMessenger */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce ) override nonReentrant public { require( _verifyXDomainMessage() == true, "Provided message could not be verified." ); bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata( _target, _sender, _message, _messageNonce ); bytes32 xDomainCalldataHash = keccak256(xDomainCalldata); require( successfulMessages[xDomainCalldataHash] == false, "Provided message has already been received." ); // Prevent calls to OVM_L2ToL1MessagePasser, which would enable // an attacker to maliciously craft the _message to spoof // a call from any L2 account. if(_target == resolve("OVM_L2ToL1MessagePasser")){ // Write to the successfulMessages mapping and return immediately. successfulMessages[xDomainCalldataHash] = true; return; } xDomainMsgSender = _sender; (bool success, ) = _target.call(_message); xDomainMsgSender = DEFAULT_XDOMAIN_SENDER; // Mark the message as received if the call was successful. Ensures that a message can be // relayed multiple times in the case that the call reverted. if (success == true) { successfulMessages[xDomainCalldataHash] = true; emit RelayedMessage(xDomainCalldataHash); } else { emit FailedRelayedMessage(xDomainCalldataHash); } // Store an identifier that can be used to prove that the given message was relayed by some // user. Gives us an easy way to pay relayers for their work. bytes32 relayId = keccak256( abi.encodePacked( xDomainCalldata, msg.sender, block.number ) ); relayedMessages[relayId] = true; } /********************** * Internal Functions * **********************/ /** * Verifies that a received cross domain message is valid. * @return _valid Whether or not the message is valid. */ function _verifyXDomainMessage() view internal returns ( bool _valid ) { return ( iOVM_L1MessageSender( resolve("OVM_L1MessageSender") ).getL1MessageSender() == resolve("OVM_L1CrossDomainMessenger") ); } /** * Sends a cross domain message. * @param _message Message to send. * param _gasLimit Gas limit for the provided message. */ function _sendXDomainMessage( bytes memory _message, uint256 // _gasLimit ) internal { iOVM_L2ToL1MessagePasser(resolve("OVM_L2ToL1MessagePasser")).passMessageToL1(_message); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol"; /** * @title iOVM_L2CrossDomainMessenger */ interface iOVM_L2CrossDomainMessenger is iOVM_CrossDomainMessenger { /******************** * Public Functions * ********************/ /** * Relays a cross domain message to a contract. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_L1MessageSender */ interface iOVM_L1MessageSender { /******************** * Public Functions * ********************/ function getL1MessageSender() external view returns (address _l1MessageSender); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_L2ToL1MessagePasser */ interface iOVM_L2ToL1MessagePasser { /********** * Events * **********/ event L2ToL1Message( uint256 _nonce, address _sender, bytes _data ); /******************** * Public Functions * ********************/ function passMessageToL1(bytes calldata _message) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_L2ToL1MessagePasser } from "../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol"; /** * @title OVM_L2ToL1MessagePasser * @dev The L2 to L1 Message Passer is a utility contract which facilitate an L1 proof of the * of a message on L2. The L1 Cross Domain Messenger performs this proof in its * _verifyStorageProof function, which verifies the existence of the transaction hash in this * contract's `sentMessages` mapping. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser { /********************** * Contract Variables * **********************/ mapping (bytes32 => bool) public sentMessages; /******************** * Public Functions * ********************/ /** * Passes a message to L1. * @param _message Message to pass to L1. */ function passMessageToL1( bytes memory _message ) override public { // Note: although this function is public, only messages sent from the // OVM_L2CrossDomainMessenger will be relayed by the OVM_L1CrossDomainMessenger. // This is enforced by a check in OVM_L1CrossDomainMessenger._verifyStorageProof(). sentMessages[keccak256( abi.encodePacked( _message, msg.sender ) )] = true; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_L1MessageSender } from "../../iOVM/predeploys/iOVM_L1MessageSender.sol"; import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; /** * @title OVM_L1MessageSender * @dev The L1MessageSender is a predeploy contract running on L2. During the execution of cross * domain transaction from L1 to L2, it returns the address of the L1 account (either an EOA or * contract) which sent the message to L2 via the Canonical Transaction Chain's `enqueue()` * function. * * This contract exclusively serves as a getter for the ovmL1TXORIGIN operation. This is necessary * because there is no corresponding operation in the EVM which the the optimistic solidity compiler * can be replaced with a call to the ExecutionManager's ovmL1TXORIGIN() function. * * * Compiler used: solc * Runtime target: OVM */ contract OVM_L1MessageSender is iOVM_L1MessageSender { /******************** * Public Functions * ********************/ /** * @return _l1MessageSender L1 message sender address (msg.sender). */ function getL1MessageSender() override public view returns ( address _l1MessageSender ) { // Note that on L2 msg.sender (ie. evmCALLER) will always be the Execution Manager return iOVM_ExecutionManager(msg.sender).ovmL1TXORIGIN(); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPReader.sol"; /** * @title TestLib_RLPReader */ contract TestLib_RLPReader { function readList( bytes memory _in ) public pure returns ( bytes[] memory ) { Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_in); bytes[] memory out = new bytes[](decoded.length); for (uint256 i = 0; i < out.length; i++) { out[i] = Lib_RLPReader.readRawBytes(decoded[i]); } return out; } function readString( bytes memory _in ) public pure returns ( string memory ) { return Lib_RLPReader.readString(_in); } function readBytes( bytes memory _in ) public pure returns ( bytes memory ) { return Lib_RLPReader.readBytes(_in); } function readBytes32( bytes memory _in ) public pure returns ( bytes32 ) { return Lib_RLPReader.readBytes32(_in); } function readUint256( bytes memory _in ) public pure returns ( uint256 ) { return Lib_RLPReader.readUint256(_in); } function readBool( bytes memory _in ) public pure returns ( bool ) { return Lib_RLPReader.readBool(_in); } function readAddress( bytes memory _in ) public pure returns ( address ) { return Lib_RLPReader.readAddress(_in); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_MerkleTrie } from "../../optimistic-ethereum/libraries/trie/Lib_MerkleTrie.sol"; /** * @title TestLib_MerkleTrie */ contract TestLib_MerkleTrie { function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bool ) { return Lib_MerkleTrie.verifyInclusionProof( _key, _value, _proof, _root ); } function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bytes32 ) { return Lib_MerkleTrie.update( _key, _value, _proof, _root ); } function get( bytes memory _key, bytes memory _proof, bytes32 _root ) public pure returns ( bool, bytes memory ) { return Lib_MerkleTrie.get( _key, _proof, _root ); } function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) public pure returns ( bytes32 ) { return Lib_MerkleTrie.getSingleNodeRootHash( _key, _value ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_SecureMerkleTrie } from "../../optimistic-ethereum/libraries/trie/Lib_SecureMerkleTrie.sol"; /** * @title TestLib_SecureMerkleTrie */ contract TestLib_SecureMerkleTrie { function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bool ) { return Lib_SecureMerkleTrie.verifyInclusionProof( _key, _value, _proof, _root ); } function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) public pure returns ( bytes32 ) { return Lib_SecureMerkleTrie.update( _key, _value, _proof, _root ); } function get( bytes memory _key, bytes memory _proof, bytes32 _root ) public pure returns ( bool, bytes memory ) { return Lib_SecureMerkleTrie.get( _key, _proof, _root ); } function getSingleNodeRootHash( bytes memory _key, bytes memory _value ) public pure returns ( bytes32 ) { return Lib_SecureMerkleTrie.getSingleNodeRootHash( _key, _value ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_ResolvedDelegateProxy */ contract Lib_ResolvedDelegateProxy { /************* * Variables * *************/ // Using mappings to store fields to avoid overwriting storage slots in the // implementation contract. For example, instead of storing these fields at // storage slot `0` & `1`, they are stored at `keccak256(key + slot)`. // See: https://solidity.readthedocs.io/en/v0.7.0/internals/layout_in_storage.html // NOTE: Do not use this code in your own contract system. // There is a known flaw in this contract, and we will remove it from the repository // in the near future. Due to the very limited way that we are using it, this flaw is // not an issue in our system. mapping (address => string) private implementationName; mapping (address => Lib_AddressManager) private addressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. * @param _implementationName implementationName of the contract to proxy to. */ constructor( address _libAddressManager, string memory _implementationName ) { addressManager[address(this)] = Lib_AddressManager(_libAddressManager); implementationName[address(this)] = _implementationName; } /********************* * Fallback Function * *********************/ fallback() external payable { address target = addressManager[address(this)].getAddress( (implementationName[address(this)]) ); require( target != address(0), "Target address must be initialized." ); (bool success, bytes memory returndata) = target.delegatecall(msg.data); if (success == true) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { assembly { revert(add(returndata, 0x20), mload(returndata)) } } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* External Imports */ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title OVM_GasPriceOracle * @dev This contract exposes the current l2 gas price, a measure of how congested the network * currently is. This measure is used by the Sequencer to determine what fee to charge for * transactions. When the system is more congested, the l2 gas price will increase and fees * will also increase as a result. * * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_GasPriceOracle is Ownable { /************* * Variables * *************/ // Current l2 gas price uint256 public gasPrice; /*************** * Constructor * ***************/ /** * @param _owner Address that will initially own this contract. */ constructor( address _owner, uint256 _initialGasPrice ) Ownable() { setGasPrice(_initialGasPrice); transferOwnership(_owner); } /******************** * Public Functions * ********************/ /** * Allows the owner to modify the l2 gas price. * @param _gasPrice New l2 gas price. */ function setGasPrice( uint256 _gasPrice ) public onlyOwner { gasPrice = _gasPrice; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Contract Imports */ import { L2StandardERC20 } from "../../../libraries/standards/L2StandardERC20.sol"; import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol"; /** * @title OVM_L2StandardTokenFactory * @dev Factory contract for creating standard L2 token representations of L1 ERC20s * compatible with and working on the standard bridge. * Compiler used: optimistic-solc * Runtime target: OVM */ contract OVM_L2StandardTokenFactory { event StandardL2TokenCreated(address indexed _l1Token, address indexed _l2Token); /** * @dev Creates an instance of the standard ERC20 token on L2. * @param _l1Token Address of the corresponding L1 token. * @param _name ERC20 name. * @param _symbol ERC20 symbol. */ function createStandardL2Token( address _l1Token, string memory _name, string memory _symbol ) external { require (_l1Token != address(0), "Must provide L1 token address"); L2StandardERC20 l2Token = new L2StandardERC20( Lib_PredeployAddresses.L2_STANDARD_BRIDGE, _l1Token, _name, _symbol ); emit StandardL2TokenCreated(_l1Token, address(l2Token)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../optimistic-ethereum/libraries/utils/Lib_Bytes32Utils.sol"; /** * @title TestLib_Byte32Utils */ contract TestLib_Bytes32Utils { function toBool( bytes32 _in ) public pure returns ( bool _out ) { return Lib_Bytes32Utils.toBool(_in); } function fromBool( bool _in ) public pure returns ( bytes32 _out ) { return Lib_Bytes32Utils.fromBool(_in); } function toAddress( bytes32 _in ) public pure returns ( address _out ) { return Lib_Bytes32Utils.toAddress(_in); } function fromAddress( address _in ) public pure returns ( bytes32 _out ) { return Lib_Bytes32Utils.fromAddress(_in); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_EthUtils } from "../../optimistic-ethereum/libraries/utils/Lib_EthUtils.sol"; /** * @title TestLib_EthUtils */ contract TestLib_EthUtils { function getCode( address _address, uint256 _offset, uint256 _length ) public view returns ( bytes memory _code ) { return Lib_EthUtils.getCode( _address, _offset, _length ); } function getCode( address _address ) public view returns ( bytes memory _code ) { return Lib_EthUtils.getCode( _address ); } function getCodeSize( address _address ) public view returns ( uint256 _codeSize ) { return Lib_EthUtils.getCodeSize( _address ); } function getCodeHash( address _address ) public view returns ( bytes32 _codeHash ) { return Lib_EthUtils.getCodeHash( _address ); } function createContract( bytes memory _code ) public returns ( address _created ) { return Lib_EthUtils.createContract( _code ); } function getAddressForCREATE( address _creator, uint256 _nonce ) public pure returns ( address _address ) { return Lib_EthUtils.getAddressForCREATE( _creator, _nonce ); } function getAddressForCREATE2( address _creator, bytes memory _bytecode, bytes32 _salt ) public pure returns (address _address) { return Lib_EthUtils.getAddressForCREATE2( _creator, _bytecode, _salt ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_MerkleTree } from "../../optimistic-ethereum/libraries/utils/Lib_MerkleTree.sol"; /** * @title TestLib_MerkleTree */ contract TestLib_MerkleTree { function getMerkleRoot( bytes32[] memory _elements ) public pure returns ( bytes32 ) { return Lib_MerkleTree.getMerkleRoot( _elements ); } function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) public pure returns ( bool ) { return Lib_MerkleTree.verify( _root, _leaf, _index, _siblings, _totalLeaves ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Interface Imports */ import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol"; /* Contract Imports */ import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; /** * @title mockOVM_BondManager */ contract mockOVM_BondManager is iOVM_BondManager, Lib_AddressResolver { constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} function recordGasSpent( bytes32 _preStateRoot, bytes32 _txHash, address _who, uint256 _gasSpent ) override public {} function finalize( bytes32 _preStateRoot, address _publisher, uint256 _timestamp ) override public {} function deposit() override public {} function startWithdrawal() override public {} function finalizeWithdrawal() override public {} function claim( address _who ) override public {} function isCollateralized( address _who ) override public view returns ( bool ) { // Only authenticate sequencer to submit state root batches. return _who == resolve("OVM_Proposer"); } function getGasSpent( bytes32, // _preStateRoot, address // _who ) override public pure returns ( uint256 ) { return 0; } }
******************* Public Functions /* Returns whether or not all of the provided bytecode is safe. @param _bytecode The bytecode to safety check. @return `true` if the bytecode is safe, `false` otherwise./ autogenerated by gen_safety_checker_constants.py number of bytes to skip for each opcode Mask to gate opcode specific cases solhint-disable-next-line max-line-length Halting opcodes solhint-disable-next-line max-line-length PUSH opcodes current opcode: 0x00...0xff inline assembly removes the extra add + bounds check Look up number of bytes to skip from opcodeSkippableBytes and then update indexInWord E.g. the 02030405 in opcodeSkippableBytes is the number of bytes to skip for PUSH1->4 We repeat this 6 times, thus we can only skip bytes for up to PUSH4 ((1+4) * 6 = 30 < 32). If we see an opcode that is listed as 0 skippable bytes e.g. PUSH5, then we will get stuck on that indexInWord and then opNum will be set to the PUSH5 opcode. all pushes are valid opcodes subsequent bytes are not opcodes. Skip them. +1 to skip the _pc++; line below in order to save gas ((-0x5f + 1) = -0x5e) STOP or JUMP or RETURN or INVALID (Note: REVERT is blacklisted, so not included here) We are now inside unreachable code until we hit a JUMPDEST! 37 bytes total, 5 left over --> 32 - 5 bytes = 27 bytes = 216 bits Call identity precompile CALLER POP PUSH1 0x00 PUSH1 0x04 GAS CALL 32 - 8 bytes = 24 bytes = 192 Call EM and abort execution if instructed CALLER PUSH1 0x00 SWAP1 GAS CALL PC PUSH1 0x0E ADD JUMPI RETURNDATASIZE PUSH1 0x00 DUP1 RETURNDATACOPY RETURNDATASIZE PUSH1 0x00 REVERT JUMPDEST RETURNDATASIZE PUSH1 0x01 EQ ISZERO PC PUSH1 0x0a ADD JUMPI PUSH1 0x01 PUSH1 0x00 RETURN JUMPDEST solhint-disable-next-line max-line-length
{ uint256[8] memory opcodeSkippableBytes = [ uint256(0x0001010101010101010101010000000001010101010101010101010101010000), uint256(0x0100000000000000000000000000000000000000010101010101000000010100), uint256(0x0000000000000000000000000000000001010101000000010101010100000000), uint256(0x0203040500000000000000000000000000000000000000000000000000000000), uint256(0x0101010101010101010101010101010101010101010101010101010101010101), uint256(0x0101010101000000000000000000000000000000000000000000000000000000), uint256(0x0000000000000000000000000000000000000000000000000000000000000000), uint256(0x0000000000000000000000000000000000000000000000000000000000000000) ]; uint256 opcodeGateMask = ~uint256(0xffffffffffffffffffffffe000000000fffffffff070ffff9c0ffffec000f001); uint256 opcodeHaltingMask = ~uint256(0x4008000000000000000000000000000000000000004000000000000000000001); uint256 opcodePushMask = ~uint256(0xffffffff000000000000000000000000); uint256 codeLength; uint256 _pc; assembly { _pc := add(_bytecode, 0x20) } codeLength = _pc + _bytecode.length; do { uint256 opNum; assembly { let indexInWord := byte(0, mload(add(opcodeSkippableBytes, byte(0, word)))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word))))) _pc := add(_pc, indexInWord) opNum := byte(indexInWord, word) } if (opBit & opcodeGateMask == 0) { if (opBit & opcodePushMask == 0) { continue; do { _pc++; assembly { opNum := byte(0, mload(_pc)) } } while (_pc < codeLength); assembly { firstOps := mload(_pc) secondOps := shr(216, mload(add(_pc, 0x20))) } if ((firstOps >> 192) == 0x3350600060045af1) { _pc += 8; _pc += 37; return false; } continue; } } _pc++; } while (_pc < codeLength); return true; }
6,167,717
[ 1, 4782, 15486, 342, 2860, 2856, 578, 486, 777, 434, 326, 2112, 22801, 353, 4183, 18, 225, 389, 1637, 16651, 1021, 22801, 358, 24179, 866, 18, 327, 1375, 3767, 68, 309, 326, 22801, 353, 4183, 16, 1375, 5743, 68, 3541, 18, 19, 7840, 635, 3157, 67, 87, 1727, 14369, 67, 19243, 67, 13358, 18, 2074, 1300, 434, 1731, 358, 2488, 364, 1517, 11396, 16698, 358, 12611, 11396, 2923, 6088, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 943, 17, 1369, 17, 2469, 670, 287, 1787, 1061, 7000, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 943, 17, 1369, 17, 2469, 28591, 1061, 7000, 783, 11396, 30, 374, 92, 713, 2777, 20, 5297, 6370, 19931, 7157, 326, 2870, 527, 397, 4972, 866, 10176, 731, 1300, 434, 1731, 358, 2488, 628, 11396, 6368, 19586, 2160, 471, 1508, 1089, 770, 382, 3944, 512, 18, 75, 18, 326, 374, 3462, 23, 3028, 6260, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 288, 203, 3639, 2254, 5034, 63, 28, 65, 3778, 11396, 6368, 19586, 2160, 273, 306, 203, 5411, 2254, 5034, 12, 20, 92, 13304, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 12648, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 2787, 3631, 203, 5411, 2254, 5034, 12, 20, 92, 1611, 12648, 12648, 12648, 12648, 9449, 1611, 1611, 1611, 1611, 1611, 1611, 9449, 1611, 1611, 713, 3631, 203, 5411, 2254, 5034, 12, 20, 92, 12648, 12648, 12648, 12648, 1611, 1611, 1611, 1611, 9449, 1611, 1611, 1611, 1611, 1611, 12648, 3631, 203, 5411, 2254, 5034, 12, 20, 92, 3103, 4630, 3028, 6260, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 3631, 203, 5411, 2254, 5034, 12, 20, 92, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 1611, 3631, 203, 5411, 2254, 5034, 12, 20, 92, 1611, 1611, 1611, 1611, 1611, 12648, 12648, 12648, 12648, 12648, 12648, 9449, 3631, 203, 5411, 2254, 5034, 12, 20, 92, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 3631, 203, 5411, 2254, 5034, 12, 20, 92, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 12648, 13, 203, 3639, 308, 31, 203, 3639, 2254, 5034, 11396, 13215, 5796, 273, 4871, 11890, 5034, 12, 20, 5297, 9460, 9460, 9460, 9460, 9460, 73, 2787, 11706, 9460, 9460, 74, 20, 7301, 9460, 29, 71, 20, 9460, 557, 3784, 74, 11664, 1769, 203, 3639, 2254, 5034, 2 ]
./full_match/80001/0x2d3B52Ab8233f29c7F189B6AAbD4AF8de3036cC4/sources/contracts/mixins/MixinKeys.sol
* Checks if the user has at least one non-expired key. @param _keyOwner the/ check hook directly with address if user has no valid keys
function getHasValidKey( address _keyOwner ) public view returns (bool isValid) { if (balanceOf(_keyOwner) == 0) { if (address(onValidKeyHook) != address(0)) { return onValidKeyHook.isValidKey( address(this), msg.sender, _keyOwner, false ); } } }
9,435,260
[ 1, 4081, 309, 326, 729, 711, 622, 4520, 1245, 1661, 17, 15820, 498, 18, 225, 389, 856, 5541, 326, 19, 866, 3953, 5122, 598, 1758, 309, 729, 711, 1158, 923, 1311, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 336, 5582, 1556, 653, 12, 203, 565, 1758, 389, 856, 5541, 203, 225, 262, 1071, 1476, 1135, 261, 6430, 4908, 13, 288, 203, 565, 309, 261, 12296, 951, 24899, 856, 5541, 13, 422, 374, 13, 288, 203, 1377, 309, 261, 2867, 12, 265, 1556, 653, 5394, 13, 480, 1758, 12, 20, 3719, 288, 203, 3639, 327, 203, 1850, 603, 1556, 653, 5394, 18, 26810, 653, 12, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 389, 856, 5541, 16, 203, 5411, 629, 203, 1850, 11272, 203, 1377, 289, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; // Part: Base64 /// @title Base64 /// @author Brecht Devos - <brecht@loopring.org> /// @notice Provides a function for encoding some bytes in base64 library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // Part: ILuchas interface ILuchas { function balanceOf(address owner) external view returns(uint256); function tokenOfOwnerByIndex(address owner, uint index) external view returns(uint256); function imageData(uint _tokenId) external view returns(string memory); } // Part: IProtoSvg interface IProtoSvg { function startSvg(uint, uint, uint, uint) external view returns (bytes memory); function endSvg() external view returns (bytes memory); function styleColor(bytes memory _element, bytes memory _b) external view returns (bytes memory); function ellipse(bytes memory _e) external view returns (bytes memory); function path(bytes memory _e, string memory _path) external view returns (bytes memory); function renderEtherLogo() external view returns(bytes memory); function triangle(bytes memory _e) external view returns (bytes memory); } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/Context /** * @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; } } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/Counters /** * @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; } } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/IERC165 /** * @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); } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/IERC721Receiver /** * @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); } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/Strings /** * @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); } } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/ERC165 /** * @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; } } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/IERC721 /** * @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; } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/Ownable /** * @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); } } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/IERC721Enumerable /** * @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); } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/IERC721Metadata /** * @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); } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/ERC721 /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/ERC721Enumerable /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // Part: OpenZeppelin/openzeppelin-contracts@4.3.0/ERC721URIStorage /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: ethlogo.sol //TODO: Test new viewport contract EthLogo is ERC721, ERC721URIStorage, ERC721Enumerable, Ownable { IProtoSvg svgContract; ILuchas luchasContract = ILuchas(0x8b4616926705Fb61E9C4eeAc07cd946a5D4b0760); using Counters for Counters.Counter; using Strings for uint256; uint256 constant maxSupply = 10000; // The last could mint little bit more ;-) uint256 constant price = 10000000 gwei; // 0.01 ETH Counters.Counter private _tokenIdCounter; // Define img themes bytes constant colors0 = hex"efccc2ff"; // 4 byte per color bytes constant colors1 = hex"b8faf7ff"; bytes constant colors2 = hex"88aaf1ff"; bytes constant colors3 = hex"cab3f6ff"; bytes constant etherLogo_p0 = hex"00fa01404e4000006a"; bytes constant etherLogo_p1 = hex"00fb01404e4000806a"; bytes constant etherLogo_p2 = hex"00fc01404e4090006a"; bytes constant etherLogo_p3 = hex"00fd01404e4090806a"; bytes constant etherLogo_p4 = hex"00fc0140d0409c0076"; bytes constant etherLogo_p5 = hex"00fd0140d0409c8076"; bytes constant description = "Commemorative Token - Use of ProtoSvgLib, Onchain Svg Library Prototype"; constructor(address _svgContractAddr) ERC721("EthSvgLogo", "ESVG"){ svgContract = IProtoSvg(_svgContractAddr); } function renderEtherShape() public view returns(bytes memory) { return abi.encodePacked( svgContract.triangle(etherLogo_p0), svgContract.triangle(etherLogo_p1), svgContract.triangle(etherLogo_p2), svgContract.triangle(etherLogo_p3), svgContract.triangle(etherLogo_p4), svgContract.triangle(etherLogo_p5) ); } function renderEtherStyle() public view returns(bytes memory) { return abi.encodePacked( svgContract.styleColor(".c250", colors0), svgContract.styleColor(".c251", colors1), svgContract.styleColor(".c252", colors2), svgContract.styleColor(".c253", colors3) ); } function svgRaw(uint256 _tokenId) public view returns(bytes memory){ return abi.encodePacked( svgContract.startSvg(0, 0,118,208), "<g class='l'>", renderEtherShape(), "</g>", renderEtherStyle(), "<style>.l{animation:a 2s infinite ease-in-out", " alternate;transform-origin:50px 50px;stroke-linejoin:round;" "stroke-width:.5;stroke: #88a;} @keyframes a{from{transform:" "scale(.9);filter:sepia(79%);}}</style>", svgContract.endSvg() ); } function svgBase64(uint256 _tokenId) public view returns(string memory){ return ( string( abi.encodePacked( "data:image/svg+xml;base64,", Base64.encode(svgRaw(_tokenId)) ) ) ); } function createToken(uint _qty) external payable { require(maxSupply > _tokenIdCounter.current(), "No more Token to mint"); // So we could have 19 more than the total supply : require(_qty > 0 && _qty <= 20, "mint qty must be between 1-20"); require(_qty * price == msg.value, "Ether amount is not correct"); for (uint i = 0; i < _qty; i++){ _safeMint(msg.sender, _tokenIdCounter.current()); _tokenIdCounter.increment(); } } // The following functions are overrides required by Solidity. function withdraw() public onlyOwner { (bool success, ) = msg.sender.call{value: address(this).balance}(''); require(success, "Withdrawal failed"); } receive() external payable {} // The following functions are overrides required by Solidity. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return string(abi.encodePacked( "data:application/json;base64,", Base64.encode(bytes( abi.encodePacked( '{"name":"', name(), '", "image": "', svgBase64(tokenId), '"}' ) )) )); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
So we could have 19 more than the total supply :
function createToken(uint _qty) external payable { require(maxSupply > _tokenIdCounter.current(), "No more Token to mint"); require(_qty > 0 && _qty <= 20, "mint qty must be between 1-20"); require(_qty * price == msg.value, "Ether amount is not correct"); for (uint i = 0; i < _qty; i++){ _safeMint(msg.sender, _tokenIdCounter.current()); _tokenIdCounter.increment(); } }
13,580,430
[ 1, 10225, 732, 3377, 1240, 5342, 1898, 2353, 326, 2078, 14467, 294, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 752, 1345, 12, 11890, 389, 85, 4098, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 1896, 3088, 1283, 405, 389, 2316, 548, 4789, 18, 2972, 9334, 315, 2279, 1898, 3155, 358, 312, 474, 8863, 203, 3639, 2583, 24899, 85, 4098, 405, 374, 597, 389, 85, 4098, 1648, 4200, 16, 315, 81, 474, 26667, 1297, 506, 3086, 404, 17, 3462, 8863, 203, 3639, 2583, 24899, 85, 4098, 380, 6205, 422, 1234, 18, 1132, 16, 315, 41, 1136, 3844, 353, 486, 3434, 8863, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 85, 4098, 31, 277, 27245, 95, 203, 5411, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 389, 2316, 548, 4789, 18, 2972, 10663, 203, 5411, 389, 2316, 548, 4789, 18, 15016, 5621, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x9D6Dc3dbC7Cc5e1d7241601473FD63d2bD1573f9/sources/contracts/concentrator/stakedao/StakeDAOVaultBase.sol
@dev Internal function to distribute new harvested rewards. @param _tokens The list of reward tokens to update. @param _amounts The list of corresponding reward token amounts. distribute intermediately distribute linearly
function _distribute(address[] memory _tokens, uint256[] memory _amounts) internal { uint256 _totalSupply = totalSupply; for (uint256 i = 0; i < _tokens.length; i++) { if (_amounts[i] == 0) continue; RewardData memory _info = rewardInfo[_tokens[i]]; if (_info.periodLength == 0) { _info.accRewardPerShare = _info.accRewardPerShare.add(_amounts[i].mul(REWARD_PRECISION) / _totalSupply); if (block.timestamp >= _info.finishAt) { _info.rate = uint128(_amounts[i] / _info.periodLength); uint256 _remaining = _info.finishAt - block.timestamp; uint256 _leftover = _remaining * _info.rate; _info.rate = uint128((_amounts[i] + _leftover) / _info.periodLength); } _info.lastUpdate = uint48(block.timestamp); _info.finishAt = uint48(block.timestamp + _info.periodLength); } rewardInfo[_tokens[i]] = _info; } }
16,500,613
[ 1, 3061, 445, 358, 25722, 394, 17895, 90, 3149, 283, 6397, 18, 225, 389, 7860, 1021, 666, 434, 19890, 2430, 358, 1089, 18, 225, 389, 8949, 87, 1021, 666, 434, 4656, 19890, 1147, 30980, 18, 25722, 1554, 7101, 25722, 9103, 715, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 2251, 887, 12, 2867, 8526, 3778, 389, 7860, 16, 2254, 5034, 8526, 3778, 389, 8949, 87, 13, 2713, 288, 203, 565, 2254, 5034, 389, 4963, 3088, 1283, 273, 2078, 3088, 1283, 31, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 7860, 18, 2469, 31, 277, 27245, 288, 203, 1377, 309, 261, 67, 8949, 87, 63, 77, 65, 422, 374, 13, 1324, 31, 203, 1377, 534, 359, 1060, 751, 3778, 389, 1376, 273, 19890, 966, 63, 67, 7860, 63, 77, 13563, 31, 203, 203, 1377, 309, 261, 67, 1376, 18, 6908, 1782, 422, 374, 13, 288, 203, 3639, 389, 1376, 18, 8981, 17631, 1060, 2173, 9535, 273, 389, 1376, 18, 8981, 17631, 1060, 2173, 9535, 18, 1289, 24899, 8949, 87, 63, 77, 8009, 16411, 12, 862, 21343, 67, 3670, 26913, 13, 342, 389, 4963, 3088, 1283, 1769, 203, 3639, 309, 261, 2629, 18, 5508, 1545, 389, 1376, 18, 13749, 861, 13, 288, 203, 1850, 389, 1376, 18, 5141, 273, 2254, 10392, 24899, 8949, 87, 63, 77, 65, 342, 389, 1376, 18, 6908, 1782, 1769, 203, 1850, 2254, 5034, 389, 17956, 273, 389, 1376, 18, 13749, 861, 300, 1203, 18, 5508, 31, 203, 1850, 2254, 5034, 389, 298, 74, 24540, 273, 389, 17956, 380, 389, 1376, 18, 5141, 31, 203, 1850, 389, 1376, 18, 5141, 273, 2254, 10392, 12443, 67, 8949, 87, 63, 77, 65, 397, 389, 298, 74, 24540, 13, 342, 389, 1376, 18, 6908, 1782, 1769, 203, 3639, 289, 203, 203, 3639, 389, 1376, 18, 2722, 2 ]
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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { 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 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @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]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public 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 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); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } /** * @title Heritable * @dev The Heritable contract provides ownership transfer capabilities, in the * case that the current owner stops "heartbeating". Only the heir can pronounce the * owner's death. */ contract Heritable is Ownable { address private heir_; // Time window the owner has to notify they are alive. uint256 private heartbeatTimeout_; // Timestamp of the owner's death, as pronounced by the heir. uint256 private timeOfDeath_; event HeirChanged(address indexed owner, address indexed newHeir); event OwnerHeartbeated(address indexed owner); event OwnerProclaimedDead(address indexed owner, address indexed heir, uint256 timeOfDeath); event HeirOwnershipClaimed(address indexed previousOwner, address indexed newOwner); /** * @dev Throw an exception if called by any account other than the heir's. */ modifier onlyHeir() { require(msg.sender == heir_); _; } /** * @notice Create a new Heritable Contract with heir address 0x0. * @param _heartbeatTimeout time available for the owner to notify they are alive, * before the heir can take ownership. */ function Heritable(uint256 _heartbeatTimeout) public { setHeartbeatTimeout(_heartbeatTimeout); } function setHeir(address newHeir) public onlyOwner { require(newHeir != owner); heartbeat(); HeirChanged(owner, newHeir); heir_ = newHeir; } /** * @dev Use these getter functions to access the internal variables in * an inherited contract. */ function heir() public view returns(address) { return heir_; } function heartbeatTimeout() public view returns(uint256) { return heartbeatTimeout_; } function timeOfDeath() public view returns(uint256) { return timeOfDeath_; } /** * @dev set heir = 0x0 */ function removeHeir() public onlyOwner { heartbeat(); heir_ = 0; } /** * @dev Heir can pronounce the owners death. To claim the ownership, they will * have to wait for `heartbeatTimeout` seconds. */ function proclaimDeath() public onlyHeir { require(ownerLives()); OwnerProclaimedDead(owner, heir_, timeOfDeath_); timeOfDeath_ = block.timestamp; } /** * @dev Owner can send a heartbeat if they were mistakenly pronounced dead. */ function heartbeat() public onlyOwner { OwnerHeartbeated(owner); timeOfDeath_ = 0; } /** * @dev Allows heir to transfer ownership only if heartbeat has timed out. */ function claimHeirOwnership() public onlyHeir { require(!ownerLives()); require(block.timestamp >= timeOfDeath_ + heartbeatTimeout_); OwnershipTransferred(owner, heir_); HeirOwnershipClaimed(owner, heir_); owner = heir_; timeOfDeath_ = 0; } function setHeartbeatTimeout(uint256 newHeartbeatTimeout) internal onlyOwner { require(ownerLives()); heartbeatTimeout_ = newHeartbeatTimeout; } function ownerLives() internal view returns (bool) { return timeOfDeath_ == 0; } } contract HawkToken is Heritable, CappedToken { string public name = "HWK"; string public symbol = "HWK"; uint8 public decimals = 18; function HawkToken ( uint256 _cap, uint256 _hbTimeout ) public Heritable(_hbTimeout) CappedToken(_cap) {} // Allow owner to change heartbeat's timeout function setHBT(uint256 newHeartbeatTimeout) public onlyOwner { setHeartbeatTimeout(newHeartbeatTimeout); } }
* @dev Allows heir to transfer ownership only if heartbeat has timed out./
function claimHeirOwnership() public onlyHeir { require(!ownerLives()); require(block.timestamp >= timeOfDeath_ + heartbeatTimeout_); OwnershipTransferred(owner, heir_); HeirOwnershipClaimed(owner, heir_); owner = heir_; timeOfDeath_ = 0; }
1,477,736
[ 1, 19132, 3904, 481, 358, 7412, 23178, 1338, 309, 12923, 711, 7491, 596, 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, 225, 445, 7516, 5256, 481, 5460, 12565, 1435, 1071, 1338, 5256, 481, 288, 203, 565, 2583, 12, 5, 8443, 48, 3606, 10663, 203, 565, 2583, 12, 2629, 18, 5508, 1545, 813, 951, 758, 421, 67, 397, 12923, 2694, 67, 1769, 203, 565, 14223, 9646, 5310, 1429, 4193, 12, 8443, 16, 3904, 481, 67, 1769, 203, 565, 8264, 481, 5460, 12565, 9762, 329, 12, 8443, 16, 3904, 481, 67, 1769, 203, 565, 3410, 273, 3904, 481, 67, 31, 203, 565, 813, 951, 758, 421, 67, 273, 374, 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 ]
./full_match/1/0x4585812e089B5C5f941Ee508C64DF78204BdE01f/sources/src/IndieV1.sol
@notice Each indie member’s withholding by address
mapping(address => uint256) public withholdingPercentageByIndie;
16,461,037
[ 1, 3442, 1547, 1385, 3140, 163, 227, 252, 87, 598, 21056, 310, 635, 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 ]
[ 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, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 598, 21056, 310, 16397, 858, 3866, 1385, 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 ]
./full_match/44787/0x89c63C0Bd5Ed84Da5A4a0D53501F03Fc36c6A19f/sources/contracts/subscriptions/CaskSubscriptions.sol
still in trial, just change now
if (subscription.status == SubscriptionStatus.Trialing) {
13,264,470
[ 1, 334, 737, 316, 12950, 16, 2537, 2549, 2037, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 309, 261, 11185, 18, 2327, 422, 12132, 1482, 18, 6251, 287, 310, 13, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; // /* CONTRACT */ contract SafeMath { function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // END_OF_contract_SafeMath //_________________________________________________________ // /* INTERFACES */ // interface tokenRecipient { function receiveApproval(address _from, uint256 _tokenAmountApproved, address tokenMacroansy, bytes _extraData) public returns(bool success); } //________________________________________________________ // interface ICO { function buy( uint payment, address buyer, bool isPreview) public returns(bool success, uint amount); function redeemCoin(uint256 amount, address redeemer, bool isPreview) public returns (bool success, uint redeemPayment); function sell(uint256 amount, address seller, bool isPreview) public returns (bool success, uint sellPayment ); function paymentAction(uint paymentValue, address beneficiary, uint paytype) public returns(bool success); function recvShrICO( address _spender, uint256 _value, uint ShrID) public returns (bool success); function burn( uint256 value, bool unburn, uint totalSupplyStart, uint balOfOwner) public returns( bool success); function getSCF() public returns(uint seriesCapFactorMulByTenPowerEighteen); function getMinBal() public returns(uint minBalForAccnts_ ); function getAvlShares(bool show) public returns(uint totalSupplyOfCoinsInSeriesNow, uint coinsAvailableForSale, uint icoFunding); } //_______________________________________________________ // interface Exchg{ function sell_Exchg_Reg( uint amntTkns, uint tknPrice, address seller) public returns(bool success); function buy_Exchg_booking( address seller, uint amntTkns, uint tknPrice, address buyer, uint payment ) public returns(bool success); function buy_Exchg_BkgChk( address seller, uint amntTkns, uint tknPrice, address buyer, uint payment) public returns(bool success); function updateSeller( address seller, uint tknsApr, address buyer, uint payment) public returns(bool success); function getExchgComisnMulByThousand() public returns(uint exchgCommissionMulByThousand_); function viewSellOffersAtExchangeMacroansy(address seller, bool show) view public returns (uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint sellerBookedTime, address buyerWhoBooked, uint buyPaymentBooked, uint buyerBookedTime, uint exchgCommissionMulByThousand_); } //_________________________________________________________ // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md /* CONTRACT */ // contract TokenERC20Interface { function totalSupply() public constant returns (uint coinLifeTimeTotalSupply); function balanceOf(address tokenOwner) public constant returns (uint coinBalance); function allowance(address tokenOwner, address spender) public constant returns (uint coinsRemaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address _from, address to, uint tokens) public returns (bool success); event Transfer(address indexed _from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } //END_OF_contract_ERC20Interface //_________________________________________________________________ /* CONTRACT */ /** * COPYRIGHT Macroansy * http://www.macroansy.org */ contract TokenMacroansy is TokenERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals = 18; // address internal owner; address private beneficiaryFunds; // uint256 public totalSupply; uint256 internal totalSupplyStart; // mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping( address => bool) internal frozenAccount; // mapping(address => uint) private msgSndr; // address tkn_addr; address ico_addr; address exchg_addr; // uint256 internal allowedIndividualShare; uint256 internal allowedPublicShare; // //uint256 internal allowedFounderShare; //uint256 internal allowedPOOLShare; //uint256 internal allowedVCShare; //uint256 internal allowedColdReserve; //_________________________________________________________ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Burn(address indexed from, uint amount); event UnBurn(address indexed from, uint amount); event FundOrPaymentTransfer(address beneficiary, uint amount); event FrozenFunds(address target, bool frozen); event BuyAtMacroansyExchg(address buyer, address seller, uint tokenAmount, uint payment); //_________________________________________________________ // //CONSTRUCTOR /* Initializes contract with initial supply tokens to the creator of the contract */ function TokenMacroansy() public { owner = msg.sender; beneficiaryFunds = owner; //totalSupplyStart = initialSupply * 10** uint256(decimals); totalSupplyStart = 3999 * 10** uint256(decimals); totalSupply = totalSupplyStart; // balanceOf[msg.sender] = totalSupplyStart; Transfer(address(0), msg.sender, totalSupplyStart); // name = "TokenMacroansy"; symbol = "$BEE"; // allowedIndividualShare = uint(1)*totalSupplyStart/100; allowedPublicShare = uint(20)* totalSupplyStart/100; // //allowedFounderShare = uint(20)*totalSupplyStart/100; //allowedPOOLShare = uint(9)* totalSupplyStart/100; //allowedColdReserve = uint(41)* totalSupplyStart/100; //allowedVCShare = uint(10)* totalSupplyStart/100; } //_________________________________________________________ modifier onlyOwner { require(msg.sender == owner); _; } function wadmin_transferOr(address _Or) public onlyOwner { owner = _Or; } //_________________________________________________________ /** * @notice Show the `totalSupply` for this Token contract */ function totalSupply() constant public returns (uint coinLifeTimeTotalSupply) { return totalSupply ; } //_________________________________________________________ /** * @notice Show the `tokenOwner` balances for this contract * @param tokenOwner the token owners address */ function balanceOf(address tokenOwner) constant public returns (uint coinBalance) { return balanceOf[tokenOwner]; } //_________________________________________________________ /** * @notice Show the allowance given by `tokenOwner` to the `spender` * @param tokenOwner the token owner address allocating allowance * @param spender the allowance spenders address */ function allowance(address tokenOwner, address spender) constant public returns (uint coinsRemaining) { return allowance[tokenOwner][spender]; } //_________________________________________________________ // function wadmin_setContrAddr(address icoAddr, address exchAddr ) public onlyOwner returns(bool success){ tkn_addr = this; ico_addr = icoAddr; exchg_addr = exchAddr; return true; } // function _getTknAddr() internal returns(address tkn_ma_addr){ return(tkn_addr); } function _getIcoAddr() internal returns(address ico_ma_addr){ return(ico_addr); } function _getExchgAddr() internal returns(address exchg_ma_addr){ return(exchg_addr); } // _getTknAddr(); _getIcoAddr(); _getExchgAddr(); // address tkn_addr; address ico_addr; address exchg_addr; //_________________________________________________________ // /* Internal transfer, only can be called by this contract */ // function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require(!frozenAccount[_from]); require(!frozenAccount[_to]); uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; require (balanceOf[_from] >= _valueA); require (balanceOf[_to] + _valueA > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] = safeSub(balanceOf[_from], _valueA); balanceOf[_to] = safeAdd(balanceOf[_to], _valueA); Transfer(_from, _to, _valueA); _valueA = 0; assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } //________________________________________________________ /** * Transfer tokens * * @notice Allows to Send Coins to other accounts * @param _to The address of the recipient of coins * @param _value The amount of coins to send */ function transfer(address _to, uint256 _value) public returns(bool success) { //check sender and receiver allw limits in accordance with ico contract bool sucsSlrLmt = _chkSellerLmts( msg.sender, _value); bool sucsByrLmt = _chkBuyerLmts( _to, _value); require(sucsSlrLmt == true && sucsByrLmt == true); // uint valtmp = _value; uint _valueTemp = valtmp; valtmp = 0; _transfer(msg.sender, _to, _valueTemp); _valueTemp = 0; return true; } //_________________________________________________________ /** * Transfer tokens from other address * * @notice sender can set an allowance for another contract, * @notice and the other contract interface function receiveApproval * @notice can call this funtion for token as payment and add further coding for service. * @notice please also refer to function approveAndCall * @notice Send `_value` tokens to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient of coins * @param _value The amount coins to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; require(_valueA <= allowance[_from][msg.sender]); allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _valueA); _transfer(_from, _to, _valueA); _valueA = 0; return true; } //_________________________________________________________ /** * Set allowance for other address * * @notice Allows `_spender` to spend no more than `_value` coins from your account * @param _spender The address authorized to spend * @param _value The max amount of coins allocated to spender */ function approve(address _spender, uint256 _value) public returns (bool success) { //check sender and receiver allw limits in accordance with ico contract bool sucsSlrLmt = _chkSellerLmts( msg.sender, _value); bool sucsByrLmt = _chkBuyerLmts( _spender, _value); require(sucsSlrLmt == true && sucsByrLmt == true); // uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; allowance[msg.sender][_spender] = _valueA; Approval(msg.sender, _spender, _valueA); _valueA =0; return true; } //_________________________________________________________ /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` coins in from your account * * @param _spender The address authorized to spend * @param _value the max amount of coins the spender can spend * @param _extraData some extra information to send to the spender contracts */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; if (approve(_spender, _valueA)) { spender.receiveApproval(msg.sender, _valueA, this, _extraData); } _valueA = 0; return true; } //_________________________________________________________ // /** * @notice `freeze` Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function wadmin_freezeAccount(address target, bool freeze) onlyOwner public returns(bool success) { frozenAccount[target] = freeze; FrozenFunds(target, freeze); return true; } //________________________________________________________ // function _safeTransferTkn( address _from, address _to, uint amount) internal returns(bool sucsTrTk){ uint tkA = amount; uint tkAtemp = tkA; tkA = 0; _transfer(_from, _to, tkAtemp); tkAtemp = 0; return true; } //_________________________________________________________ // function _safeTransferPaymnt( address paymentBenfcry, uint payment) internal returns(bool sucsTrPaymnt){ uint pA = payment; uint paymentTemp = pA; pA = 0; paymentBenfcry.transfer(paymentTemp); FundOrPaymentTransfer(paymentBenfcry, paymentTemp); paymentTemp = 0; return true; } //_________________________________________________________ // function _safePaymentActionAtIco( uint payment, address paymentBenfcry, uint paytype) internal returns(bool success){ // payment req to ico uint Pm = payment; uint PmTemp = Pm; Pm = 0; ICO ico = ICO(_getIcoAddr()); // paytype 1 for redeempayment and 2 for sell payment bool pymActSucs = ico.paymentAction( PmTemp, paymentBenfcry, paytype); require(pymActSucs == true); PmTemp = 0; return true; } //_________________________________________________________ /* @notice Allows to Buy ICO tokens directly from this contract by sending ether */ function buyCoinsAtICO() payable public returns(bool success) { msgSndr[msg.sender] = msg.value; ICO ico = ICO(_getIcoAddr() ); require( msg.value > 0 ); // buy exe at ico bool icosuccess; uint tknsBuyAppr; (icosuccess, tknsBuyAppr) = ico.buy( msg.value, msg.sender, false); require( icosuccess == true ); // tkn transfer bool sucsTrTk = _safeTransferTkn( owner, msg.sender, tknsBuyAppr); require(sucsTrTk == true); msgSndr[msg.sender] = 0; return (true) ; } //_____________________________________________________________ // /* @notice Allows anyone to preview a Buy of ICO tokens before an actual buy */ function buyCoinsPreview(uint myProposedPaymentInWEI) public view returns(bool success, uint tokensYouCanBuy, uint yourSafeMinBalReqdInWEI) { uint payment = myProposedPaymentInWEI; msgSndr[msg.sender] = payment; success = false; ICO ico = ICO(_getIcoAddr() ); tokensYouCanBuy = 0; bool icosuccess; (icosuccess, tokensYouCanBuy) = ico.buy( payment, msg.sender, true); msgSndr[msg.sender] = 0; return ( icosuccess, tokensYouCanBuy, ico.getMinBal()) ; } //_____________________________________________________________ /** * @notice Allows Token owners to Redeem Tokens to this Contract for its value promised */ function redeemCoinsToICO( uint256 amountOfCoinsToRedeem) public returns (bool success ) { uint amount = amountOfCoinsToRedeem; msgSndr[msg.sender] = amount; bool isPreview = false; ICO ico = ICO(_getIcoAddr()); // redeem exe at ico bool icosuccess ; uint redeemPaymentValue; (icosuccess , redeemPaymentValue) = ico.redeemCoin( amount, msg.sender, isPreview); require( icosuccess == true); require( _getIcoAddr().balance >= safeAdd( ico.getMinBal() , redeemPaymentValue) ); bool sucsTrTk = false; bool pymActSucs = false; if(isPreview == false) { // transfer tkns sucsTrTk = _safeTransferTkn( msg.sender, owner, amount); require(sucsTrTk == true); // payment req to ico 1 for redeempayment and 2 for sell payment msgSndr[msg.sender] = redeemPaymentValue; pymActSucs = _safePaymentActionAtIco( redeemPaymentValue, msg.sender, 1); require(pymActSucs == true); } msgSndr[msg.sender] = 0; return (true); } //_________________________________________________________ /** * @notice Allows Token owners to Sell Tokens directly to this Contract * */ function sellCoinsToICO( uint256 amountOfCoinsToSell ) public returns (bool success ) { uint amount = amountOfCoinsToSell; msgSndr[msg.sender] = amount; bool isPreview = false; ICO ico = ICO(_getIcoAddr() ); // sell exe at ico bool icosuccess; uint sellPaymentValue; ( icosuccess , sellPaymentValue) = ico.sell( amount, msg.sender, isPreview); require( icosuccess == true ); require( _getIcoAddr().balance >= safeAdd(ico.getMinBal() , sellPaymentValue) ); bool sucsTrTk = false; bool pymActSucs = false; if(isPreview == false){ // token transfer sucsTrTk = _safeTransferTkn( msg.sender, owner, amount); require(sucsTrTk == true); // payment request to ico 1 for redeempayment and 2 for sell payment msgSndr[msg.sender] = sellPaymentValue; pymActSucs = _safePaymentActionAtIco( sellPaymentValue, msg.sender, 2); require(pymActSucs == true); } msgSndr[msg.sender] = 0; return ( true); } //________________________________________________________ /** * @notice a sellers allowed limits in holding ico tokens is checked */ // function _chkSellerLmts( address seller, uint amountOfCoinsSellerCanSell) internal returns(bool success){ uint amountTkns = amountOfCoinsSellerCanSell; success = false; ICO ico = ICO( _getIcoAddr() ); uint seriesCapFactor = ico.getSCF(); if( amountTkns <= balanceOf[seller] && balanceOf[seller] <= safeDiv(allowedIndividualShare*seriesCapFactor,10**18) ){ success = true; } return success; } // bool sucsSlrLmt = _chkSellerLmts( address seller, uint amountTkns); //_________________________________________________________ // /** * @notice a buyers allowed limits in holding ico tokens is checked */ function _chkBuyerLmts( address buyer, uint amountOfCoinsBuyerCanBuy) internal returns(bool success){ uint amountTkns = amountOfCoinsBuyerCanBuy; success = false; ICO ico = ICO( _getIcoAddr() ); uint seriesCapFactor = ico.getSCF(); if( amountTkns <= safeSub( safeDiv(allowedIndividualShare*seriesCapFactor,10**18), balanceOf[buyer] )) { success = true; } return success; } //_________________________________________________________ // /** * @notice a buyers allowed limits in holding ico tokens along with financial capacity to buy is checked */ function _chkBuyerLmtsAndFinl( address buyer, uint amountTkns, uint priceOfr) internal returns(bool success){ success = false; // buyer limits bool sucs1 = false; sucs1 = _chkBuyerLmts( buyer, amountTkns); // buyer funds ICO ico = ICO( _getIcoAddr() ); bool sucs2 = false; if( buyer.balance >= safeAdd( safeMul(amountTkns , priceOfr) , ico.getMinBal() ) ) sucs2 = true; if( sucs1 == true && sucs2 == true) success = true; return success; } //_________________________________________________________ // function _slrByrLmtChk( address seller, uint amountTkns, uint priceOfr, address buyer) internal returns(bool success){ // seller limits check bool successSlrl; (successSlrl) = _chkSellerLmts( seller, amountTkns); // buyer limits check bool successByrlAFinl; (successByrlAFinl) = _chkBuyerLmtsAndFinl( buyer, amountTkns, priceOfr); require( successSlrl == true && successByrlAFinl == true); return true; } //___________________________________________________________________ /** * @notice allows a seller to formally register his sell offer at ExchangeMacroansy */ function sellBkgAtExchg( uint amountOfCoinsOffer, uint priceOfOneCoinInWEI) public returns(bool success){ uint amntTkns = amountOfCoinsOffer ; uint tknPrice = priceOfOneCoinInWEI; // seller limits bool successSlrl; (successSlrl) = _chkSellerLmts( msg.sender, amntTkns); require(successSlrl == true); msgSndr[msg.sender] = amntTkns; // bkg registration at exchange Exchg em = Exchg(_getExchgAddr()); bool emsuccess; (emsuccess) = em.sell_Exchg_Reg( amntTkns, tknPrice, msg.sender ); require(emsuccess == true ); msgSndr[msg.sender] = 0; return true; } //_________________________________________________________ // /** * @notice function for booking and locking for a buy with respect to a sale offer registered * @notice after booking then proceed for payment using func buyCoinsAtExchg * @notice payment booking value and actual payment value should be exact */ function buyBkgAtExchg( address seller, uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint myProposedPaymentInWEI) public returns(bool success){ uint amountTkns = sellersCoinAmountOffer; uint priceOfr = sellersPriceOfOneCoinInWEI; uint payment = myProposedPaymentInWEI; msgSndr[msg.sender] = amountTkns; // seller buyer limits check bool sucsLmt = _slrByrLmtChk( seller, amountTkns, priceOfr, msg.sender); require(sucsLmt == true); // booking at exchange Exchg em = Exchg(_getExchgAddr()); bool emBkgsuccess; (emBkgsuccess)= em.buy_Exchg_booking( seller, amountTkns, priceOfr, msg.sender, payment); require( emBkgsuccess == true ); msgSndr[msg.sender] = 0; return true; } //________________________________________________________ /** * @notice for buyingCoins at ExchangeMacroansy * @notice please first book the buy through function_buy_Exchg_booking */ // function buyCoinsAtExchg( address seller, uint amountTkns, uint priceOfr) payable public returns(bool success) { function buyCoinsAtExchg( address seller, uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI) payable public returns(bool success) { uint amountTkns = sellersCoinAmountOffer; uint priceOfr = sellersPriceOfOneCoinInWEI; require( msg.value > 0 && msg.value <= safeMul(amountTkns, priceOfr ) ); msgSndr[msg.sender] = amountTkns; // calc tokens that can be bought uint tknsBuyAppr = safeDiv(msg.value , priceOfr); // check buyer booking at exchange Exchg em = Exchg(_getExchgAddr()); bool sucsBkgChk = em.buy_Exchg_BkgChk(seller, amountTkns, priceOfr, msg.sender, msg.value); require(sucsBkgChk == true); // update seller reg and buyer booking at exchange msgSndr[msg.sender] = tknsBuyAppr; bool emUpdateSuccess; (emUpdateSuccess) = em.updateSeller(seller, tknsBuyAppr, msg.sender, msg.value); require( emUpdateSuccess == true ); // token transfer in this token contract bool sucsTrTkn = _safeTransferTkn( seller, msg.sender, tknsBuyAppr); require(sucsTrTkn == true); // payment to seller bool sucsTrPaymnt; sucsTrPaymnt = _safeTransferPaymnt( seller, safeSub( msg.value , safeDiv(msg.value*em.getExchgComisnMulByThousand(),1000) ) ); require(sucsTrPaymnt == true ); // BuyAtMacroansyExchg(msg.sender, seller, tknsBuyAppr, msg.value); //event msgSndr[msg.sender] = 0; return true; } //___________________________________________________________ /** * @notice Fall Back Function, not to receive ether directly and/or accidentally * */ function () public payable { if(msg.sender != owner) revert(); } //_________________________________________________________ /* * @notice Burning tokens ie removing tokens from the formal total supply */ function wadmin_burn( uint256 value, bool unburn) onlyOwner public returns( bool success ) { msgSndr[msg.sender] = value; ICO ico = ICO( _getIcoAddr() ); if( unburn == false) { balanceOf[owner] = safeSub( balanceOf[owner] , value); totalSupply = safeSub( totalSupply, value); Burn(owner, value); } if( unburn == true) { balanceOf[owner] = safeAdd( balanceOf[owner] , value); totalSupply = safeAdd( totalSupply , value); UnBurn(owner, value); } bool icosuccess = ico.burn( value, unburn, totalSupplyStart, balanceOf[owner] ); require( icosuccess == true); return true; } //_________________________________________________________ /* * @notice Withdraw Payments to beneficiary * @param withdrawAmount the amount withdrawn in wei */ function wadmin_withdrawFund(uint withdrawAmount) onlyOwner public returns(bool success) { success = _withdraw(withdrawAmount); return success; } //_________________________________________________________ /*internal function can called by this contract only */ function _withdraw(uint _withdrawAmount) internal returns(bool success) { bool sucsTrPaymnt = _safeTransferPaymnt( beneficiaryFunds, _withdrawAmount); require(sucsTrPaymnt == true); return true; } //_________________________________________________________ /** * @notice Allows to receive coins from Contract Share approved by contract * @notice to receive the share, it has to be already approved by the contract * @notice the share Id will be provided by contract while payments are made through other channels like paypal * @param amountOfCoinsToReceive the allocated allowance of coins to be transferred to you * @param ShrID 1 is FounderShare, 2 is POOLShare, 3 is ColdReserveShare, 4 is VCShare, 5 is PublicShare, 6 is RdmSellPool */ function receiveICOcoins( uint256 amountOfCoinsToReceive, uint ShrID ) public returns (bool success){ msgSndr[msg.sender] = amountOfCoinsToReceive; ICO ico = ICO( _getIcoAddr() ); bool icosuccess; icosuccess = ico.recvShrICO(msg.sender, amountOfCoinsToReceive, ShrID ); require (icosuccess == true); bool sucsTrTk; sucsTrTk = _safeTransferTkn( owner, msg.sender, amountOfCoinsToReceive); require(sucsTrTk == true); msgSndr[msg.sender] = 0; return true; } //_______________________________________________________ // called by other contracts function sendMsgSndr(address caller, address origin) public returns(bool success, uint value){ (success, value) = _sendMsgSndr(caller, origin); return(success, value); } //_______________________________________________________ // function _sendMsgSndr(address caller, address origin) internal returns(bool success, uint value){ require(caller == _getIcoAddr() || caller == _getExchgAddr()); //require(origin == tx.origin); return(true, msgSndr[origin]); } //_______________________________________________________ // function a_viewSellOffersAtExchangeMacroansy(address seller, bool show) view public returns (uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint sellerBookedTime, address buyerWhoBooked, uint buyPaymentBooked, uint buyerBookedTime, uint exchgCommissionMulByThousand_){ if(show == true){ Exchg em = Exchg(_getExchgAddr()); ( sellersCoinAmountOffer, sellersPriceOfOneCoinInWEI, sellerBookedTime, buyerWhoBooked, buyPaymentBooked, buyerBookedTime, exchgCommissionMulByThousand_) = em.viewSellOffersAtExchangeMacroansy( seller, show) ; return ( sellersCoinAmountOffer, sellersPriceOfOneCoinInWEI, sellerBookedTime, buyerWhoBooked, buyPaymentBooked, buyerBookedTime, exchgCommissionMulByThousand_); } } //_________________________________________________________ // function a_viewCoinSupplyAndFunding(bool show) public view returns(uint totalSupplyOfCoinsInSeriesNow, uint coinsAvailableForSale, uint icoFunding){ if(show == true){ ICO ico = ICO( _getIcoAddr() ); ( totalSupplyOfCoinsInSeriesNow, coinsAvailableForSale, icoFunding) = ico.getAvlShares(show); return( totalSupplyOfCoinsInSeriesNow, coinsAvailableForSale, icoFunding); } } //_______________________________________________________ // /* bool private isEndOk; function endOfRewards(bool isEndNow) public onlyOwner { isEndOk == isEndNow; } function endOfRewardsConfirmed(bool isEndNow) public onlyOwner{ if(isEndOk == true && isEndNow == true) selfdestruct(owner); } */ //_______________________________________________________ } // END_OF_CONTRACT
_______________________________________________________
interface Exchg{ function sell_Exchg_Reg( uint amntTkns, uint tknPrice, address seller) public returns(bool success); function buy_Exchg_booking( address seller, uint amntTkns, uint tknPrice, address buyer, uint payment ) public returns(bool success); function buy_Exchg_BkgChk( address seller, uint amntTkns, uint tknPrice, address buyer, uint payment) public returns(bool success); function updateSeller( address seller, uint tknsApr, address buyer, uint payment) public returns(bool success); function getExchgComisnMulByThousand() public returns(uint exchgCommissionMulByThousand_); function viewSellOffersAtExchangeMacroansy(address seller, bool show) view public returns (uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint sellerBookedTime, address buyerWhoBooked, uint buyPaymentBooked, uint buyerBookedTime, uint exchgCommissionMulByThousand_); }
7,901,557
[ 1, 21157, 21157, 21157, 7198, 31268, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1560, 1312, 343, 75, 95, 203, 540, 203, 3639, 445, 357, 80, 67, 424, 343, 75, 67, 1617, 12, 2254, 2125, 496, 56, 79, 2387, 16, 2254, 13030, 82, 5147, 16, 1758, 29804, 13, 1071, 1135, 12, 6430, 2216, 1769, 203, 3639, 445, 30143, 67, 424, 343, 75, 67, 3618, 310, 12, 1758, 29804, 16, 2254, 2125, 496, 56, 79, 2387, 16, 2254, 13030, 82, 5147, 16, 1758, 27037, 16, 2254, 5184, 262, 1071, 1135, 12, 6430, 2216, 1769, 203, 3639, 445, 30143, 67, 424, 343, 75, 67, 38, 14931, 782, 79, 12, 1758, 29804, 16, 2254, 2125, 496, 56, 79, 2387, 16, 2254, 13030, 82, 5147, 16, 1758, 27037, 16, 2254, 5184, 13, 1071, 1135, 12, 6430, 2216, 1769, 203, 3639, 445, 1089, 22050, 12, 1758, 29804, 16, 2254, 13030, 2387, 37, 683, 16, 1758, 27037, 16, 2254, 5184, 13, 1071, 1135, 12, 6430, 2216, 1769, 21281, 203, 3639, 445, 26246, 343, 75, 799, 291, 82, 27860, 858, 1315, 1481, 464, 1435, 1071, 1135, 12, 11890, 431, 343, 75, 799, 3951, 27860, 858, 1315, 1481, 464, 67, 1769, 21281, 203, 3639, 445, 1476, 55, 1165, 7210, 414, 861, 11688, 17392, 634, 93, 12, 2867, 29804, 16, 1426, 2405, 13, 1476, 1071, 1135, 261, 11890, 357, 3135, 27055, 6275, 10513, 16, 2254, 357, 3135, 5147, 951, 3335, 27055, 382, 6950, 45, 16, 2254, 29804, 9084, 329, 950, 16, 1758, 27037, 2888, 83, 9084, 329, 16, 2254, 30143, 6032, 9084, 329, 16, 2254, 27037, 9084, 329, 950, 16, 2254, 431, 343, 75, 799, 3951, 2 ]
pragma solidity ^0.4.24; import "contracts/Issuer.sol"; import "contracts/NuCypherToken.sol"; import "contracts/proxy/Upgradeable.sol"; /** * @dev Contract for testing internal methods in the Issuer contract **/ contract IssuerMock is Issuer { constructor( NuCypherToken _token, uint32 _hoursPerPeriod, uint256 _miningCoefficient, uint256 _lockedPeriodsCoefficient, uint16 _rewardedPeriods ) public Issuer( _token, _hoursPerPeriod, _miningCoefficient, _lockedPeriodsCoefficient, _rewardedPeriods ) { } function testMint( uint16 _period, uint256 _lockedValue, uint256 _totalLockedValue, uint16 _allLockedPeriods ) public returns (uint256 amount) { amount = mint( _period, _lockedValue, _totalLockedValue, _allLockedPeriods); token.transfer(msg.sender, amount); } } /** * @notice Upgrade to this contract must lead to fail **/ contract IssuerBad is Upgradeable { address public token; uint256 public miningCoefficient; uint256 public lockedPeriodsCoefficient; uint32 public secondsPerPeriod; uint16 public rewardedPeriods; uint16 public lastMintedPeriod; // uint256 public currentSupply1; uint256 public currentSupply2; function verifyState(address) public {} function finishUpgrade(address) public {} } /** * @notice Contract for testing upgrading the Issuer contract **/ contract IssuerV2Mock is Issuer { uint256 public valueToCheck; constructor( NuCypherToken _token, uint32 _hoursPerPeriod, uint256 _miningCoefficient, uint256 _lockedPeriodsCoefficient, uint16 _rewardedPeriods ) public Issuer( _token, _hoursPerPeriod, _miningCoefficient, _lockedPeriodsCoefficient, _rewardedPeriods ) { } function setValueToCheck(uint256 _valueToCheck) public { valueToCheck = _valueToCheck; } function verifyState(address _testTarget) public onlyOwner { super.verifyState(_testTarget); require(uint256(delegateGet(_testTarget, "valueToCheck()")) == valueToCheck); } }
* @notice Contract for testing upgrading the Issuer contract/
contract IssuerV2Mock is Issuer { uint256 public valueToCheck; constructor( NuCypherToken _token, uint32 _hoursPerPeriod, uint256 _miningCoefficient, uint256 _lockedPeriodsCoefficient, uint16 _rewardedPeriods ) public Issuer( _token, _hoursPerPeriod, _miningCoefficient, _lockedPeriodsCoefficient, _rewardedPeriods ) { } function setValueToCheck(uint256 _valueToCheck) public { valueToCheck = _valueToCheck; } function verifyState(address _testTarget) public onlyOwner { super.verifyState(_testTarget); require(uint256(delegateGet(_testTarget, "valueToCheck()")) == valueToCheck); } }
12,568,103
[ 1, 8924, 364, 7769, 731, 15210, 326, 23959, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 23959, 58, 22, 9865, 353, 23959, 288, 203, 203, 565, 2254, 5034, 1071, 460, 18126, 31, 203, 203, 565, 3885, 12, 203, 3639, 20123, 17992, 21496, 1345, 389, 2316, 16, 203, 3639, 2254, 1578, 389, 16814, 2173, 5027, 16, 203, 3639, 2254, 5034, 389, 1154, 310, 4249, 25403, 16, 203, 3639, 2254, 5034, 389, 15091, 30807, 4249, 25403, 16, 203, 3639, 2254, 2313, 389, 266, 11804, 30807, 203, 565, 262, 203, 3639, 1071, 203, 3639, 23959, 12, 203, 5411, 389, 2316, 16, 203, 5411, 389, 16814, 2173, 5027, 16, 203, 5411, 389, 1154, 310, 4249, 25403, 16, 203, 5411, 389, 15091, 30807, 4249, 25403, 16, 203, 5411, 389, 266, 11804, 30807, 203, 3639, 262, 203, 565, 288, 203, 565, 289, 203, 203, 565, 445, 5524, 18126, 12, 11890, 5034, 389, 1132, 18126, 13, 1071, 288, 203, 3639, 460, 18126, 273, 389, 1132, 18126, 31, 203, 565, 289, 203, 203, 565, 445, 3929, 1119, 12, 2867, 389, 3813, 2326, 13, 1071, 1338, 5541, 288, 203, 3639, 2240, 18, 8705, 1119, 24899, 3813, 2326, 1769, 203, 3639, 2583, 12, 11890, 5034, 12, 22216, 967, 24899, 3813, 2326, 16, 315, 1132, 18126, 10031, 3719, 422, 460, 18126, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; // File: witnet-ethereum-block-relay/contracts/BlockRelayInterface.sol /** * @title Block Relay Interface * @notice Interface of a Block Relay to a Witnet network * It defines how to interact with the Block Relay in order to support: * - Retrieve last beacon information * - Verify proof of inclusions (PoIs) of data request and tally transactions * @author Witnet Foundation */ interface BlockRelayInterface { /// @notice Returns the beacon from the last inserted block. /// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility. /// @return last beacon in bytes function getLastBeacon() external view returns(bytes memory); /// @notice Returns the lastest epoch reported to the block relay. /// @return epoch function getLastEpoch() external view returns(uint256); /// @notice Returns the latest hash reported to the block relay /// @return blockhash function getLastHash() external view returns(uint256); /// @notice Verifies the validity of a data request PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view returns(bool); /// @notice Verifies the validity of a tally PoI against the Tally merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid tally PoI function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view returns(bool); /// @notice Verifies if the block relay can be upgraded /// @return true if contract is upgradable function isUpgradable(address _address) external view returns(bool); } // File: witnet-ethereum-block-relay/contracts/CentralizedBlockRelay.sol /** * @title Block relay contract * @notice Contract to store/read block headers from the Witnet network * @author Witnet Foundation */ contract CentralizedBlockRelay is BlockRelayInterface { struct MerkleRoots { // hash of the merkle root of the DRs in Witnet uint256 drHashMerkleRoot; // hash of the merkle root of the tallies in Witnet uint256 tallyHashMerkleRoot; } struct Beacon { // hash of the last block uint256 blockHash; // epoch of the last block uint256 epoch; } // Address of the block pusher address public witnet; // Last block reported Beacon public lastBlock; mapping (uint256 => MerkleRoots) public blocks; // Event emitted when a new block is posted to the contract event NewBlock(address indexed _from, uint256 _id); // Only the owner should be able to push blocks modifier isOwner() { require(msg.sender == witnet, "Sender not authorized"); // If it is incorrect here, it reverts. _; // Otherwise, it continues. } // Ensures block exists modifier blockExists(uint256 _id){ require(blocks[_id].drHashMerkleRoot!=0, "Non-existing block"); _; } // Ensures block does not exist modifier blockDoesNotExist(uint256 _id){ require(blocks[_id].drHashMerkleRoot==0, "The block already existed"); _; } constructor() public{ // Only the contract deployer is able to push blocks witnet = msg.sender; } /// @dev Read the beacon of the last block inserted /// @return bytes to be signed by bridge nodes function getLastBeacon() external view override returns(bytes memory) { return abi.encodePacked(lastBlock.blockHash, lastBlock.epoch); } /// @notice Returns the lastest epoch reported to the block relay. /// @return epoch function getLastEpoch() external view override returns(uint256) { return lastBlock.epoch; } /// @notice Returns the latest hash reported to the block relay /// @return blockhash function getLastHash() external view override returns(uint256) { return lastBlock.blockHash; } /// @dev Verifies the validity of a PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) returns(bool) { uint256 drMerkleRoot = blocks[_blockHash].drHashMerkleRoot; return(verifyPoi( _poi, drMerkleRoot, _index, _element)); } /// @dev Verifies the validity of a PoI against the tally merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the element /// @return true or false depending the validity function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) returns(bool) { uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot; return(verifyPoi( _poi, tallyMerkleRoot, _index, _element)); } /// @dev Verifies if the contract is upgradable /// @return true if the contract upgradable function isUpgradable(address _address) external view override returns(bool) { if (_address == witnet) { return true; } return false; } /// @dev Post new block into the block relay /// @param _blockHash Hash of the block header /// @param _epoch Witnet epoch to which the block belongs to /// @param _drMerkleRoot Merkle root belonging to the data requests /// @param _tallyMerkleRoot Merkle root belonging to the tallies function postNewBlock( uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot) external isOwner blockDoesNotExist(_blockHash) { lastBlock.blockHash = _blockHash; lastBlock.epoch = _epoch; blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot; blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot; emit NewBlock(witnet, _blockHash); } /// @dev Retrieve the requests-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header /// @return Requests-only merkle root hash in the block header. function readDrMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].drHashMerkleRoot; } /// @dev Retrieve the tallies-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header. /// @return tallies-only merkle root hash in the block header. function readTallyMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].tallyHashMerkleRoot; } /// @dev Verifies the validity of a PoI /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _root the merkle root /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyPoi( uint256[] memory _poi, uint256 _root, uint256 _index, uint256 _element) private pure returns(bool) { uint256 tree = _element; uint256 index = _index; // We want to prove that the hash of the _poi and the _element is equal to _root // For knowing if concatenate to the left or the right we check the parity of the the index for (uint i = 0; i < _poi.length; i++) { if (index%2 == 0) { tree = uint256(sha256(abi.encodePacked(tree, _poi[i]))); } else { tree = uint256(sha256(abi.encodePacked(_poi[i], tree))); } index = index >> 1; } return _root == tree; } } // File: witnet-ethereum-block-relay/contracts/BlockRelayProxy.sol /** * @title Block Relay Proxy * @notice Contract to act as a proxy between the Witnet Bridge Interface and the block relay * @dev More information can be found here * DISCLAIMER: this is a work in progress, meaning the contract could be voulnerable to attacks * @author Witnet Foundation */ contract BlockRelayProxy { // Address of the current controller address internal blockRelayAddress; // Current interface to the controller BlockRelayInterface internal blockRelayInstance; struct ControllerInfo { // last epoch seen by a controller uint256 lastEpoch; // address of the controller address blockRelayController; } // array containing the information about controllers ControllerInfo[] internal controllers; modifier notIdentical(address _newAddress) { require(_newAddress != blockRelayAddress, "The provided Block Relay instance address is already in use"); _; } constructor(address _blockRelayAddress) public { // Initialize the first epoch pointing to the first controller controllers.push(ControllerInfo({lastEpoch: 0, blockRelayController: _blockRelayAddress})); blockRelayAddress = _blockRelayAddress; blockRelayInstance = BlockRelayInterface(_blockRelayAddress); } /// @notice Returns the beacon from the last inserted block. /// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility. /// @return last beacon in bytes function getLastBeacon() external view returns(bytes memory) { return blockRelayInstance.getLastBeacon(); } /// @notice Returns the last Wtinet epoch known to the block relay instance. /// @return The last epoch is used in the WRB to avoid reusage of PoI in a data request. function getLastEpoch() external view returns(uint256) { return blockRelayInstance.getLastEpoch(); } /// @notice Verifies the validity of a data request PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _epoch the epoch of the blockchash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _epoch, uint256 _index, uint256 _element) external view returns(bool) { address controller = getController(_epoch); return BlockRelayInterface(controller).verifyDrPoi( _poi, _blockHash, _index, _element); } /// @notice Verifies the validity of a tally PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _epoch the epoch of the blockchash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _epoch, uint256 _index, uint256 _element) external view returns(bool) { address controller = getController(_epoch); return BlockRelayInterface(controller).verifyTallyPoi( _poi, _blockHash, _index, _element); } /// @notice Upgrades the block relay if the current one is upgradeable /// @param _newAddress address of the new block relay to upgrade function upgradeBlockRelay(address _newAddress) external notIdentical(_newAddress) { // Check if the controller is upgradeable require(blockRelayInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation"); // Get last epoch seen by the replaced controller uint256 epoch = blockRelayInstance.getLastEpoch(); // Get the length of last epochs seen by the different controllers uint256 n = controllers.length; // If the the last epoch seen by the replaced controller is lower than the one already anotated e.g. 0 // just update the already anotated epoch with the new address, ignoring the previously inserted controller // Else, anotate the epoch from which the new controller should start receiving blocks if (epoch < controllers[n-1].lastEpoch) { controllers[n-1].blockRelayController = _newAddress; } else { controllers.push(ControllerInfo({lastEpoch: epoch+1, blockRelayController: _newAddress})); } // Update instance blockRelayAddress = _newAddress; blockRelayInstance = BlockRelayInterface(_newAddress); } /// @notice Gets the controller associated with the BR controller corresponding to the epoch provided /// @param _epoch the epoch to work with function getController(uint256 _epoch) public view returns(address _controller) { // Get length of all last epochs seen by controllers uint256 n = controllers.length; // Go backwards until we find the controller having that blockhash for (uint i = n; i > 0; i--) { if (_epoch >= controllers[i-1].lastEpoch) { return (controllers[i-1].blockRelayController); } } } } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // File: elliptic-curve-solidity/contracts/EllipticCurve.sol /** * @title Elliptic Curve Library * @dev Library providing arithmetic operations over elliptic curves. * @author Witnet Foundation */ library EllipticCurve { /// @dev Modular euclidean inverse of a number (mod p). /// @param _x The number /// @param _pp The modulus /// @return q such that x*q = 1 (mod _pp) function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) { require(_x != 0 && _x != _pp && _pp != 0, "Invalid number"); uint256 q = 0; uint256 newT = 1; uint256 r = _pp; uint256 newR = _x; uint256 t; while (newR != 0) { t = r / newR; (q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp)); (r, newR) = (newR, r - t * newR ); } return q; } /// @dev Modular exponentiation, b^e % _pp. /// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol /// @param _base base /// @param _exp exponent /// @param _pp modulus /// @return r such that r = b**e (mod _pp) function expMod(uint256 _base, uint256 _exp, uint256 _pp) internal pure returns (uint256) { require(_pp!=0, "Modulus is zero"); if (_base == 0) return 0; if (_exp == 0) return 1; uint256 r = 1; uint256 bit = 2 ** 255; assembly { for { } gt(bit, 0) { }{ r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, bit)))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), _pp) bit := div(bit, 16) } } return r; } /// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1). /// @param _x coordinate x /// @param _y coordinate y /// @param _z coordinate z /// @param _pp the modulus /// @return (x', y') affine coordinates function toAffine( uint256 _x, uint256 _y, uint256 _z, uint256 _pp) internal pure returns (uint256, uint256) { uint256 zInv = invMod(_z, _pp); uint256 zInv2 = mulmod(zInv, zInv, _pp); uint256 x2 = mulmod(_x, zInv2, _pp); uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp); return (x2, y2); } /// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf). /// @param _prefix parity byte (0x02 even, 0x03 odd) /// @param _x coordinate x /// @param _aa constant of curve /// @param _bb constant of curve /// @param _pp the modulus /// @return y coordinate y function deriveY( uint8 _prefix, uint256 _x, uint256 _aa, uint256 _bb, uint256 _pp) internal pure returns (uint256) { require(_prefix == 0x02 || _prefix == 0x03, "Invalid compressed EC point prefix"); // x^3 + ax + b uint256 y2 = addmod(mulmod(_x, mulmod(_x, _x, _pp), _pp), addmod(mulmod(_x, _aa, _pp), _bb, _pp), _pp); y2 = expMod(y2, (_pp + 1) / 4, _pp); // uint256 cmp = yBit ^ y_ & 1; uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2; return y; } /// @dev Check whether point (x,y) is on curve defined by a, b, and _pp. /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _aa constant of curve /// @param _bb constant of curve /// @param _pp the modulus /// @return true if x,y in the curve, false else function isOnCurve( uint _x, uint _y, uint _aa, uint _bb, uint _pp) internal pure returns (bool) { if (0 == _x || _x == _pp || 0 == _y || _y == _pp) { return false; } // y^2 uint lhs = mulmod(_y, _y, _pp); // x^3 uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp); if (_aa != 0) { // x^3 + a*x rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp); } if (_bb != 0) { // x^3 + a*x + b rhs = addmod(rhs, _bb, _pp); } return lhs == rhs; } /// @dev Calculate inverse (x, -y) of point (x, y). /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _pp the modulus /// @return (x, -y) function ecInv( uint256 _x, uint256 _y, uint256 _pp) internal pure returns (uint256, uint256) { return (_x, (_pp - _y) % _pp); } /// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates. /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _x2 coordinate x of P2 /// @param _y2 coordinate y of P2 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = P1+P2 in affine coordinates function ecAdd( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { uint x = 0; uint y = 0; uint z = 0; // Double if x1==x2 else add if (_x1==_x2) { (x, y, z) = jacDouble( _x1, _y1, 1, _aa, _pp); } else { (x, y, z) = jacAdd( _x1, _y1, 1, _x2, _y2, 1, _pp); } // Get back to affine return toAffine( x, y, z, _pp); } /// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates. /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _x2 coordinate x of P2 /// @param _y2 coordinate y of P2 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = P1-P2 in affine coordinates function ecSub( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { // invert square (uint256 x, uint256 y) = ecInv(_x2, _y2, _pp); // P1-square return ecAdd( _x1, _y1, x, y, _aa, _pp); } /// @dev Multiply point (x1, y1, z1) times d in affine coordinates. /// @param _k scalar to multiply /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = d*P in affine coordinates function ecMul( uint256 _k, uint256 _x, uint256 _y, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { // Jacobian multiplication (uint256 x1, uint256 y1, uint256 z1) = jacMul( _k, _x, _y, 1, _aa, _pp); // Get back to affine return toAffine( x1, y1, z1, _pp); } /// @dev Adds two points (x1, y1, z1) and (x2 y2, z2). /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _z1 coordinate z of P1 /// @param _x2 coordinate x of square /// @param _y2 coordinate y of square /// @param _z2 coordinate z of square /// @param _pp the modulus /// @return (qx, qy, qz) P1+square in Jacobian function jacAdd( uint256 _x1, uint256 _y1, uint256 _z1, uint256 _x2, uint256 _y2, uint256 _z2, uint256 _pp) internal pure returns (uint256, uint256, uint256) { if ((_x1==0)&&(_y1==0)) return (_x2, _y2, _z2); if ((_x2==0)&&(_y2==0)) return (_x1, _y1, _z1); // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5 uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3 zs[0] = mulmod(_z1, _z1, _pp); zs[1] = mulmod(_z1, zs[0], _pp); zs[2] = mulmod(_z2, _z2, _pp); zs[3] = mulmod(_z2, zs[2], _pp); // u1, s1, u2, s2 zs = [ mulmod(_x1, zs[2], _pp), mulmod(_y1, zs[3], _pp), mulmod(_x2, zs[0], _pp), mulmod(_y2, zs[1], _pp) ]; // In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used require(zs[0] != zs[2], "Invalid data"); uint[4] memory hr; //h hr[0] = addmod(zs[2], _pp - zs[0], _pp); //r hr[1] = addmod(zs[3], _pp - zs[1], _pp); //h^2 hr[2] = mulmod(hr[0], hr[0], _pp); // h^3 hr[3] = mulmod(hr[2], hr[0], _pp); // qx = -h^3 -2u1h^2+r^2 uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp); qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp); // qy = -s1*z1*h^3+r(u1*h^2 -x^3) uint256 qy = mulmod(hr[1], addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp), _pp); qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp); // qz = h*z1*z2 uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp); return(qx, qy, qz); } /// @dev Doubles a points (x, y, z). /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _z coordinate z of P1 /// @param _pp the modulus /// @param _aa the a scalar in the curve equation /// @return (qx, qy, qz) 2P in Jacobian function jacDouble( uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) internal pure returns (uint256, uint256, uint256) { if (_z == 0) return (_x, _y, _z); uint256[3] memory square; // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5 // Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4) square[0] = mulmod(_x, _x, _pp); //x1^2 square[1] = mulmod(_y, _y, _pp); //y1^2 square[2] = mulmod(_z, _z, _pp); //z1^2 // s uint s = mulmod(4, mulmod(_x, square[1], _pp), _pp); // m uint m = addmod(mulmod(3, square[0], _pp), mulmod(_aa, mulmod(square[2], square[2], _pp), _pp), _pp); // qx uint256 qx = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp); // qy = -8*y1^4 + M(S-T) uint256 qy = addmod(mulmod(m, addmod(s, _pp - qx, _pp), _pp), _pp - mulmod(8, mulmod(square[1], square[1], _pp), _pp), _pp); // qz = 2*y1*z1 uint256 qz = mulmod(2, mulmod(_y, _z, _pp), _pp); return (qx, qy, qz); } /// @dev Multiply point (x, y, z) times d. /// @param _d scalar to multiply /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _z coordinate z of P1 /// @param _aa constant of curve /// @param _pp the modulus /// @return (qx, qy, qz) d*P1 in Jacobian function jacMul( uint256 _d, uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) internal pure returns (uint256, uint256, uint256) { uint256 remaining = _d; uint256[3] memory point; point[0] = _x; point[1] = _y; point[2] = _z; uint256 qx = 0; uint256 qy = 0; uint256 qz = 1; if (_d == 0) { return (qx, qy, qz); } // Double and add algorithm while (remaining != 0) { if ((remaining & 1) != 0) { (qx, qy, qz) = jacAdd( qx, qy, qz, point[0], point[1], point[2], _pp); } remaining = remaining / 2; (point[0], point[1], point[2]) = jacDouble( point[0], point[1], point[2], _aa, _pp); } return (qx, qy, qz); } } // File: vrf-solidity/contracts/VRF.sol /** * @title Verifiable Random Functions (VRF) * @notice Library verifying VRF proofs using the `Secp256k1` curve and the `SHA256` hash function. * @dev This library follows the algorithms described in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04) and [RFC6979](https://tools.ietf.org/html/rfc6979). * It supports the _SECP256K1_SHA256_TAI_ cipher suite, i.e. the aforementioned algorithms using `SHA256` and the `Secp256k1` curve. * @author Witnet Foundation */ library VRF { /** * Secp256k1 parameters */ // Generator coordinate `x` of the EC curve uint256 public constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; // Generator coordinate `y` of the EC curve uint256 public constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; // Constant `a` of EC equation uint256 public constant AA = 0; // Constant `b` of EC equation uint256 public constant BB = 7; // Prime number of the curve uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // Order of the curve uint256 public constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; /// @dev Public key derivation from private key. /// @param _d The scalar /// @param _x The coordinate x /// @param _y The coordinate y /// @return (qx, qy) The derived point function derivePoint(uint256 _d, uint256 _x, uint256 _y) internal pure returns (uint256, uint256) { return EllipticCurve.ecMul( _d, _x, _y, AA, PP ); } /// @dev Function to derive the `y` coordinate given the `x` coordinate and the parity byte (`0x03` for odd `y` and `0x04` for even `y`). /// @param _yByte The parity byte following the ec point compressed format /// @param _x The coordinate `x` of the point /// @return The coordinate `y` of the point function deriveY(uint8 _yByte, uint256 _x) internal pure returns (uint256) { return EllipticCurve.deriveY( _yByte, _x, AA, BB, PP); } /// @dev Computes the VRF hash output as result of the digest of a ciphersuite-dependent prefix /// concatenated with the gamma point /// @param _gammaX The x-coordinate of the gamma EC point /// @param _gammaY The y-coordinate of the gamma EC point /// @return The VRF hash ouput as shas256 digest function gammaToHash(uint256 _gammaX, uint256 _gammaY) internal pure returns (bytes32) { bytes memory c = abi.encodePacked( // Cipher suite code (SECP256K1-SHA256-TAI is 0xFE) uint8(0xFE), // 0x01 uint8(0x03), // Compressed Gamma Point encodePoint(_gammaX, _gammaY)); return sha256(c); } /// @dev VRF verification by providing the public key, the message and the VRF proof. /// This function computes several elliptic curve operations which may lead to extensive gas consumption. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @return true, if VRF proof is valid function verify(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (bool) { // Step 2: Hash to try and increment (outputs a hashed value, a finite EC point in G) uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); // Step 3: U = s*B - c*Y (where B is the generator) (uint256 uPointX, uint256 uPointY) = ecMulSubMul( _proof[3], GX, GY, _proof[2], _publicKey[0], _publicKey[1]); // Step 4: V = s*H - c*Gamma (uint256 vPointX, uint256 vPointY) = ecMulSubMul( _proof[3], hPoint[0], hPoint[1], _proof[2], _proof[0],_proof[1]); // Step 5: derived c from hash points(...) bytes16 derivedC = hashPoints( hPoint[0], hPoint[1], _proof[0], _proof[1], uPointX, uPointY, vPointX, vPointY); // Step 6: Check validity c == c' return uint128(derivedC) == _proof[2]; } /// @dev VRF fast verification by providing the public key, the message, the VRF proof and several intermediate elliptic curve points that enable the verification shortcut. /// This function leverages the EVM's `ecrecover` precompile to verify elliptic curve multiplications by decreasing the security from 32 to 20 bytes. /// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @param _uPoint The `u` EC point defined as `U = s*B - c*Y` /// @param _vComponents The components required to compute `v` as `V = s*H - c*Gamma` /// @return true, if VRF proof is valid function fastVerify( uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message, uint256[2] memory _uPoint, uint256[4] memory _vComponents) internal pure returns (bool) { // Step 2: Hash to try and increment -> hashed value, a finite EC point in G uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); // Step 3 & Step 4: // U = s*B - c*Y (where B is the generator) // V = s*H - c*Gamma if (!ecMulSubMulVerify( _proof[3], _proof[2], _publicKey[0], _publicKey[1], _uPoint[0], _uPoint[1]) || !ecMulVerify( _proof[3], hPoint[0], hPoint[1], _vComponents[0], _vComponents[1]) || !ecMulVerify( _proof[2], _proof[0], _proof[1], _vComponents[2], _vComponents[3]) ) { return false; } (uint256 vPointX, uint256 vPointY) = EllipticCurve.ecSub( _vComponents[0], _vComponents[1], _vComponents[2], _vComponents[3], AA, PP); // Step 5: derived c from hash points(...) bytes16 derivedC = hashPoints( hPoint[0], hPoint[1], _proof[0], _proof[1], _uPoint[0], _uPoint[1], vPointX, vPointY); // Step 6: Check validity c == c' return uint128(derivedC) == _proof[2]; } /// @dev Decode VRF proof from bytes /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` function decodeProof(bytes memory _proof) internal pure returns (uint[4] memory) { require(_proof.length == 81, "Malformed VRF proof"); uint8 gammaSign; uint256 gammaX; uint128 c; uint256 s; assembly { gammaSign := mload(add(_proof, 1)) gammaX := mload(add(_proof, 33)) c := mload(add(_proof, 49)) s := mload(add(_proof, 81)) } uint256 gammaY = deriveY(gammaSign, gammaX); return [ gammaX, gammaY, c, s]; } /// @dev Decode EC point from bytes /// @param _point The EC point as bytes /// @return The point as `[point-x, point-y]` function decodePoint(bytes memory _point) internal pure returns (uint[2] memory) { require(_point.length == 33, "Malformed compressed EC point"); uint8 sign; uint256 x; assembly { sign := mload(add(_point, 1)) x := mload(add(_point, 33)) } uint256 y = deriveY(sign, x); return [x, y]; } /// @dev Compute the parameters (EC points) required for the VRF fast verification function. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])` function computeFastVerifyParams(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (uint256[2] memory, uint256[4] memory) { // Requirements for Step 3: U = s*B - c*Y (where B is the generator) uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); (uint256 uPointX, uint256 uPointY) = ecMulSubMul( _proof[3], GX, GY, _proof[2], _publicKey[0], _publicKey[1]); // Requirements for Step 4: V = s*H - c*Gamma (uint256 sHX, uint256 sHY) = derivePoint(_proof[3], hPoint[0], hPoint[1]); (uint256 cGammaX, uint256 cGammaY) = derivePoint(_proof[2], _proof[0], _proof[1]); return ( [uPointX, uPointY], [ sHX, sHY, cGammaX, cGammaY ]); } /// @dev Function to convert a `Hash(PK|DATA)` to a point in the curve as defined in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04). /// Used in Step 2 of VRF verification function. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _message The message used for computing the VRF /// @return The hash point in affine cooridnates function hashToTryAndIncrement(uint256[2] memory _publicKey, bytes memory _message) internal pure returns (uint, uint) { // Step 1: public key to bytes // Step 2: V = cipher_suite | 0x01 | public_key_bytes | message | ctr bytes memory c = abi.encodePacked( // Cipher suite code (SECP256K1-SHA256-TAI is 0xFE) uint8(254), // 0x01 uint8(1), // Public Key encodePoint(_publicKey[0], _publicKey[1]), // Message _message); // Step 3: find a valid EC point // Loop over counter ctr starting at 0x00 and do hash for (uint8 ctr = 0; ctr < 256; ctr++) { // Counter update // c[cLength-1] = byte(ctr); bytes32 sha = sha256(abi.encodePacked(c, ctr)); // Step 4: arbitraty string to point and check if it is on curve uint hPointX = uint256(sha); uint hPointY = deriveY(2, hPointX); if (EllipticCurve.isOnCurve( hPointX, hPointY, AA, BB, PP)) { // Step 5 (omitted): calculate H (cofactor is 1 on secp256k1) // If H is not "INVALID" and cofactor > 1, set H = cofactor * H return (hPointX, hPointY); } } revert("No valid point was found"); } /// @dev Function to hash a certain set of points as specified in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04). /// Used in Step 5 of VRF verification function. /// @param _hPointX The coordinate `x` of point `H` /// @param _hPointY The coordinate `y` of point `H` /// @param _gammaX The coordinate `x` of the point `Gamma` /// @param _gammaX The coordinate `y` of the point `Gamma` /// @param _uPointX The coordinate `x` of point `U` /// @param _uPointY The coordinate `y` of point `U` /// @param _vPointX The coordinate `x` of point `V` /// @param _vPointY The coordinate `y` of point `V` /// @return The first half of the digest of the points using SHA256 function hashPoints( uint256 _hPointX, uint256 _hPointY, uint256 _gammaX, uint256 _gammaY, uint256 _uPointX, uint256 _uPointY, uint256 _vPointX, uint256 _vPointY) internal pure returns (bytes16) { bytes memory c = abi.encodePacked( // Ciphersuite 0xFE uint8(254), // Prefix 0x02 uint8(2), // Points to Bytes encodePoint(_hPointX, _hPointY), encodePoint(_gammaX, _gammaY), encodePoint(_uPointX, _uPointY), encodePoint(_vPointX, _vPointY) ); // Hash bytes and truncate bytes32 sha = sha256(c); bytes16 half1; assembly { let freemem_pointer := mload(0x40) mstore(add(freemem_pointer,0x00), sha) half1 := mload(add(freemem_pointer,0x00)) } return half1; } /// @dev Encode an EC point to bytes /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @return The point coordinates as bytes function encodePoint(uint256 _x, uint256 _y) internal pure returns (bytes memory) { uint8 prefix = uint8(2 + (_y % 2)); return abi.encodePacked(prefix, _x); } /// @dev Substracts two key derivation functionsas `s1*A - s2*B`. /// @param _scalar1 The scalar `s1` /// @param _a1 The `x` coordinate of point `A` /// @param _a2 The `y` coordinate of point `A` /// @param _scalar2 The scalar `s2` /// @param _b1 The `x` coordinate of point `B` /// @param _b2 The `y` coordinate of point `B` /// @return The derived point in affine cooridnates function ecMulSubMul( uint256 _scalar1, uint256 _a1, uint256 _a2, uint256 _scalar2, uint256 _b1, uint256 _b2) internal pure returns (uint256, uint256) { (uint256 m1, uint256 m2) = derivePoint(_scalar1, _a1, _a2); (uint256 n1, uint256 n2) = derivePoint(_scalar2, _b1, _b2); (uint256 r1, uint256 r2) = EllipticCurve.ecSub( m1, m2, n1, n2, AA, PP); return (r1, r2); } /// @dev Verify an Elliptic Curve multiplication of the form `(qx,qy) = scalar*(x,y)` by using the precompiled `ecrecover` function. /// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes. /// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 /// @param _scalar The scalar of the point multiplication /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @param _qx The coordinate `x` of the multiplication result /// @param _qy The coordinate `y` of the multiplication result /// @return true, if first 20 bytes match function ecMulVerify( uint256 _scalar, uint256 _x, uint256 _y, uint256 _qx, uint256 _qy) internal pure returns(bool) { address result = ecrecover( 0, _y % 2 != 0 ? 28 : 27, bytes32(_x), bytes32(mulmod(_scalar, _x, NN))); return pointToAddress(_qx, _qy) == result; } /// @dev Verify an Elliptic Curve operation of the form `Q = scalar1*(gx,gy) - scalar2*(x,y)` by using the precompiled `ecrecover` function, where `(gx,gy)` is the generator of the EC. /// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes. /// Based on SolCrypto library: https://github.com/HarryR/solcrypto /// @param _scalar1 The scalar of the multiplication of `(gx,gy)` /// @param _scalar2 The scalar of the multiplication of `(x,y)` /// @param _x The coordinate `x` of the point to be mutiply by `scalar2` /// @param _y The coordinate `y` of the point to be mutiply by `scalar2` /// @param _qx The coordinate `x` of the equation result /// @param _qy The coordinate `y` of the equation result /// @return true, if first 20 bytes match function ecMulSubMulVerify( uint256 _scalar1, uint256 _scalar2, uint256 _x, uint256 _y, uint256 _qx, uint256 _qy) internal pure returns(bool) { uint256 scalar1 = (NN - _scalar1) % NN; scalar1 = mulmod(scalar1, _x, NN); uint256 scalar2 = (NN - _scalar2) % NN; address result = ecrecover( bytes32(scalar1), _y % 2 != 0 ? 28 : 27, bytes32(_x), bytes32(mulmod(scalar2, _x, NN))); return pointToAddress(_qx, _qy) == result; } /// @dev Gets the address corresponding to the EC point digest (keccak256), i.e. the first 20 bytes of the digest. /// This function is used for performing a fast EC multiplication verification. /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @return The address of the EC point digest (keccak256) function pointToAddress(uint256 _x, uint256 _y) internal pure returns(address) { return address(uint256(keccak256(abi.encodePacked(_x, _y))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } } // File: witnet-ethereum-bridge/contracts/ActiveBridgeSetLib.sol /** * @title Active Bridge Set (ABS) library * @notice This library counts the number of bridges that were active recently. */ library ActiveBridgeSetLib { // Number of Ethereum blocks during which identities can be pushed into a single activity slot uint8 public constant CLAIM_BLOCK_PERIOD = 8; // Number of activity slots in the ABS uint8 public constant ACTIVITY_LENGTH = 100; struct ActiveBridgeSet { // Mapping of activity slots with participating identities mapping (uint16 => address[]) epochIdentities; // Mapping of identities with their participation count mapping (address => uint16) identityCount; // Number of identities in the Active Bridge Set (consolidated during `ACTIVITY_LENGTH`) uint32 activeIdentities; // Number of identities for the next activity slot (to be updated in the next activity slot) uint32 nextActiveIdentities; // Last used block number during an activity update uint256 lastBlockNumber; } modifier validBlockNumber(uint256 _blockFromArguments, uint256 _blockFromContractState) { require (_blockFromArguments >= _blockFromContractState, "The provided block is older than the last updated block"); _; } /// @dev Updates activity in Witnet without requiring protocol participation. /// @param _abs The Active Bridge Set structure to be updated. /// @param _blockNumber The block number up to which the activity should be updated. function updateActivity(ActiveBridgeSet storage _abs, uint256 _blockNumber) internal validBlockNumber(_blockNumber, _abs.lastBlockNumber) { (uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber); // Avoid gas cost if ABS is up to date require( updateABS( _abs, currentSlot, lastSlot, overflow ), "The ABS was already up to date"); _abs.lastBlockNumber = _blockNumber; } /// @dev Pushes activity updates through protocol activities (implying insertion of identity). /// @param _abs The Active Bridge Set structure to be updated. /// @param _address The address pushing the activity. /// @param _blockNumber The block number up to which the activity should be updated. function pushActivity(ActiveBridgeSet storage _abs, address _address, uint256 _blockNumber) internal validBlockNumber(_blockNumber, _abs.lastBlockNumber) returns (bool success) { (uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber); // Update ABS and if it was already up to date, check if identities already counted if ( updateABS( _abs, currentSlot, lastSlot, overflow )) { _abs.lastBlockNumber = _blockNumber; } else { // Check if address was already counted as active identity in this current activity slot uint256 epochIdsLength = _abs.epochIdentities[currentSlot].length; for (uint256 i; i < epochIdsLength; i++) { if (_abs.epochIdentities[currentSlot][i] == _address) { return false; } } } // Update current activity slot with identity: // 1. Add currentSlot to `epochIdentities` with address // 2. If count = 0, increment by 1 `nextActiveIdentities` // 3. Increment by 1 the count of the identity _abs.epochIdentities[currentSlot].push(_address); if (_abs.identityCount[_address] == 0) { _abs.nextActiveIdentities++; } _abs.identityCount[_address]++; return true; } /// @dev Checks if an address is a member of the ABS. /// @param _abs The Active Bridge Set structure from the Witnet Requests Board. /// @param _address The address to check. /// @return true if address is member of ABS. function absMembership(ActiveBridgeSet storage _abs, address _address) internal view returns (bool) { return _abs.identityCount[_address] > 0; } /// @dev Gets the slots of the last block seen by the ABS provided and the block number provided. /// @param _abs The Active Bridge Set structure containing the last block. /// @param _blockNumber The block number from which to get the current slot. /// @return (currentSlot, lastSlot, overflow), where overflow implies the block difference &gt; CLAIM_BLOCK_PERIOD* ACTIVITY_LENGTH. function getSlots(ActiveBridgeSet storage _abs, uint256 _blockNumber) private view returns (uint8, uint8, bool) { // Get current activity slot number uint8 currentSlot = uint8((_blockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH); // Get last actitivy slot number uint8 lastSlot = uint8((_abs.lastBlockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH); // Check if there was an activity slot overflow // `ACTIVITY_LENGTH` is changed to `uint16` here to ensure the multiplication doesn't overflow silently bool overflow = (_blockNumber - _abs.lastBlockNumber) >= CLAIM_BLOCK_PERIOD * uint16(ACTIVITY_LENGTH); return (currentSlot, lastSlot, overflow); } /// @dev Updates the provided ABS according to the slots provided. /// @param _abs The Active Bridge Set to be updated. /// @param _currentSlot The current slot. /// @param _lastSlot The last slot seen by the ABS. /// @param _overflow Whether the current slot has overflown the last slot. /// @return True if update occurred. function updateABS( ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot, bool _overflow) private returns (bool) { // If there are more than `ACTIVITY_LENGTH` slots empty => remove entirely the ABS if (_overflow) { flushABS(_abs, _lastSlot, _lastSlot); // If ABS are not up to date => fill previous activity slots with empty activities } else if (_currentSlot != _lastSlot) { flushABS(_abs, _currentSlot, _lastSlot); } else { return false; } return true; } /// @dev Flushes the provided ABS record between lastSlot and currentSlot. /// @param _abs The Active Bridge Set to be flushed. /// @param _currentSlot The current slot. function flushABS(ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot) private { // For each slot elapsed, remove identities and update `nextActiveIdentities` count for (uint16 slot = (_lastSlot + 1) % ACTIVITY_LENGTH ; slot != _currentSlot ; slot = (slot + 1) % ACTIVITY_LENGTH) { flushSlot(_abs, slot); } // Update current activity slot flushSlot(_abs, _currentSlot); _abs.activeIdentities = _abs.nextActiveIdentities; } /// @dev Flushes a slot of the provided ABS. /// @param _abs The Active Bridge Set to be flushed. /// @param _slot The slot to be flushed. function flushSlot(ActiveBridgeSet storage _abs, uint16 _slot) private { // For a given slot, go through all identities to flush them uint256 epochIdsLength = _abs.epochIdentities[_slot].length; for (uint256 id = 0; id < epochIdsLength; id++) { flushIdentity(_abs, _abs.epochIdentities[_slot][id]); } delete _abs.epochIdentities[_slot]; } /// @dev Decrements the appearance counter of an identity from the provided ABS. If the counter reaches 0, the identity is flushed. /// @param _abs The Active Bridge Set to be flushed. /// @param _address The address to be flushed. function flushIdentity(ActiveBridgeSet storage _abs, address _address) private { require(absMembership(_abs, _address), "The identity address is already out of the ARS"); // Decrement the count of an identity, and if it reaches 0, delete it and update `nextActiveIdentities`count _abs.identityCount[_address]--; if (_abs.identityCount[_address] == 0) { delete _abs.identityCount[_address]; _abs.nextActiveIdentities--; } } } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardInterface.sol /** * @title Witnet Requests Board Interface * @notice Interface of a Witnet Request Board (WRB) * It defines how to interact with the WRB in order to support: * - Post and upgrade a data request * - Read the result of a dr * @author Witnet Foundation */ interface WitnetRequestsBoardInterface { /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256); /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable; /// @dev Retrieves the DR hash of the id from the WRB. /// @param _id The unique identifier of the data request. /// @return The hash of the DR function readDrHash (uint256 _id) external view returns(uint256); /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR function readResult (uint256 _id) external view returns(bytes memory); /// @notice Verifies if the block relay can be upgraded. /// @return true if contract is upgradable. function isUpgradable(address _address) external view returns(bool); } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoard.sol /** * @title Witnet Requests Board * @notice Contract to bridge requests to Witnet. * @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network. * The result of the requests will be posted back to this contract by the bridge nodes too. * @author Witnet Foundation */ contract WitnetRequestsBoard is WitnetRequestsBoardInterface { using ActiveBridgeSetLib for ActiveBridgeSetLib.ActiveBridgeSet; // Expiration period after which a Witnet Request can be claimed again uint256 public constant CLAIM_EXPIRATION = 13; struct DataRequest { bytes dr; uint256 inclusionReward; uint256 tallyReward; bytes result; // Block number at which the DR was claimed for the last time uint256 blockNumber; uint256 drHash; address payable pkhClaim; } // Owner of the Witnet Request Board address public witnet; // Block Relay proxy prividing verification functions BlockRelayProxy public blockRelay; // Witnet Requests within the board DataRequest[] public requests; // Set of recently active bridges ActiveBridgeSetLib.ActiveBridgeSet public abs; // Replication factor for Active Bridge Set identities uint8 public repFactor; // Event emitted when a new DR is posted event PostedRequest(address indexed _from, uint256 _id); // Event emitted when a DR inclusion proof is posted event IncludedRequest(address indexed _from, uint256 _id); // Event emitted when a result proof is posted event PostedResult(address indexed _from, uint256 _id); // Ensures the reward is not greater than the value modifier payingEnough(uint256 _value, uint256 _tally) { require(_value >= _tally, "Transaction value needs to be equal or greater than tally reward"); _; } // Ensures the poe is valid modifier poeValid( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) { require( verifyPoe( _poe, _publicKey, _uPoint, _vPointHelpers), "Not a valid PoE"); _; } // Ensures signature (sign(msg.sender)) is valid modifier validSignature( uint256[2] memory _publicKey, bytes memory addrSignature) { require(verifySig(abi.encodePacked(msg.sender), _publicKey, addrSignature), "Not a valid signature"); _; } // Ensures the DR inclusion proof has not been reported yet modifier drNotIncluded(uint256 _id) { require(requests[_id].drHash == 0, "DR already included"); _; } // Ensures the DR inclusion has been already reported modifier drIncluded(uint256 _id) { require(requests[_id].drHash != 0, "DR not yet included"); _; } // Ensures the result has not been reported yet modifier resultNotIncluded(uint256 _id) { require(requests[_id].result.length == 0, "Result already included"); _; } // Ensures the VRF is valid modifier vrfValid( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) virtual { require( VRF.fastVerify( _publicKey, _poe, getLastBeacon(), _uPoint, _vPointHelpers), "Not a valid VRF"); _; } // Ensures the address belongs to the active bridge set modifier absMember(address _address) { require(abs.absMembership(_address), "Not a member of the ABS"); _; } /** * @notice Include an address to specify the Witnet Block Relay and a replication factor. * @param _blockRelayAddress BlockRelayProxy address. * @param _repFactor replication factor. */ constructor(address _blockRelayAddress, uint8 _repFactor) public { blockRelay = BlockRelayProxy(_blockRelayAddress); witnet = msg.sender; // Insert an empty request so as to initialize the requests array with length > 0 DataRequest memory request; requests.push(request); repFactor = _repFactor; } /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _serialized The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _serialized, uint256 _tallyReward) external payable payingEnough(msg.value, _tallyReward) override returns(uint256) { // The initial length of the `requests` array will become the ID of the request for everything related to the WRB uint256 id = requests.length; // Create a new `DataRequest` object and initialize all the non-default fields DataRequest memory request; request.dr = _serialized; request.inclusionReward = SafeMath.sub(msg.value, _tallyReward); request.tallyReward = _tallyReward; // Push the new request into the contract state requests.push(request); // Let observers know that a new request has been posted emit PostedRequest(msg.sender, id); return id; } /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable payingEnough(msg.value, _tallyReward) resultNotIncluded(_id) override { if (requests[_id].drHash != 0) { require( msg.value == _tallyReward, "Txn value should equal result reward argument (request reward already paid)" ); requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward); } else { requests[_id].inclusionReward = SafeMath.add(requests[_id].inclusionReward, msg.value - _tallyReward); requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward); } } /// @dev Checks if the data requests from a list are claimable or not. /// @param _ids The list of data request identifiers to be checked. /// @return An array of booleans indicating if data requests are claimable or not. function checkDataRequestsClaimability(uint256[] calldata _ids) external view returns (bool[] memory) { uint256 idsLength = _ids.length; bool[] memory validIds = new bool[](idsLength); for (uint i = 0; i < idsLength; i++) { uint256 index = _ids[i]; validIds[i] = (dataRequestCanBeClaimed(requests[index])) && requests[index].drHash == 0 && index < requests.length && requests[index].result.length == 0; } return validIds; } /// @dev Presents a proof of inclusion to prove that the request was posted into Witnet so as to unlock the inclusion reward that was put aside for the claiming identity (public key hash). /// @param _id The unique identifier of the data request. /// @param _poi A proof of inclusion proving that the data request appears listed in one recent block in Witnet. /// @param _index The index in the merkle tree. /// @param _blockHash The hash of the block in which the data request was inserted. /// @param _epoch The epoch in which the blockHash was created. function reportDataRequestInclusion( uint256 _id, uint256[] calldata _poi, uint256 _index, uint256 _blockHash, uint256 _epoch) external drNotIncluded(_id) { // Check the data request has been claimed require(dataRequestCanBeClaimed(requests[_id]) == false, "Data Request has not yet been claimed"); uint256 drOutputHash = uint256(sha256(requests[_id].dr)); uint256 drHash = uint256(sha256(abi.encodePacked(drOutputHash, _poi[0]))); // Update the state upon which this function depends before the external call requests[_id].drHash = drHash; require( blockRelay.verifyDrPoi( _poi, _blockHash, _epoch, _index, drOutputHash), "Invalid PoI"); requests[_id].pkhClaim.transfer(requests[_id].inclusionReward); // Push requests[_id].pkhClaim to abs abs.pushActivity(requests[_id].pkhClaim, block.number); emit IncludedRequest(msg.sender, _id); } /// @dev Reports the result of a data request in Witnet. /// @param _id The unique identifier of the data request. /// @param _poi A proof of inclusion proving that the data in _result has been acknowledged by the Witnet network as being the final result for the data request by putting in a tally transaction inside a Witnet block. /// @param _index The position of the tally transaction in the tallies-only merkle tree in the Witnet block. /// @param _blockHash The hash of the block in which the result (tally) was inserted. /// @param _epoch The epoch in which the blockHash was created. /// @param _result The result itself as bytes. function reportResult( uint256 _id, uint256[] calldata _poi, uint256 _index, uint256 _blockHash, uint256 _epoch, bytes calldata _result) external drIncluded(_id) resultNotIncluded(_id) absMember(msg.sender) { // Ensures the result byes do not have zero length // This would not be a valid encoding with CBOR and could trigger a reentrancy attack require(_result.length != 0, "Result has zero length"); // Update the state upon which this function depends before the external call requests[_id].result = _result; uint256 resHash = uint256(sha256(abi.encodePacked(requests[_id].drHash, _result))); require( blockRelay.verifyTallyPoi( _poi, _blockHash, _epoch, _index, resHash), "Invalid PoI"); msg.sender.transfer(requests[_id].tallyReward); emit PostedResult(msg.sender, _id); } /// @dev Retrieves the bytes of the serialization of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the data request as bytes. function readDataRequest(uint256 _id) external view returns(bytes memory) { require(requests.length > _id, "Id not found"); return requests[_id].dr; } /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR function readResult(uint256 _id) external view override returns(bytes memory) { require(requests.length > _id, "Id not found"); return requests[_id].result; } /// @dev Retrieves hash of the data request transaction in Witnet. /// @param _id The unique identifier of the data request. /// @return The hash of the DataRequest transaction in Witnet. function readDrHash(uint256 _id) external view override returns(uint256) { require(requests.length > _id, "Id not found"); return requests[_id].drHash; } /// @dev Returns the number of data requests in the WRB. /// @return the number of data requests in the WRB. function requestsCount() external view returns(uint256) { return requests.length; } /// @notice Wrapper around the decodeProof from VRF library. /// @dev Decode VRF proof from bytes. /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. /// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. function decodeProof(bytes calldata _proof) external pure returns (uint[4] memory) { return VRF.decodeProof(_proof); } /// @notice Wrapper around the decodePoint from VRF library. /// @dev Decode EC point from bytes. /// @param _point The EC point as bytes. /// @return The point as `[point-x, point-y]`. function decodePoint(bytes calldata _point) external pure returns (uint[2] memory) { return VRF.decodePoint(_point); } /// @dev Wrapper around the computeFastVerifyParams from VRF library. /// @dev Compute the parameters (EC points) required for the VRF fast verification function.. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`. /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. /// @param _message The message (in bytes) used for computing the VRF. /// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`. function computeFastVerifyParams(uint256[2] calldata _publicKey, uint256[4] calldata _proof, bytes calldata _message) external pure returns (uint256[2] memory, uint256[4] memory) { return VRF.computeFastVerifyParams(_publicKey, _proof, _message); } /// @dev Updates the ABS activity with the block number provided. /// @param _blockNumber update the ABS until this block number. function updateAbsActivity(uint256 _blockNumber) external { require (_blockNumber <= block.number, "The provided block number has not been reached"); abs.updateActivity(_blockNumber); } /// @dev Verifies if the contract is upgradable. /// @return true if the contract upgradable. function isUpgradable(address _address) external view override returns(bool) { if (_address == witnet) { return true; } return false; } /// @dev Claim drs to be posted to Witnet by the node. /// @param _ids Data request ids to be claimed. /// @param _poe PoE claiming eligibility. /// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y. /// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma. function claimDataRequests( uint256[] memory _ids, uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers, bytes memory addrSignature) public validSignature(_publicKey, addrSignature) poeValid(_poe,_publicKey, _uPoint,_vPointHelpers) returns(bool) { for (uint i = 0; i < _ids.length; i++) { require( dataRequestCanBeClaimed(requests[_ids[i]]), "One of the listed data requests was already claimed" ); requests[_ids[i]].pkhClaim = msg.sender; requests[_ids[i]].blockNumber = block.number; } return true; } /// @dev Read the beacon of the last block inserted. /// @return bytes to be signed by the node as PoE. function getLastBeacon() public view virtual returns(bytes memory) { return blockRelay.getLastBeacon(); } /// @dev Claim drs to be posted to Witnet by the node. /// @param _poe PoE claiming eligibility. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`. /// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y. /// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma. function verifyPoe( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) internal view vrfValid(_poe,_publicKey, _uPoint,_vPointHelpers) returns(bool) { uint256 vrf = uint256(VRF.gammaToHash(_poe[0], _poe[1])); // True if vrf/(2^{256} -1) <= repFactor/abs.activeIdentities if (abs.activeIdentities < repFactor) { return true; } // We rewrote it as vrf <= ((2^{256} -1)/abs.activeIdentities)*repFactor to gain efficiency if (vrf <= ((~uint256(0)/abs.activeIdentities)*repFactor)) { return true; } return false; } /// @dev Verifies the validity of a signature. /// @param _message message to be verified. /// @param _publicKey public key of the signer as `[pubKey-x, pubKey-y]`. /// @param _addrSignature the signature to verify asas r||s||v. /// @return true or false depending the validity. function verifySig( bytes memory _message, uint256[2] memory _publicKey, bytes memory _addrSignature) internal pure returns(bool) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_addrSignature, 0x20)) s := mload(add(_addrSignature, 0x40)) v := byte(0, mload(add(_addrSignature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return false; } if (v != 0 && v != 1) { return false; } v = 28 - v; bytes32 msgHash = sha256(_message); address hashedKey = VRF.pointToAddress(_publicKey[0], _publicKey[1]); return ecrecover( msgHash, v, r, s) == hashedKey; } function dataRequestCanBeClaimed(DataRequest memory _request) private view returns (bool) { return (_request.blockNumber == 0 || block.number - _request.blockNumber > CLAIM_EXPIRATION) && _request.drHash == 0 && _request.result.length == 0; } } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardProxy.sol /** * @title Block Relay Proxy * @notice Contract to act as a proxy between the Witnet Bridge Interface and the Block Relay. * @author Witnet Foundation */ contract WitnetRequestsBoardProxy { // Address of the Witnet Request Board contract that is currently being used address public witnetRequestsBoardAddress; // Struct if the information of each controller struct ControllerInfo { // Address of the Controller address controllerAddress; // The lastId of the previous Controller uint256 lastId; } // Last id of the WRB controller uint256 internal currentLastId; // Instance of the current WitnetRequestBoard WitnetRequestsBoardInterface internal witnetRequestsBoardInstance; // Array with the controllers that have been used in the Proxy ControllerInfo[] internal controllers; modifier notIdentical(address _newAddress) { require(_newAddress != witnetRequestsBoardAddress, "The provided Witnet Requests Board instance address is already in use"); _; } /** * @notice Include an address to specify the Witnet Request Board. * @param _witnetRequestsBoardAddress WitnetRequestBoard address. */ constructor(address _witnetRequestsBoardAddress) public { // Initialize the first epoch pointing to the first controller controllers.push(ControllerInfo({controllerAddress: _witnetRequestsBoardAddress, lastId: 0})); witnetRequestsBoardAddress = _witnetRequestsBoardAddress; witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_witnetRequestsBoardAddress); } /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256) { uint256 n = controllers.length; uint256 offset = controllers[n - 1].lastId; // Update the currentLastId with the id in the controller plus the offSet currentLastId = witnetRequestsBoardInstance.postDataRequest{value: msg.value}(_dr, _tallyReward) + offset; return currentLastId; } /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable { address wrbAddress; uint256 wrbOffset; (wrbAddress, wrbOffset) = getController(_id); return witnetRequestsBoardInstance.upgradeDataRequest{value: msg.value}(_id - wrbOffset, _tallyReward); } /// @dev Retrieves the DR hash of the id from the WRB. /// @param _id The unique identifier of the data request. /// @return The hash of the DR. function readDrHash (uint256 _id) external view returns(uint256) { // Get the address and the offset of the corresponding to id address wrbAddress; uint256 offsetWrb; (wrbAddress, offsetWrb) = getController(_id); // Return the result of the DR readed in the corresponding Controller with its own id WitnetRequestsBoardInterface wrbWithDrHash; wrbWithDrHash = WitnetRequestsBoardInterface(wrbAddress); uint256 drHash = wrbWithDrHash.readDrHash(_id - offsetWrb); return drHash; } /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR. function readResult(uint256 _id) external view returns(bytes memory) { // Get the address and the offset of the corresponding to id address wrbAddress; uint256 offSetWrb; (wrbAddress, offSetWrb) = getController(_id); // Return the result of the DR in the corresponding Controller with its own id WitnetRequestsBoardInterface wrbWithResult; wrbWithResult = WitnetRequestsBoardInterface(wrbAddress); return wrbWithResult.readResult(_id - offSetWrb); } /// @notice Upgrades the Witnet Requests Board if the current one is upgradeable. /// @param _newAddress address of the new block relay to upgrade. function upgradeWitnetRequestsBoard(address _newAddress) public notIdentical(_newAddress) { // Require the WRB is upgradable require(witnetRequestsBoardInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation"); // Map the currentLastId to the corresponding witnetRequestsBoardAddress and add it to controllers controllers.push(ControllerInfo({controllerAddress: _newAddress, lastId: currentLastId})); // Upgrade the WRB witnetRequestsBoardAddress = _newAddress; witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_newAddress); } /// @notice Gets the controller from an Id. /// @param _id id of a Data Request from which we get the controller. function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) { // Check id is bigger than 0 require(_id > 0, "Non-existent controller for id 0"); uint256 n = controllers.length; // If the id is bigger than the lastId of a Controller, read the result in that Controller for (uint i = n; i > 0; i--) { if (_id > controllers[i - 1].lastId) { return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId); } } } } // File: witnet-ethereum-bridge/contracts/BufferLib.sol /** * @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface * @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will * start with the byte that goes right after the last one in the previous read. * @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some * theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded. */ library BufferLib { struct Buffer { bytes data; uint32 cursor; } // Ensures we access an existing index in an array modifier notOutOfBounds(uint32 index, uint256 length) { require(index < length, "Tried to read from a consumed Buffer (must rewind it first)"); _; } /** * @notice Read and consume a certain amount of bytes from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @param _length How many bytes to read and consume from the buffer. * @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position. */ function read(Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) { // Make sure not to read out of the bounds of the original bytes require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading"); // Create a new `bytes memory destination` value bytes memory destination = new bytes(_length); bytes memory source = _buffer.data; uint32 offset = _buffer.cursor; // Get raw pointers for source and destination uint sourcePointer; uint destinationPointer; assembly { sourcePointer := add(add(source, 32), offset) destinationPointer := add(destination, 32) } // Copy `_length` bytes from source to destination memcpy(destinationPointer, sourcePointer, uint(_length)); // Move the cursor forward by `_length` bytes seek(_buffer, _length, true); return destination; } /** * @notice Read and consume the next byte from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @return The next byte in the buffer counting from the cursor position. */ function next(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (byte) { // Return the byte at the position marked by the cursor and advance the cursor all at once return _buffer.data[_buffer.cursor++]; } /** * @notice Move the inner cursor of the buffer to a relative or absolute position. * @param _buffer An instance of `BufferLib.Buffer`. * @param _offset How many bytes to move the cursor forward. * @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the * buffer (`true`). * @return The final position of the cursor (will equal `_offset` if `_relative` is `false`). */ // solium-disable-next-line security/no-assign-params function seek(Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) { // Deal with relative offsets if (_relative) { require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking"); _offset += _buffer.cursor; } // Make sure not to read out of the bounds of the original bytes require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking"); _buffer.cursor = _offset; return _buffer.cursor; } /** * @notice Move the inner cursor a number of bytes forward. * @dev This is a simple wrapper around the relative offset case of `seek()`. * @param _buffer An instance of `BufferLib.Buffer`. * @param _relativeOffset How many bytes to move the cursor forward. * @return The final position of the cursor. */ function seek(Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) { return seek(_buffer, _relativeOffset, true); } /** * @notice Move the inner cursor back to the first byte in the buffer. * @param _buffer An instance of `BufferLib.Buffer`. */ function rewind(Buffer memory _buffer) internal pure { _buffer.cursor = 0; } /** * @notice Read and consume the next byte from the buffer as an `uint8`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint8` value of the next byte in the buffer counting from the cursor position. */ function readUint8(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint8 value; assembly { value := mload(add(add(bytesValue, 1), offset)) } _buffer.cursor++; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an `uint16`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position. */ function readUint16(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint16 value; assembly { value := mload(add(add(bytesValue, 2), offset)) } _buffer.cursor += 2; return value; } /** * @notice Read and consume the next 4 bytes from the buffer as an `uint32`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readUint32(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint32 value; assembly { value := mload(add(add(bytesValue, 4), offset)) } _buffer.cursor += 4; return value; } /** * @notice Read and consume the next 8 bytes from the buffer as an `uint64`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position. */ function readUint64(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint64 value; assembly { value := mload(add(add(bytesValue, 8), offset)) } _buffer.cursor += 8; return value; } /** * @notice Read and consume the next 16 bytes from the buffer as an `uint128`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position. */ function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } _buffer.cursor += 16; return value; } /** * @notice Read and consume the next 32 bytes from the buffer as an `uint256`. * @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position. * @param _buffer An instance of `BufferLib.Buffer`. */ function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint256 value; assembly { value := mload(add(add(bytesValue, 32), offset)) } _buffer.cursor += 32; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an * `int32`. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16` * use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are * expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readFloat16(Buffer memory _buffer) internal pure returns (int32) { uint32 bytesValue = readUint16(_buffer); // Get bit at position 0 uint32 sign = bytesValue & 0x8000; // Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15; // Get bits 6 to 15 int32 significand = int32(bytesValue & 0x03ff); // Add 1024 to the fraction if the exponent is 0 if (exponent == 15) { significand |= 0x400; } // Compute `2 ^ exponent · (1 + fraction / 1024)` int32 result = 0; if (exponent >= 0) { result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10); } else { result = int32((((uint256(significand) | 0x400) * 10000) / (1 << uint256(- exponent))) >> 10); } // Make the result negative if the sign bit is not 0 if (sign != 0) { result *= - 1; } return result; } /** * @notice Copy bytes from one memory address into another. * @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms * of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE). * @param _dest Address of the destination memory. * @param _src Address to the source memory. * @param _len How many bytes to copy. */ // solium-disable-next-line security/no-assign-params function memcpy(uint _dest, uint _src, uint _len) private pure { // 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)) } } } // File: witnet-ethereum-bridge/contracts/CBOR.sol /** * @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation” * @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize * the gas cost of decoding them into a useful native type. * @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js * TODO: add support for Array (majorType = 4) * TODO: add support for Map (majorType = 5) * TODO: add support for Float32 (majorType = 7, additionalInformation = 26) * TODO: add support for Float64 (majorType = 7, additionalInformation = 27) */ library CBOR { using BufferLib for BufferLib.Buffer; uint64 constant internal UINT64_MAX = ~uint64(0); struct Value { BufferLib.Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /** * @notice Decode a `CBOR.Value` structure into a native `bytes` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `bytes` value. */ function decodeBytes(Value memory _cborValue) public pure returns(bytes memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory bytesData; // These checks look repetitive but the equivalent loop would be more expensive. uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT64_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT64_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); } } return bytesData; } else { return _cborValue.buffer.read(uint32(_cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a `fixed16` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16` * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeFixed16(Value memory _cborValue) public pure returns(int32) { require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `CBOR.Value` with majorType != 7"); require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `CBOR.Value` with additionalInformation != 25"); return _cborValue.buffer.readFloat16(); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value whose inner values follow the same convention. * as explained in `decodeFixed16`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeFixed16Array(Value memory _cborValue) public pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeFixed16(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `int128` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeInt128(Value memory _cborValue) public pure returns(int128) { if (_cborValue.majorType == 1) { uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); return int128(-1) - int128(length); } else if (_cborValue.majorType == 0) { // Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer // a uniform API for positive and negative numbers return int128(decodeUint64(_cborValue)); } revert("Tried to read `int128` from a `CBOR.Value` with majorType not 0 or 1"); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeInt128Array(Value memory _cborValue) public pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `string` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `string` value. */ function decodeString(Value memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a native `string[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `string[]` value. */ function decodeStringArray(Value memory _cborValue) public pure returns(string[] memory) { require(_cborValue.majorType == 4, "Tried to read `string[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); string[] memory array = new string[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeString(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `uint64` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64` value. */ function decodeUint64(Value memory _cborValue) public pure returns(uint64) { require(_cborValue.majorType == 0, "Tried to read `uint64` from a `CBOR.Value` with majorType != 0"); return readLength(_cborValue.buffer, _cborValue.additionalInformation); } /** * @notice Decode a `CBOR.Value` structure into a native `uint64[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64[]` value. */ function decodeUint64Array(Value memory _cborValue) public pure returns(uint64[] memory) { require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); uint64[] memory array = new uint64[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeUint64(item); } return array; } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is the main factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBytes(bytes memory _cborBytes) public pure returns(Value memory) { BufferLib.Buffer memory buffer = BufferLib.Buffer(_cborBytes, 0); return valueFromBuffer(buffer); } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _buffer A Buffer structure representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) { require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value"); uint8 initialByte; uint8 majorType = 255; uint8 additionalInformation; uint64 length; uint64 tag = UINT64_MAX; bool isTagged = true; while (isTagged) { // Extract basic CBOR properties from input bytes initialByte = _buffer.readUint8(); majorType = initialByte >> 5; additionalInformation = initialByte & 0x1f; // Early CBOR tag parsing. if (majorType == 6) { tag = readLength(_buffer, additionalInformation); } else { isTagged = false; } } require(majorType <= 7, "Invalid CBOR major type"); return CBOR.Value( _buffer, initialByte, majorType, additionalInformation, length, tag); } // Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the // value of the `additionalInformation` argument. function readLength(BufferLib.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) { if (additionalInformation < 24) { return additionalInformation; } if (additionalInformation == 24) { return _buffer.readUint8(); } if (additionalInformation == 25) { return _buffer.readUint16(); } if (additionalInformation == 26) { return _buffer.readUint32(); } if (additionalInformation == 27) { return _buffer.readUint64(); } if (additionalInformation == 31) { return UINT64_MAX; } revert("Invalid length encoding (non-existent additionalInformation value)"); } // Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming // as many bytes as specified by the first byte. function readIndefiniteStringLength(BufferLib.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) { uint8 initialByte = _buffer.readUint8(); if (initialByte == 0xff) { return UINT64_MAX; } uint64 length = readLength(_buffer, initialByte & 0x1f); require(length < UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length"); return length; } // Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness, // but it can be easily casted into a string with `string(result)`. // solium-disable-next-line security/no-assign-params function readText(BufferLib.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) { bytes memory result; for (uint64 index = 0; index < _length; index++) { uint8 value = _buffer.readUint8(); if (value & 0x80 != 0) { if (value < 0xe0) { value = (value & 0x1f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 1; } else if (value < 0xf0) { value = (value & 0x0f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 2; } else { value = (value & 0x0f) << 18 | (_buffer.readUint8() & 0x3f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 3; } } result = abi.encodePacked(result, value); } return result; } } // File: witnet-ethereum-bridge/contracts/Witnet.sol /** * @title A library for decoding Witnet request results * @notice The library exposes functions to check the Witnet request success. * and retrieve Witnet results from CBOR values into solidity types. */ library Witnet { using CBOR for CBOR.Value; /* STRUCTS */ struct Result { bool success; CBOR.Value cborValue; } /* ENUMS */ enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid RADON script. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, Size } /* Result impl's */ /** * @notice Decode raw CBOR bytes into a Result instance. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `Result` instance. */ function resultFromCborBytes(bytes calldata _cborBytes) external pure returns(Result memory) { CBOR.Value memory cborValue = CBOR.valueFromBytes(_cborBytes); return resultFromCborValue(cborValue); } /** * @notice Decode a CBOR value into a Result instance. * @param _cborValue An instance of `CBOR.Value`. * @return A `Result` instance. */ function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) { // Witnet uses CBOR tag 39 to represent RADON error code identifiers. // [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md bool success = _cborValue.tag != 39; return Result(success, _cborValue); } /** * @notice Tell if a Result is successful. * @param _result An instance of Result. * @return `true` if successful, `false` if errored. */ function isOk(Result memory _result) public pure returns(bool) { return _result.success; } /** * @notice Tell if a Result is errored. * @param _result An instance of Result. * @return `true` if errored, `false` if successful. */ function isError(Result memory _result) public pure returns(bool) { return !_result.success; } /** * @notice Decode a bytes value from a Result as a `bytes` value. * @param _result An instance of Result. * @return The `bytes` decoded from the Result. */ function asBytes(Result memory _result) public pure returns(bytes memory) { require(_result.success, "Tried to read bytes value from errored Result"); return _result.cborValue.decodeBytes(); } /** * @notice Decode an error code from a Result as a member of `ErrorCodes`. * @param _result An instance of `Result`. * @return The `CBORValue.Error memory` decoded from the Result. */ function asErrorCode(Result memory _result) public pure returns(ErrorCodes) { uint64[] memory error = asRawError(_result); return supportedErrorOrElseUnknown(error[0]); } /** * @notice Generate a suitable error message for a member of `ErrorCodes` and its corresponding arguments. * @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function * @param _result An instance of `Result`. * @return A tuple containing the `CBORValue.Error memory` decoded from the `Result`, plus a loggable error message. */ function asErrorMessage(Result memory _result) public pure returns(ErrorCodes, string memory) { uint64[] memory error = asRawError(_result); ErrorCodes errorCode = supportedErrorOrElseUnknown(error[0]); bytes memory errorMessage; if (errorCode == ErrorCodes.SourceScriptNotCBOR) { errorMessage = abi.encodePacked("Source script #", utoa(error[1]), " was not a valid CBOR value"); } else if (errorCode == ErrorCodes.SourceScriptNotArray) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not an Array of calls"); } else if (errorCode == ErrorCodes.SourceScriptNotRADON) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not a valid RADON script"); } else if (errorCode == ErrorCodes.RequestTooManySources) { errorMessage = abi.encodePacked("The request contained too many sources (", utoa(error[1]), ")"); } else if (errorCode == ErrorCodes.ScriptTooManyCalls) { errorMessage = abi.encodePacked( "Script #", utoa(error[2]), " from the ", stageName(error[1]), " stage contained too many calls (", utoa(error[3]), ")" ); } else if (errorCode == ErrorCodes.UnsupportedOperator) { errorMessage = abi.encodePacked( "Operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage is not supported" ); } else if (errorCode == ErrorCodes.HTTP) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved. Failed with HTTP error code: ", utoa(error[2] / 100), utoa(error[2] % 100 / 10), utoa(error[2] % 10) ); } else if (errorCode == ErrorCodes.RetrievalTimeout) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved because of a timeout." ); } else if (errorCode == ErrorCodes.Underflow) { errorMessage = abi.encodePacked( "Underflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.Overflow) { errorMessage = abi.encodePacked( "Overflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.DivisionByZero) { errorMessage = abi.encodePacked( "Division by zero at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else { errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")"); } return (errorCode, string(errorMessage)); } /** * @notice Decode a raw error from a `Result` as a `uint64[]`. * @param _result An instance of `Result`. * @return The `uint64[]` raw error as decoded from the `Result`. */ function asRawError(Result memory _result) public pure returns(uint64[] memory) { require(!_result.success, "Tried to read error code from successful Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Decode a fixed16 (half-precision) numeric value from a Result as an `int32` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asFixed16(Result memory _result) public pure returns(int32) { require(_result.success, "Tried to read `fixed16` value from errored Result"); return _result.cborValue.decodeFixed16(); } /** * @notice Decode an array of fixed16 values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asFixed16Array(Result memory _result) public pure returns(int128[] memory) { require(_result.success, "Tried to read `fixed16[]` value from errored Result"); return _result.cborValue.decodeFixed16Array(); } /** * @notice Decode a integer numeric value from a Result as an `int128` value. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asInt128(Result memory _result) public pure returns(int128) { require(_result.success, "Tried to read `int128` value from errored Result"); return _result.cborValue.decodeInt128(); } /** * @notice Decode an array of integer numeric values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asInt128Array(Result memory _result) public pure returns(int128[] memory) { require(_result.success, "Tried to read `int128[]` value from errored Result"); return _result.cborValue.decodeInt128Array(); } /** * @notice Decode a string value from a Result as a `string` value. * @param _result An instance of Result. * @return The `string` decoded from the Result. */ function asString(Result memory _result) public pure returns(string memory) { require(_result.success, "Tried to read `string` value from errored Result"); return _result.cborValue.decodeString(); } /** * @notice Decode an array of string values from a Result as a `string[]` value. * @param _result An instance of Result. * @return The `string[]` decoded from the Result. */ function asStringArray(Result memory _result) public pure returns(string[] memory) { require(_result.success, "Tried to read `string[]` value from errored Result"); return _result.cborValue.decodeStringArray(); } /** * @notice Decode a natural numeric value from a Result as a `uint64` value. * @param _result An instance of Result. * @return The `uint64` decoded from the Result. */ function asUint64(Result memory _result) public pure returns(uint64) { require(_result.success, "Tried to read `uint64` value from errored Result"); return _result.cborValue.decodeUint64(); } /** * @notice Decode an array of natural numeric values from a Result as a `uint64[]` value. * @param _result An instance of Result. * @return The `uint64[]` decoded from the Result. */ function asUint64Array(Result memory _result) public pure returns(uint64[] memory) { require(_result.success, "Tried to read `uint64[]` value from errored Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Convert a stage index number into the name of the matching Witnet request stage. * @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages. * @return The name of the matching stage. */ function stageName(uint64 _stageIndex) public pure returns(string memory) { if (_stageIndex == 0) { return "retrieval"; } else if (_stageIndex == 1) { return "aggregation"; } else if (_stageIndex == 2) { return "tally"; } else { return "unknown"; } } /** * @notice Get an `ErrorCodes` item from its `uint64` discriminant, or default to `ErrorCodes.Unknown` if it doesn't * exist. * @param _discriminant The numeric identifier of an error. * @return A member of `ErrorCodes`. */ function supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns(ErrorCodes) { if (_discriminant < uint8(ErrorCodes.Size)) { return ErrorCodes(_discriminant); } else { return ErrorCodes.Unknown; } } /** * @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its. * three less significant decimal values. * @param _u A `uint64` value. * @return The `string` representing its decimal value. */ function utoa(uint64 _u) private pure returns(string memory) { if (_u < 10) { bytes memory b1 = new bytes(1); b1[0] = byte(uint8(_u) + 48); return string(b1); } else if (_u < 100) { bytes memory b2 = new bytes(2); b2[0] = byte(uint8(_u / 10) + 48); b2[1] = byte(uint8(_u % 10) + 48); return string(b2); } else { bytes memory b3 = new bytes(3); b3[0] = byte(uint8(_u / 100) + 48); b3[1] = byte(uint8(_u % 100 / 10) + 48); b3[2] = byte(uint8(_u % 10) + 48); return string(b3); } } /** * @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values. * @param _u A `uint64` value. * @return The `string` representing its hexadecimal value. */ function utohex(uint64 _u) private pure returns(string memory) { bytes memory b2 = new bytes(2); uint8 d0 = uint8(_u / 16) + 48; uint8 d1 = uint8(_u % 16) + 48; if (d0 > 57) d0 += 7; if (d1 > 57) d1 += 7; b2[0] = byte(d0); b2[1] = byte(d1); return string(b2); } } // File: witnet-ethereum-bridge/contracts/Request.sol /** * @title The serialized form of a Witnet data request */ contract Request { bytes public bytecode; uint256 public id; /** * @dev A `Request` is constructed around a `bytes memory` value containing a well-formed Witnet data request serialized * using Protocol Buffers. However, we cannot verify its validity at this point. This implies that contracts using * the WRB should not be considered trustless before a valid Proof-of-Inclusion has been posted for the requests. * The hash of the request is computed in the constructor to guarantee consistency. Otherwise there could be a * mismatch and a data request could be resolved with the result of another. * @param _bytecode Witnet request in bytes. */ constructor(bytes memory _bytecode) public { bytecode = _bytecode; id = uint256(sha256(_bytecode)); } } // File: witnet-ethereum-bridge/contracts/UsingWitnet.sol /** * @title The UsingWitnet contract * @notice Contract writers can inherit this contract in order to create requests for the * Witnet network. */ contract UsingWitnet { using Witnet for Witnet.Result; WitnetRequestsBoardProxy internal wrb; /** * @notice Include an address to specify the WitnetRequestsBoard. * @param _wrb WitnetRequestsBoard address. */ constructor(address _wrb) public { wrb = WitnetRequestsBoardProxy(_wrb); } // Provides a convenient way for client contracts extending this to block the execution of the main logic of the // contract until a particular request has been successfully accepted into Witnet modifier witnetRequestAccepted(uint256 _id) { require(witnetCheckRequestAccepted(_id), "Witnet request is not yet accepted into the Witnet network"); _; } // Ensures that user-specified rewards are equal to the total transaction value to prevent users from burning any excess value modifier validRewards(uint256 _requestReward, uint256 _resultReward) { require(_requestReward + _resultReward >= _requestReward, "The sum of rewards overflows"); require(msg.value == _requestReward + _resultReward, "Transaction value should equal the sum of rewards"); _; } /** * @notice Send a new request to the Witnet network * @dev Call to `post_dr` function in the WitnetRequestsBoard contract * @param _request An instance of the `Request` contract * @param _requestReward Reward specified for the user which posts the request into Witnet * @param _resultReward Reward specified for the user which posts back the request result * @return Sequencial identifier for the request included in the WitnetRequestsBoard */ function witnetPostRequest(Request _request, uint256 _requestReward, uint256 _resultReward) internal validRewards(_requestReward, _resultReward) returns (uint256) { return wrb.postDataRequest.value(_requestReward + _resultReward)(_request.bytecode(), _resultReward); } /** * @notice Check if a request has been accepted into Witnet. * @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third. * parties) before this method returns `true`. * @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard. * @return A boolean telling if the request has been already accepted or not. `false` do not mean rejection, though. */ function witnetCheckRequestAccepted(uint256 _id) internal view returns (bool) { // Find the request in the uint256 drHash = wrb.readDrHash(_id); // If the hash of the data request transaction in Witnet is not the default, then it means that inclusion of the // request has been proven to the WRB. return drHash != 0; } /** * @notice Upgrade the rewards for a Data Request previously included. * @dev Call to `upgrade_dr` function in the WitnetRequestsBoard contract. * @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard. * @param _requestReward Reward specified for the user which posts the request into Witnet * @param _resultReward Reward specified for the user which post the Data Request result. */ function witnetUpgradeRequest(uint256 _id, uint256 _requestReward, uint256 _resultReward) internal validRewards(_requestReward, _resultReward) { wrb.upgradeDataRequest.value(msg.value)(_id, _resultReward); } /** * @notice Read the result of a resolved request. * @dev Call to `read_result` function in the WitnetRequestsBoard contract. * @param _id The sequential identifier of a request that was posted to Witnet. * @return The result of the request as an instance of `Result`. */ function witnetReadResult(uint256 _id) internal view returns (Witnet.Result memory) { return Witnet.resultFromCborBytes(wrb.readResult(_id)); } } // File: adomedianizer/contracts/IERC2362.sol /** * @dev EIP2362 Interface for pull oracles * https://github.com/tellor-io/EIP-2362 */ interface IERC2362 { /** * @dev Exposed function pertaining to EIP standards * @param _id bytes32 ID of the query * @return int,uint,uint returns the value, timestamp, and status code of query */ function valueFor(bytes32 _id) external view returns(int256,uint256,uint256); } // File: witnet-price-feeds-examples/contracts/requests/BitcoinPrice.sol // The bytecode of the BitcoinPrice request that will be sent to Witnet contract BitcoinPriceRequest is Request { constructor () Request(hex"0abb0108c3aafbf405123b122468747470733a2f2f7777772e6269747374616d702e6e65742f6170692f7469636b65722f1a13841877821864646c6173748218571903e8185b125c123168747470733a2f2f6170692e636f696e6465736b2e636f6d2f76312f6270692f63757272656e7470726963652e6a736f6e1a2786187782186663627069821866635553448218646a726174655f666c6f61748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/bitcoin_price_feed/BtcUsdPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the BitcoinPrice request that you created before // Your contract needs to inherit from UsingWitnet contract BtcUsdPriceFeed is UsingWitnet, IERC2362 { // The public Bitcoin price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is `keccak256("Price-BTC/USD-3")` bytes32 constant public BTCUSD3ID = bytes32(hex"637b7efb6b620736c247aaa282f3898914c0bef6c12faff0d3fe9d4bea783020"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new BitcoinPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != BTCUSD3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: witnet-price-feeds-examples/contracts/requests/EthPrice.sol // The bytecode of the EthPrice request that will be sent to Witnet contract EthPriceRequest is Request { constructor () Request(hex"0a850208d7affbf4051245122e68747470733a2f2f7777772e6269747374616d702e6e65742f6170692f76322f7469636b65722f6574687573642f1a13841877821864646c6173748218571903e8185b1247122068747470733a2f2f6170692e636f696e6361702e696f2f76322f6173736574731a238618778218616464617461821818018218646870726963655573648218571903e8185b1253122668747470733a2f2f6170692e636f696e70617072696b612e636f6d2f76312f7469636b6572731a29871876821818038218666671756f746573821866635553448218646570726963658218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/eth_price_feed/EthUsdPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the ethPrice request that you created before // Your contract needs to inherit from UsingWitnet contract EthUsdPriceFeed is UsingWitnet, IERC2362 { // The public eth price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is the ERC2362 identifier for a eth price feed, computed as `keccak256("Price-ETH/USD-3")` bytes32 constant public ETHUSD3ID = bytes32(hex"dfaa6f747f0f012e8f2069d6ecacff25f5cdf0258702051747439949737fc0b5"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new EthPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != ETHUSD3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: witnet-price-feeds-examples/contracts/requests/GoldPrice.sol // The bytecode of the GoldPrice request that will be sent to Witnet contract GoldPriceRequest is Request { constructor () Request(hex"0ab90308c3aafbf4051257123f68747470733a2f2f636f696e7965702e636f6d2f6170692f76312f3f66726f6d3d58415526746f3d455552266c616e673d657326666f726d61743d6a736f6e1a148418778218646570726963658218571903e8185b1253122b68747470733a2f2f646174612d6173672e676f6c6470726963652e6f72672f64625852617465732f4555521a24861877821861656974656d73821818008218646878617550726963658218571903e8185b1255123668747470733a2f2f7777772e6d7963757272656e63797472616e736665722e636f6d2f6170692f63757272656e742f5841552f4555521a1b851877821866646461746182186464726174658218571903e8185b129101125d68747470733a2f2f7777772e696e766572736f726f2e65732f6461746f732f3f706572696f643d3379656172267869676e6974655f636f64653d5841552663757272656e63793d455552267765696768745f756e69743d6f756e6365731a308518778218666a7461626c655f64617461821864736d6574616c5f70726963655f63757272656e748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/gold_price_feed/GoldEurPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the goldPrice request that you created before // Your contract needs to inherit from UsingWitnet contract GoldEurPriceFeed is UsingWitnet, IERC2362 { // The public gold price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is the ERC2362 identifier for a gold price feed, computed as `keccak256("Price-XAU/EUR-3")` bytes32 constant public XAUEUR3ID = bytes32(hex"68cba0705475e40c1ddbf7dc7c1ae4e7320ca094c4e118d1067c4dea5df28590"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new GoldPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != XAUEUR3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: contracts/Deployer.sol // Import witnet-ethereum-block-relay-contracts // Import the UsingWitnet library that enables interacting with Witnet // Import price feeds contract Deployer { } // File: contracts/Migrations.sol contract Migrations { address public owner; uint public lastCompletedMigration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint _completed) public restricted { lastCompletedMigration = _completed; } function upgrade(address _newAddress) public restricted { Migrations upgraded = Migrations(_newAddress); upgraded.setCompleted(lastCompletedMigration); } }
z1^2, z1^3, z2^2, z2^3
uint[4] memory zs;
901,068
[ 1, 94, 21, 66, 22, 16, 998, 21, 66, 23, 16, 998, 22, 66, 22, 16, 998, 22, 66, 23, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 63, 24, 65, 3778, 998, 87, 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 ]
pragma solidity 0.4.26; import './interfaces/IBancorXUpgrader.sol'; import './interfaces/IBancorX.sol'; import '../token/interfaces/ISmartTokenController.sol'; import '../utility/ContractRegistryClient.sol'; import '../utility/SafeMath.sol'; import '../utility/TokenHolder.sol'; import '../token/interfaces/ISmartToken.sol'; /** * @dev The BancorX contract allows cross chain token transfers. * * There are two processes that take place in the contract - * - Initiate a cross chain transfer to a target blockchain (locks tokens from the caller account on Ethereum) * - Report a cross chain transfer initiated on a source blockchain (releases tokens to an account on Ethereum) * * Reporting cross chain transfers works similar to standard multisig contracts, meaning that multiple * callers are required to report a transfer before tokens are released to the target account. */ contract BancorX is IBancorX, TokenHolder, ContractRegistryClient { using SafeMath for uint256; // represents a transaction on another blockchain where tokens were destroyed/locked struct Transaction { uint256 amount; bytes32 fromBlockchain; address to; uint8 numOfReports; bool completed; } uint16 public version = 3; uint256 public maxLockLimit; // the maximum amount of tokens that can be locked in one transaction uint256 public maxReleaseLimit; // the maximum amount of tokens that can be released in one transaction uint256 public minLimit; // the minimum amount of tokens that can be transferred in one transaction uint256 public prevLockLimit; // the lock limit *after* the last transaction uint256 public prevReleaseLimit; // the release limit *after* the last transaction uint256 public limitIncPerBlock; // how much the limit increases per block uint256 public prevLockBlockNumber; // the block number of the last lock transaction uint256 public prevReleaseBlockNumber; // the block number of the last release transaction uint256 public minRequiredReports; // minimum number of required reports to release tokens IERC20Token public token; // erc20 token or smart token bool public isSmartToken; // false - erc20 token; true - smart token bool public xTransfersEnabled = true; // true if x transfers are enabled, false if not bool public reportingEnabled = true; // true if reporting is enabled, false if not // txId -> Transaction mapping (uint256 => Transaction) public transactions; // xTransferId -> txId mapping (uint256 => uint256) public transactionIds; // txId -> reporter -> true if reporter already reported txId mapping (uint256 => mapping (address => bool)) public reportedTxs; // address -> true if address is reporter mapping (address => bool) public reporters; /** * @dev triggered when tokens are locked in smart contract * * @param _from wallet address that the tokens are locked from * @param _amount amount locked */ event TokensLock( address indexed _from, uint256 _amount ); /** * @dev triggered when tokens are released by the smart contract * * @param _to wallet address that the tokens are released to * @param _amount amount released */ event TokensRelease( address indexed _to, uint256 _amount ); /** * @dev triggered when xTransfer is successfully called * * @param _from wallet address that initiated the xtransfer * @param _toBlockchain target blockchain * @param _to target wallet * @param _amount transfer amount * @param _id xtransfer id */ event XTransfer( address indexed _from, bytes32 _toBlockchain, bytes32 indexed _to, uint256 _amount, uint256 _id ); /** * @dev triggered when report is successfully submitted * * @param _reporter reporter wallet * @param _fromBlockchain source blockchain * @param _txId tx id on the source blockchain * @param _to target wallet * @param _amount transfer amount * @param _xTransferId xtransfer id */ event TxReport( address indexed _reporter, bytes32 _fromBlockchain, uint256 _txId, address _to, uint256 _amount, uint256 _xTransferId ); /** * @dev triggered when final report is successfully submitted * * @param _to target wallet * @param _id xtransfer id */ event XTransferComplete( address _to, uint256 _id ); /** * @dev initializes a new BancorX instance * * @param _maxLockLimit maximum amount of tokens that can be locked in one transaction * @param _maxReleaseLimit maximum amount of tokens that can be released in one transaction * @param _minLimit minimum amount of tokens that can be transferred in one transaction * @param _limitIncPerBlock how much the limit increases per block * @param _minRequiredReports minimum number of reporters to report transaction before tokens can be released * @param _registry address of contract registry * @param _token erc20 token or smart token * @param _isSmartToken false - erc20 token; true - smart token */ constructor( uint256 _maxLockLimit, uint256 _maxReleaseLimit, uint256 _minLimit, uint256 _limitIncPerBlock, uint256 _minRequiredReports, IContractRegistry _registry, IERC20Token _token, bool _isSmartToken ) ContractRegistryClient(_registry) public { // the maximum limits, minimum limit, and limit increase per block maxLockLimit = _maxLockLimit; maxReleaseLimit = _maxReleaseLimit; minLimit = _minLimit; limitIncPerBlock = _limitIncPerBlock; minRequiredReports = _minRequiredReports; // previous limit is _maxLimit, and previous block number is current block number prevLockLimit = _maxLockLimit; prevReleaseLimit = _maxReleaseLimit; prevLockBlockNumber = block.number; prevReleaseBlockNumber = block.number; token = _token; isSmartToken = _isSmartToken; } // validates that the caller is a reporter modifier isReporter { require(reporters[msg.sender]); _; } // allows execution only when x transfers are enabled modifier whenXTransfersEnabled { require(xTransfersEnabled); _; } // allows execution only when reporting is enabled modifier whenReportingEnabled { require(reportingEnabled); _; } /** * @dev setter * * @param _maxLockLimit new maxLockLimit */ function setMaxLockLimit(uint256 _maxLockLimit) public ownerOnly { maxLockLimit = _maxLockLimit; } /** * @dev setter * * @param _maxReleaseLimit new maxReleaseLimit */ function setMaxReleaseLimit(uint256 _maxReleaseLimit) public ownerOnly { maxReleaseLimit = _maxReleaseLimit; } /** * @dev setter * * @param _minLimit new minLimit */ function setMinLimit(uint256 _minLimit) public ownerOnly { minLimit = _minLimit; } /** * @dev setter * * @param _limitIncPerBlock new limitIncPerBlock */ function setLimitIncPerBlock(uint256 _limitIncPerBlock) public ownerOnly { limitIncPerBlock = _limitIncPerBlock; } /** * @dev setter * * @param _minRequiredReports new minRequiredReports */ function setMinRequiredReports(uint256 _minRequiredReports) public ownerOnly { minRequiredReports = _minRequiredReports; } /** * @dev allows the owner to set/remove reporters * * @param _reporter reporter whos status is to be set * @param _active true if the reporter is approved, false otherwise */ function setReporter(address _reporter, bool _active) public ownerOnly { reporters[_reporter] = _active; } /** * @dev allows the owner enable/disable the xTransfer method * * @param _enable true to enable, false to disable */ function enableXTransfers(bool _enable) public ownerOnly { xTransfersEnabled = _enable; } /** * @dev allows the owner enable/disable the reportTransaction method * * @param _enable true to enable, false to disable */ function enableReporting(bool _enable) public ownerOnly { reportingEnabled = _enable; } /** * @dev upgrades the contract to the latest version * can only be called by the owner * note that the owner needs to call acceptOwnership on the new contract after the upgrade * * @param _reporters new list of reporters */ function upgrade(address[] _reporters) public ownerOnly { IBancorXUpgrader bancorXUpgrader = IBancorXUpgrader(addressOf(BANCOR_X_UPGRADER)); transferOwnership(bancorXUpgrader); bancorXUpgrader.upgrade(version, _reporters); acceptOwnership(); } /** * @dev claims tokens from msg.sender to be converted to tokens on another blockchain * * @param _toBlockchain blockchain on which tokens will be issued * @param _to address to send the tokens to * @param _amount the amount of tokens to transfer */ function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount) public whenXTransfersEnabled { // get the current lock limit uint256 currentLockLimit = getCurrentLockLimit(); // require that; minLimit <= _amount <= currentLockLimit require(_amount >= minLimit && _amount <= currentLockLimit); lockTokens(_amount); // set the previous lock limit and block number prevLockLimit = currentLockLimit.sub(_amount); prevLockBlockNumber = block.number; // emit XTransfer event with id of 0 emit XTransfer(msg.sender, _toBlockchain, _to, _amount, 0); } /** * @dev claims tokens from msg.sender to be converted to tokens on another blockchain * * @param _toBlockchain blockchain on which tokens will be issued * @param _to address to send the tokens to * @param _amount the amount of tokens to transfer * @param _id pre-determined unique (if non zero) id which refers to this transaction */ function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount, uint256 _id) public whenXTransfersEnabled { // get the current lock limit uint256 currentLockLimit = getCurrentLockLimit(); // require that; minLimit <= _amount <= currentLockLimit require(_amount >= minLimit && _amount <= currentLockLimit); lockTokens(_amount); // set the previous lock limit and block number prevLockLimit = currentLockLimit.sub(_amount); prevLockBlockNumber = block.number; // emit XTransfer event emit XTransfer(msg.sender, _toBlockchain, _to, _amount, _id); } /** * @dev allows reporter to report transaction which occured on another blockchain * * @param _fromBlockchain blockchain in which tokens were destroyed * @param _txId transactionId of transaction thats being reported * @param _to address to receive tokens * @param _amount amount of tokens destroyed on another blockchain * @param _xTransferId unique (if non zero) pre-determined id (unlike _txId which is determined after the transactions been mined) */ function reportTx( bytes32 _fromBlockchain, uint256 _txId, address _to, uint256 _amount, uint256 _xTransferId ) public isReporter whenReportingEnabled { // require that the transaction has not been reported yet by the reporter require(!reportedTxs[_txId][msg.sender]); // set reported as true reportedTxs[_txId][msg.sender] = true; Transaction storage txn = transactions[_txId]; // If the caller is the first reporter, set the transaction details if (txn.numOfReports == 0) { txn.to = _to; txn.amount = _amount; txn.fromBlockchain = _fromBlockchain; if (_xTransferId != 0) { // verify uniqueness of xTransfer id to prevent overwriting require(transactionIds[_xTransferId] == 0); transactionIds[_xTransferId] = _txId; } } else { // otherwise, verify transaction details require(txn.to == _to && txn.amount == _amount && txn.fromBlockchain == _fromBlockchain); if (_xTransferId != 0) { require(transactionIds[_xTransferId] == _txId); } } // increment the number of reports txn.numOfReports++; emit TxReport(msg.sender, _fromBlockchain, _txId, _to, _amount, _xTransferId); // if theres enough reports, try to release tokens if (txn.numOfReports >= minRequiredReports) { require(!transactions[_txId].completed); // set the transaction as completed transactions[_txId].completed = true; emit XTransferComplete(_to, _xTransferId); releaseTokens(_to, _amount); } } /** * @dev gets x transfer amount by xTransferId (not txId) * * @param _xTransferId unique (if non zero) pre-determined id (unlike _txId which is determined after the transactions been broadcasted) * @param _for address corresponding to xTransferId * * @return amount that was sent in xTransfer corresponding to _xTransferId */ function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256) { // xTransferId -> txId -> Transaction Transaction storage transaction = transactions[transactionIds[_xTransferId]]; // verify that the xTransferId is for _for require(transaction.to == _for); return transaction.amount; } /** * @dev method for calculating current lock limit * * @return the current maximum limit of tokens that can be locked */ function getCurrentLockLimit() public view returns (uint256) { // prevLockLimit + ((currBlockNumber - prevLockBlockNumber) * limitIncPerBlock) uint256 currentLockLimit = prevLockLimit.add(((block.number).sub(prevLockBlockNumber)).mul(limitIncPerBlock)); if (currentLockLimit > maxLockLimit) return maxLockLimit; return currentLockLimit; } /** * @dev method for calculating current release limit * * @return the current maximum limit of tokens that can be released */ function getCurrentReleaseLimit() public view returns (uint256) { // prevReleaseLimit + ((currBlockNumber - prevReleaseBlockNumber) * limitIncPerBlock) uint256 currentReleaseLimit = prevReleaseLimit.add(((block.number).sub(prevReleaseBlockNumber)).mul(limitIncPerBlock)); if (currentReleaseLimit > maxReleaseLimit) return maxReleaseLimit; return currentReleaseLimit; } /** * @dev claims and locks tokens from msg.sender to be converted to tokens on another blockchain * * @param _amount the amount of tokens to lock */ function lockTokens(uint256 _amount) private { if (isSmartToken) ISmartTokenController(ISmartToken(token).owner()).claimTokens(msg.sender, _amount); else token.transferFrom(msg.sender, address(this), _amount); emit TokensLock(msg.sender, _amount); } /** * @dev private method to release tokens held by the contract * * @param _to the address to release tokens to * @param _amount the amount of tokens to release */ function releaseTokens(address _to, uint256 _amount) private { // get the current release limit uint256 currentReleaseLimit = getCurrentReleaseLimit(); require(_amount >= minLimit && _amount <= currentReleaseLimit); // update the previous release limit and block number prevReleaseLimit = currentReleaseLimit.sub(_amount); prevReleaseBlockNumber = block.number; // no need to require, reverts on failure token.transfer(_to, _amount); emit TokensRelease(_to, _amount); } }
* @dev private method to release tokens held by the contract @param _to the address to release tokens to @param _amount the amount of tokens to release/ get the current release limit update the previous release limit and block number no need to require, reverts on failure
function releaseTokens(address _to, uint256 _amount) private { uint256 currentReleaseLimit = getCurrentReleaseLimit(); require(_amount >= minLimit && _amount <= currentReleaseLimit); prevReleaseLimit = currentReleaseLimit.sub(_amount); prevReleaseBlockNumber = block.number; token.transfer(_to, _amount); emit TokensRelease(_to, _amount); }
986,561
[ 1, 1152, 707, 358, 3992, 2430, 15770, 635, 326, 6835, 225, 389, 869, 1377, 326, 1758, 358, 3992, 2430, 358, 225, 389, 8949, 225, 326, 3844, 434, 2430, 358, 3992, 19, 336, 326, 783, 3992, 1800, 1089, 326, 2416, 3992, 1800, 471, 1203, 1300, 1158, 1608, 358, 2583, 16, 15226, 87, 603, 5166, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 3992, 5157, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 3238, 288, 203, 3639, 2254, 5034, 783, 7391, 3039, 273, 5175, 7391, 3039, 5621, 203, 203, 3639, 2583, 24899, 8949, 1545, 1131, 3039, 597, 389, 8949, 1648, 783, 7391, 3039, 1769, 203, 540, 203, 3639, 2807, 7391, 3039, 273, 783, 7391, 3039, 18, 1717, 24899, 8949, 1769, 203, 3639, 2807, 7391, 1768, 1854, 273, 1203, 18, 2696, 31, 203, 203, 3639, 1147, 18, 13866, 24899, 869, 16, 389, 8949, 1769, 203, 203, 3639, 3626, 13899, 7391, 24899, 869, 16, 389, 8949, 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 ]
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol
* @dev Changes the admin of the proxy. Emits an {IERC1967-AdminChanged} event./
function changeAdmin(address newAdmin) internal { emit AdminChanged(getAdmin(), newAdmin); _setAdmin(newAdmin); }
8,082,533
[ 1, 7173, 326, 3981, 434, 326, 2889, 18, 7377, 1282, 392, 288, 45, 654, 39, 3657, 9599, 17, 4446, 5033, 97, 871, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 4446, 12, 2867, 394, 4446, 13, 2713, 288, 203, 3639, 3626, 7807, 5033, 12, 588, 4446, 9334, 394, 4446, 1769, 203, 3639, 389, 542, 4446, 12, 2704, 4446, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-09-09 */ // File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 { 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"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ 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 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } } // File: @openzeppelin/contracts/token/ERC20/presets/ERC20PresetFixedSupply.sol pragma solidity ^0.8.0; /** * @dev {ERC20} token, including: * * - Preminted initial supply * - Ability for holders to burn (destroy) their tokens * - No access control mechanism (for minting/pausing) and hence no governance * * This contract uses {ERC20Burnable} to include burn capabilities - head to * its documentation for details. * * _Available since v3.4._ */ contract ERC20PresetFixedSupply is ERC20Burnable { /** * @dev Mints `initialSupply` amount of token and transfers them to `owner`. * * See {ERC20-constructor}. */ constructor( string memory name, string memory symbol, uint256 initialSupply, address owner ) ERC20(name, symbol) { _mint(owner, initialSupply); } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.8.0; contract MRSV is ERC20PresetFixedSupply, Ownable { // blocked address address[] public blockAddress; // contract pause or unpause bool public paused; constructor() ERC20PresetFixedSupply("Maison Reserve", "MRSV", 10**11 * 10**18, msg.sender) { } // add address to blocklist function addBlockAddress(address newAddress) public { blockAddress.push(newAddress); } // function for token transfer function tokenTransfer(address recept, uint256 amount) public { bool flag = false; for (uint key = 0; key < blockAddress.length; key++){ if (msg.sender == blockAddress[key] || recept == blockAddress[key]){ flag = true; break; } } require(flag == false, "Your address or receiving address is blocked!"); _transfer(msg.sender, recept, amount); } // function for pause smart contract function setPaused(bool _paused) public onlyOwner() { paused = _paused; } // pause all withdrawAll function withdrawAllMoney(address payable _to) public onlyOwner() { require(paused == false, "Contract Paused"); _to.transfer(address(this).balance); } } contract Proxy { address delegate; address owner = msg.sender; function upgradeDelegate(address newDelegateAddress) public { require(msg.sender == owner); delegate = newDelegateAddress; } }
pause all withdrawAll
function withdrawAllMoney(address payable _to) public onlyOwner() { require(paused == false, "Contract Paused"); _to.transfer(address(this).balance); }
15,445,747
[ 1, 19476, 777, 598, 9446, 1595, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 9446, 1595, 23091, 12, 2867, 8843, 429, 389, 869, 13, 1071, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 8774, 3668, 422, 629, 16, 315, 8924, 21800, 3668, 8863, 203, 3639, 389, 869, 18, 13866, 12, 2867, 12, 2211, 2934, 12296, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xd84F1fefe13E91C52C41998D06d9182e879cb649/sources/contracts/Tokens/StakingRewardFactory.sol
immutables the staking tokens for which the rewards contract has been deployed info about rewards for a particular staking token
contract StakingRewardsFactory is Ownable { address public rewardsToken; uint256 public stakingRewardsGenesis; address[] public stakingTokens; struct StakingRewardsInfo { address stakingRewards; uint256 rewardAmount; } mapping(address => StakingRewardsInfo) public stakingRewardsInfoByStakingToken; constructor(address _rewardsToken, uint256 _stakingRewardsGenesis) Ownable() { require(_stakingRewardsGenesis >= block.timestamp, 'StakingRewardsFactory::constructor: genesis too soon'); rewardsToken = _rewardsToken; stakingRewardsGenesis = _stakingRewardsGenesis; } function deploy( address stakingToken, uint256 rewardAmount, uint256 rewardsDuration ) public onlyOwner { require(rewardsDuration > 0, 'rewardsDuration=0'); StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken]; require(info.stakingRewards == address(0), 'StakingRewardsFactory::deploy: already deployed'); info.stakingRewards = address( new StakingRewards( address(this), rewardsToken, stakingToken, rewardsDuration, owner() ) ); info.rewardAmount = rewardAmount; stakingTokens.push(stakingToken); } function notifyRewardAmounts() public { require(stakingTokens.length > 0, 'StakingRewardsFactory::notifyRewardAmounts: called before any deploys'); for (uint256 i = 0; i < stakingTokens.length; i++) { notifyRewardAmount(stakingTokens[i]); } } function notifyRewardAmounts() public { require(stakingTokens.length > 0, 'StakingRewardsFactory::notifyRewardAmounts: called before any deploys'); for (uint256 i = 0; i < stakingTokens.length; i++) { notifyRewardAmount(stakingTokens[i]); } } function notifyRewardAmount(address stakingToken) public { require(block.timestamp >= stakingRewardsGenesis, 'StakingRewardsFactory::notifyRewardAmount: not ready'); StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken]; require(info.stakingRewards != address(0), 'StakingRewardsFactory::notifyRewardAmount: not deployed'); if (info.rewardAmount > 0) { uint256 rewardAmount = info.rewardAmount; info.rewardAmount = 0; require( IERC20(rewardsToken).transfer(info.stakingRewards, rewardAmount), 'StakingRewardsFactory::notifyRewardAmount: transfer failed' ); StakingRewards(info.stakingRewards).notifyRewardAmount(rewardAmount); } } function notifyRewardAmount(address stakingToken) public { require(block.timestamp >= stakingRewardsGenesis, 'StakingRewardsFactory::notifyRewardAmount: not ready'); StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken]; require(info.stakingRewards != address(0), 'StakingRewardsFactory::notifyRewardAmount: not deployed'); if (info.rewardAmount > 0) { uint256 rewardAmount = info.rewardAmount; info.rewardAmount = 0; require( IERC20(rewardsToken).transfer(info.stakingRewards, rewardAmount), 'StakingRewardsFactory::notifyRewardAmount: transfer failed' ); StakingRewards(info.stakingRewards).notifyRewardAmount(rewardAmount); } } function emergencyWithdraw(address _token) external onlyOwner { IERC20(_token).transfer(msg.sender, IERC20(_token).balanceOf(address(this))); } }
670,265
[ 1, 381, 10735, 1538, 326, 384, 6159, 2430, 364, 1492, 326, 283, 6397, 6835, 711, 2118, 19357, 1123, 2973, 283, 6397, 364, 279, 6826, 384, 6159, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 934, 6159, 17631, 14727, 1733, 353, 14223, 6914, 288, 203, 565, 1758, 1071, 283, 6397, 1345, 31, 203, 565, 2254, 5034, 1071, 384, 6159, 17631, 14727, 7642, 16786, 31, 203, 203, 565, 1758, 8526, 1071, 384, 6159, 5157, 31, 203, 203, 203, 203, 203, 565, 1958, 934, 6159, 17631, 14727, 966, 288, 203, 3639, 1758, 384, 6159, 17631, 14727, 31, 203, 3639, 2254, 5034, 19890, 6275, 31, 203, 565, 289, 203, 203, 203, 565, 2874, 12, 2867, 516, 934, 6159, 17631, 14727, 966, 13, 1071, 384, 6159, 17631, 14727, 966, 858, 510, 6159, 1345, 31, 203, 565, 3885, 12, 2867, 389, 266, 6397, 1345, 16, 2254, 5034, 389, 334, 6159, 17631, 14727, 7642, 16786, 13, 14223, 6914, 1435, 288, 203, 3639, 2583, 24899, 334, 6159, 17631, 14727, 7642, 16786, 1545, 1203, 18, 5508, 16, 296, 510, 6159, 17631, 14727, 1733, 2866, 12316, 30, 21906, 4885, 17136, 8284, 203, 203, 3639, 283, 6397, 1345, 273, 389, 266, 6397, 1345, 31, 203, 3639, 384, 6159, 17631, 14727, 7642, 16786, 273, 389, 334, 6159, 17631, 14727, 7642, 16786, 31, 203, 565, 289, 203, 203, 203, 565, 445, 7286, 12, 203, 3639, 1758, 384, 6159, 1345, 16, 203, 3639, 2254, 5034, 19890, 6275, 16, 203, 3639, 2254, 5034, 283, 6397, 5326, 203, 565, 262, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 266, 6397, 5326, 405, 374, 16, 296, 266, 6397, 5326, 33, 20, 8284, 203, 3639, 934, 6159, 17631, 14727, 966, 2502, 1123, 273, 384, 6159, 17631, 14727, 966, 858, 510, 6159, 1345, 63, 334, 6159, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-02-07 */ // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; 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); } function add32(uint32 x, uint32 y) internal pure returns (uint32 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); } function sub32(uint32 x, uint32 y) internal pure returns (uint32 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)); } function div(uint256 x, uint256 y) internal pure returns(uint256 z){ require(y > 0); z=x/y; } } 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} */ 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). * * 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); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } /** * @dev 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.3._ */ 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.3._ */ 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); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } 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); } abstract contract ERC20 is IERC20 { using LowGasSafeMath for uint256; // TODO comment actual hash value. bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _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_, uint8 decimals_) { _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. 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 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(msg.sender, 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(msg.sender, 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, 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 virtual 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 virtual 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 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); _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 ammount_) internal virtual { require(account_ != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address( this ), account_, ammount_); _totalSupply = _totalSupply.add(ammount_); _balances[account_] = _balances[account_].add(ammount_); emit Transfer(address( 0 ), account_, ammount_); } /** * @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); _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. */ /** * @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 { } } library Counters { using LowGasSafeMath 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); } } interface IERC2612Permit { /** * @dev Sets `amount` 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: * * - `owner` cannot be the zero address. * - `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 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current ERC2612 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); } abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public immutable DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) )); } /** * @dev See {IERC2612Permit-permit}. * */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline)); bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "ERC20Permit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } /** * @dev See {IERC2612Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } contract OwnableData { address public owner; address public pendingOwner; } contract Ownable is OwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } contract sSIN is ERC20Permit, Ownable { using LowGasSafeMath for uint256; modifier onlyStakingContract() { require( msg.sender == stakingContract, "OSC" ); _; } address public stakingContract; address public initializer; event LogSupply(uint256 indexed epoch, uint256 timestamp, uint256 totalSupply ); event LogRebase( uint256 indexed epoch, uint256 rebase, uint256 index ); event LogStakingContractUpdated( address stakingContract ); event LogSetIndex(uint256 indexed index ); struct Rebase { uint epoch; uint rebase; // 18 decimals uint totalStakedBefore; uint totalStakedAfter; uint amountRebased; uint index; uint32 timeOccured; } Rebase[] public rebases; uint public INDEX; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 5000000 * 10**9; // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; mapping ( address => mapping ( address => uint256 ) ) private _allowedValue; constructor() ERC20("Staked Sin", "sSIN", 9) ERC20Permit() { initializer = msg.sender; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); } function initialize( address stakingContract_ ) external returns ( bool ) { require( msg.sender == initializer, "NA" ); require( stakingContract_ != address(0), "IA" ); stakingContract = stakingContract_; _gonBalances[ stakingContract ] = TOTAL_GONS; emit Transfer( address(0x0), stakingContract, _totalSupply ); emit LogStakingContractUpdated( stakingContract_ ); initializer = address(0); return true; } function setIndex( uint _INDEX ) external onlyOwner() { require( INDEX == 0, "INZ"); INDEX = gonsForBalance( _INDEX ); emit LogSetIndex(INDEX); } /** @notice increases sSIN\ supply to increase staking balances relative to profit_ @param profit_ uint256 @return uint256 */ function rebase( uint256 profit_, uint epoch_ ) public onlyStakingContract() returns ( uint256 ) { uint256 rebaseAmount; uint256 circulatingSupply_ = circulatingSupply(); if ( profit_ == 0 ) { emit LogSupply( epoch_, block.timestamp, _totalSupply ); emit LogRebase( epoch_, 0, index() ); return _totalSupply; } else if ( circulatingSupply_ > 0 ){ rebaseAmount = profit_.mul( _totalSupply ).div( circulatingSupply_ ); } else { rebaseAmount = profit_; } _totalSupply = _totalSupply.add( rebaseAmount ); if ( _totalSupply > MAX_SUPPLY ) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div( _totalSupply ); _storeRebase( circulatingSupply_, profit_, epoch_ ); return _totalSupply; } /** @notice emits event with data about rebase @param previousCirculating_ uint @param profit_ uint @param epoch_ uint @return bool */ function _storeRebase( uint previousCirculating_, uint profit_, uint epoch_ ) internal returns ( bool ) { uint rebasePercent = profit_.mul( 1e18 ).div( previousCirculating_ ); rebases.push( Rebase ( { epoch: epoch_, rebase: rebasePercent, // 18 decimals totalStakedBefore: previousCirculating_, totalStakedAfter: circulatingSupply(), amountRebased: profit_, index: index(), timeOccured: uint32(block.timestamp) })); emit LogSupply( epoch_, block.timestamp, _totalSupply ); emit LogRebase( epoch_, rebasePercent, index() ); return true; } function balanceOf( address who ) public view override returns ( uint256 ) { return _gonBalances[ who ].div( _gonsPerFragment ); } function gonsForBalance( uint amount ) public view returns ( uint ) { return amount.mul( _gonsPerFragment ); } function balanceForGons( uint gons ) public view returns ( uint ) { return gons.div( _gonsPerFragment ); } // Staking contract holds excess sSIN function circulatingSupply() public view returns ( uint ) { return _totalSupply.sub( balanceOf( stakingContract ) ); } function index() public view returns ( uint ) { return balanceForGons( INDEX ); } function transfer( address to, uint256 value ) public override returns (bool) { uint256 gonValue = value.mul( _gonsPerFragment ); _gonBalances[ msg.sender ] = _gonBalances[ msg.sender ].sub( gonValue ); _gonBalances[ to ] = _gonBalances[ to ].add( gonValue ); emit Transfer( msg.sender, to, value ); return true; } function allowance( address owner_, address spender ) public view override returns ( uint256 ) { return _allowedValue[ owner_ ][ spender ]; } function transferFrom( address from, address to, uint256 value ) public override returns ( bool ) { _allowedValue[ from ][ msg.sender ] = _allowedValue[ from ][ msg.sender ].sub( value ); emit Approval( from, msg.sender, _allowedValue[ from ][ msg.sender ] ); uint256 gonValue = gonsForBalance( value ); _gonBalances[ from ] = _gonBalances[from].sub( gonValue ); _gonBalances[ to ] = _gonBalances[to].add( gonValue ); emit Transfer( from, to, value ); return true; } function approve( address spender, uint256 value ) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = value; emit Approval( msg.sender, spender, value ); return true; } // What gets called in a permit function _approve( address owner, address spender, uint256 value ) internal override virtual { _allowedValue[owner][spender] = value; emit Approval( owner, spender, value ); } function increaseAllowance( address spender, uint256 addedValue ) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = _allowedValue[ msg.sender ][ spender ].add( addedValue ); emit Approval( msg.sender, spender, _allowedValue[ msg.sender ][ spender ] ); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) public override returns (bool) { uint256 oldValue = _allowedValue[ msg.sender ][ spender ]; if (subtractedValue >= oldValue) { _allowedValue[ msg.sender ][ spender ] = 0; } else { _allowedValue[ msg.sender ][ spender ] = oldValue.sub( subtractedValue ); } emit Approval( msg.sender, spender, _allowedValue[ msg.sender ][ spender ] ); return true; } }
* @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); }
2,288,975
[ 1, 8650, 487, 288, 22044, 17, 1887, 17, 915, 1477, 17, 2867, 17, 3890, 17, 20294, 68, 915, 1477, 68, 6487, 1496, 598, 1375, 1636, 1079, 68, 487, 279, 5922, 15226, 3971, 1347, 1375, 3299, 68, 15226, 87, 18, 389, 5268, 3241, 331, 23, 18, 21, 6315, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 445, 1477, 12, 203, 3639, 1758, 1018, 16, 7010, 3639, 1731, 3778, 501, 16, 7010, 3639, 533, 3778, 9324, 203, 565, 262, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 389, 915, 26356, 620, 12, 3299, 16, 501, 16, 374, 16, 9324, 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 ]
pragma solidity 0.4.15; import './ownership/multiowned.sol'; import './crowdsale/FixedTimeBonuses.sol'; import './crowdsale/FundsRegistry.sol'; import './crowdsale/InvestmentAnalytics.sol'; import './security/ArgumentsChecker.sol'; import './STQToken.sol'; import 'zeppelin-solidity/contracts/ReentrancyGuard.sol'; import 'zeppelin-solidity/contracts/math/Math.sol'; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; /// @title Storiqa ICO contract contract STQCrowdsale is ArgumentsChecker, ReentrancyGuard, multiowned, InvestmentAnalytics { using Math for uint256; using SafeMath for uint256; using FixedTimeBonuses for FixedTimeBonuses.Data; enum IcoState { INIT, ICO, PAUSED, FAILED, DISTRIBUTING_BONUSES, SUCCEEDED } /// @dev bookkeeping for last investment bonus struct LastInvestment { address investor; uint payment; // time-based bonus which was already received by the investor uint timeBonus; } event StateChanged(IcoState _state); event FundTransfer(address backer, uint amount, bool isContribution); modifier requiresState(IcoState _state) { require(m_state == _state); _; } /// @dev triggers some state changes based on current time /// @param investor optional refund parameter /// @param payment optional refund parameter /// note: function body could be skipped! modifier timedStateChange(address investor, uint payment) { if (IcoState.INIT == m_state && getCurrentTime() >= getStartTime()) changeState(IcoState.ICO); if (IcoState.ICO == m_state && getCurrentTime() >= getEndTime()) { finishICO(); if (payment > 0) investor.transfer(payment); // note that execution of further (but not preceding!) modifiers and functions ends here } else { _; } } /// @dev automatic check for unaccounted withdrawals /// @param investor optional refund parameter /// @param payment optional refund parameter modifier fundsChecker(address investor, uint payment) { uint atTheBeginning = m_funds.balance; if (atTheBeginning < m_lastFundsAmount) { changeState(IcoState.PAUSED); if (payment > 0) investor.transfer(payment); // we cant throw (have to save state), so refunding this way // note that execution of further (but not preceding!) modifiers and functions ends here } else { _; if (m_funds.balance < atTheBeginning) { changeState(IcoState.PAUSED); } else { m_lastFundsAmount = m_funds.balance; } } } // PUBLIC interface function STQCrowdsale(address[] _owners, address _token, address _funds, address _teamTokens) multiowned(_owners, 2) validAddress(_token) validAddress(_funds) validAddress(_teamTokens) { require(3 == _owners.length); m_token = STQToken(_token); m_funds = FundsRegistry(_funds); m_teamTokens = _teamTokens; m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (1 weeks), bonus: 30})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (2 weeks), bonus: 25})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (3 weeks), bonus: 20})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (4 weeks), bonus: 15})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (5 weeks), bonus: 10})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (8 weeks), bonus: 5})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: 1514246400, bonus: 0})); m_bonuses.validate(true); deployer = msg.sender; } // PUBLIC interface: payments // fallback function as a shortcut function() payable { require(0 == msg.data.length); buy(); // only internal call here! } /// @notice ICO participation function buy() public payable { // dont mark as external! iaOnInvested(msg.sender, msg.value, false); } function iaOnInvested(address investor, uint payment, bool usingPaymentChannel) internal nonReentrant timedStateChange(investor, payment) fundsChecker(investor, payment) { require(m_state == IcoState.ICO || m_state == IcoState.INIT && isOwner(investor) /* for final test */); require(payment >= c_MinInvestment); uint startingInvariant = this.balance.add(m_funds.balance); // checking for max cap uint fundsAllowed = getMaximumFunds().sub(getTotalInvested()); assert(0 != fundsAllowed); // in this case state must not be IcoState.ICO payment = fundsAllowed.min256(payment); uint256 change = msg.value.sub(payment); // issue tokens var (stq, timeBonus) = calcSTQAmount(payment, usingPaymentChannel ? c_paymentChannelBonusPercent : 0); m_token.mint(investor, stq); // record payment m_funds.invested.value(payment)(investor); FundTransfer(investor, payment, true); recordInvestment(investor, payment, timeBonus); // check if ICO must be closed early if (change > 0) { assert(getMaximumFunds() == getTotalInvested()); finishICO(); // send change investor.transfer(change); assert(startingInvariant == this.balance.add(m_funds.balance).add(change)); } else assert(startingInvariant == this.balance.add(m_funds.balance)); } // PUBLIC interface: owners: maintenance /// @notice pauses ICO function pause() external timedStateChange(address(0), 0) requiresState(IcoState.ICO) onlyowner { changeState(IcoState.PAUSED); } /// @notice resume paused ICO function unpause() external timedStateChange(address(0), 0) requiresState(IcoState.PAUSED) onlymanyowners(sha3(msg.data)) { changeState(IcoState.ICO); checkTime(); } /// @notice consider paused ICO as failed function fail() external timedStateChange(address(0), 0) requiresState(IcoState.PAUSED) onlymanyowners(sha3(msg.data)) { changeState(IcoState.FAILED); } /// @notice In case we need to attach to existent token function setToken(address _token) external validAddress(_token) timedStateChange(address(0), 0) requiresState(IcoState.PAUSED) onlymanyowners(sha3(msg.data)) { m_token = STQToken(_token); } /// @notice In case we need to attach to existent funds function setFundsRegistry(address _funds) external validAddress(_funds) timedStateChange(address(0), 0) requiresState(IcoState.PAUSED) onlymanyowners(sha3(msg.data)) { m_funds = FundsRegistry(_funds); } /// @notice explicit trigger for timed state changes function checkTime() public timedStateChange(address(0), 0) onlyowner { } /// @notice computing and distributing post-ICO bonuses function distributeBonuses(uint investorsLimit) external timedStateChange(address(0), 0) requiresState(IcoState.DISTRIBUTING_BONUSES) { uint limitIndex = uint(m_lastInvestments.length).min256(m_nextUndestributedBonusIndex + investorsLimit); uint iterations = 0; uint startingGas = msg.gas; while (m_nextUndestributedBonusIndex < limitIndex) { if (c_lastInvestmentsBonus > m_lastInvestments[m_nextUndestributedBonusIndex].timeBonus) { uint bonus = c_lastInvestmentsBonus.sub(m_lastInvestments[m_nextUndestributedBonusIndex].timeBonus); uint bonusSTQ = m_lastInvestments[m_nextUndestributedBonusIndex].payment.mul(c_STQperETH).mul(bonus).div(100); m_token.mint(m_lastInvestments[m_nextUndestributedBonusIndex].investor, bonusSTQ); } m_nextUndestributedBonusIndex++; // preventing gas limit hit uint avgGasPerIteration = startingGas.sub(msg.gas).div(++iterations); if (msg.gas < avgGasPerIteration * 3) break; } if (m_nextUndestributedBonusIndex == m_lastInvestments.length) changeState(IcoState.SUCCEEDED); } function createMorePaymentChannels(uint limit) external returns (uint) { require(isOwner(msg.sender) || msg.sender == deployer); return createMorePaymentChannelsInternal(limit); } // INTERNAL functions function finishICO() private { if (getTotalInvested() < getMinFunds()) changeState(IcoState.FAILED); else changeState(IcoState.DISTRIBUTING_BONUSES); } /// @dev performs only allowed state transitions function changeState(IcoState _newState) private { assert(m_state != _newState); if (IcoState.INIT == m_state) { assert(IcoState.ICO == _newState); } else if (IcoState.ICO == m_state) { assert(IcoState.PAUSED == _newState || IcoState.FAILED == _newState || IcoState.DISTRIBUTING_BONUSES == _newState); } else if (IcoState.PAUSED == m_state) { assert(IcoState.ICO == _newState || IcoState.FAILED == _newState); } else if (IcoState.DISTRIBUTING_BONUSES == m_state) { assert(IcoState.SUCCEEDED == _newState); } else assert(false); m_state = _newState; StateChanged(m_state); // this should be tightly linked if (IcoState.SUCCEEDED == m_state) { onSuccess(); } else if (IcoState.FAILED == m_state) { onFailure(); } } function onSuccess() private { // mint tokens for owners uint tokensForTeam = m_token.totalSupply().mul(40).div(60); m_token.mint(m_teamTokens, tokensForTeam); m_funds.changeState(FundsRegistry.State.SUCCEEDED); m_funds.detachController(); m_token.disableMinting(); m_token.startCirculation(); m_token.detachController(); } function onFailure() private { m_funds.changeState(FundsRegistry.State.REFUNDING); m_funds.detachController(); } function getLargePaymentBonus(uint payment) private constant returns (uint) { if (payment > 5000 ether) return 20; if (payment > 3000 ether) return 15; if (payment > 1000 ether) return 10; if (payment > 800 ether) return 8; if (payment > 500 ether) return 5; if (payment > 200 ether) return 2; return 0; } /// @dev calculates amount of STQ to which payer of _wei is entitled function calcSTQAmount(uint _wei, uint extraBonus) private constant returns (uint stq, uint timeBonus) { timeBonus = m_bonuses.getBonus(getCurrentTime()); uint bonus = extraBonus.add(timeBonus).add(getLargePaymentBonus(_wei)); // apply bonus stq = _wei.mul(c_STQperETH).mul(bonus.add(100)).div(100); } /// @dev records investments in a circular buffer function recordInvestment(address investor, uint payment, uint timeBonus) private { uint writeTo; assert(m_lastInvestments.length <= getLastMaxInvestments()); if (m_lastInvestments.length < getLastMaxInvestments()) { // buffer is still expanding writeTo = m_lastInvestments.length++; } else { // reusing buffer writeTo = m_nextFreeLastInvestmentIndex++; if (m_nextFreeLastInvestmentIndex == m_lastInvestments.length) m_nextFreeLastInvestmentIndex = 0; } assert(writeTo < m_lastInvestments.length); m_lastInvestments[writeTo] = LastInvestment(investor, payment, timeBonus); } /// @dev start time of the ICO, inclusive function getStartTime() private constant returns (uint) { return c_startTime; } /// @dev end time of the ICO, inclusive function getEndTime() private constant returns (uint) { return m_bonuses.getLastTime(); } /// @dev to be overridden in tests function getCurrentTime() internal constant returns (uint) { return now; } /// @dev to be overridden in tests function getMinFunds() internal constant returns (uint) { return c_MinFunds; } /// @dev to be overridden in tests function getMaximumFunds() internal constant returns (uint) { return c_MaximumFunds; } /// @dev amount of investments during all crowdsales function getTotalInvested() internal constant returns (uint) { return m_funds.totalInvested().add(4426 ether /* FIXME update me */); } /// @dev to be overridden in tests function getLastMaxInvestments() internal constant returns (uint) { return c_maxLastInvestments; } // FIELDS /// @notice starting exchange rate of STQ uint public constant c_STQperETH = 100000; /// @notice minimum investment uint public constant c_MinInvestment = 10 finney; /// @notice minimum investments to consider ICO as a success uint public constant c_MinFunds = 30000 ether; /// @notice maximum investments to be accepted during ICO uint public constant c_MaximumFunds = 90000 ether; /// @notice start time of the ICO uint public constant c_startTime = 1508889600; /// @notice authorised payment bonus uint public constant c_paymentChannelBonusPercent = 2; /// @notice timed bonuses FixedTimeBonuses.Data m_bonuses; uint public constant c_maxLastInvestments = 100; uint public constant c_lastInvestmentsBonus = 30; /// @dev bookkeeping for last investment bonus LastInvestment[] public m_lastInvestments; uint m_nextFreeLastInvestmentIndex; uint m_nextUndestributedBonusIndex; /// @dev state of the ICO IcoState public m_state = IcoState.INIT; /// @dev contract responsible for token accounting STQToken public m_token; address public m_teamTokens; address public deployer; /// @dev contract responsible for investments accounting FundsRegistry public m_funds; /// @dev last recorded funds uint256 public m_lastFundsAmount; }
@notice consider paused ICO as failed
{ changeState(IcoState.FAILED); }
12,662,727
[ 1, 8559, 3585, 17781, 467, 3865, 487, 2535, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 3639, 2549, 1119, 12, 45, 2894, 1119, 18, 11965, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-03-15 */ // File: node_modules\@openzeppelin\contracts\GSN\Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: node_modules\@openzeppelin\contracts\introspection\IERC165.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: node_modules\@openzeppelin\contracts\token\ERC721\IERC721.sol pragma solidity ^0.6.2; /** * @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 calldata data) external; } // File: node_modules\@openzeppelin\contracts\token\ERC721\IERC721Metadata.sol pragma solidity ^0.6.2; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // File: node_modules\@openzeppelin\contracts\token\ERC721\IERC721Enumerable.sol pragma solidity ^0.6.2; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { 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); } // File: node_modules\@openzeppelin\contracts\token\ERC721\IERC721Receiver.sol pragma solidity ^0.6.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ abstract contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public virtual returns (bytes4); } // File: node_modules\@openzeppelin\contracts\introspection\ERC165.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: node_modules\@openzeppelin\contracts\utils\Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: node_modules\@openzeppelin\contracts\utils\EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: node_modules\@openzeppelin\contracts\utils\EnumerableMap.sol pragma solidity ^0.6.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // File: node_modules\@openzeppelin\contracts\utils\Strings.sol pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin\contracts\token\ERC721\ERC721.sol pragma solidity ^0.6.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev Gets the token name. * @return string representing the token name */ function name() public view override returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If a base URI is set (via {_setBaseURI}), it is added as a prefix to the * token's own URI (via {_setTokenURI}). * * If there is a base URI but no token URI, the token's ID will be used as * its URI when appending it to the base URI. This pattern for autogenerated * token URIs can lead to large gas savings. * * .Examples * |=== * |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()` * | "" * | "" * | "" * | "" * | "token.uri/123" * | "token.uri/123" * | "token.uri/" * | "123" * | "token.uri/123" * | "token.uri/" * | "" * | "token.uri/<tokenId>" * |=== * * Requirements: * * - `tokenId` must exist. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param operator operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: If all token IDs share a prefix (for example, if your URIs look like * `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - when `from` is zero, `tokenId` will be minted for `to`. * - when `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin\contracts\utils\Counters.sol pragma solidity ^0.6.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: @openzeppelin\contracts\access\Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin\contracts\math\SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // 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; } } // File: contracts\CryptoKings.sol // SPDX-License-Identifier: MIT // Contract written by Wizard pragma solidity ^0.6.0; contract CryptoKings is ERC721, Ownable { using Counters for Counters.Counter; using SafeMath for uint256; Counters.Counter private _tokenIds; constructor() public ERC721("CryptoKings", "CKS") {} mapping(uint256 => string) public nftNames; // Holds the names the NFTs currently have mapping(string => bool) public usedNames; // Holds which names are currently occupied uint256 public deployedBlock = block.number; // The block this contract was deployed on uint256 public expireSaleAfterBlocks = 137460; // 21 days; uint256 public maxNfts = 5000; // The maximum amount of NFTs is 5000 uint256 public lastKnownPrice = 0.1 ether; // In case we dont sell out within 21 days we sell at the last known price uint256 public saleEndedBlock; // The block when the sale ends when NFTs were minted uint256 public saleStartBlock = 12062935; // This is the block where people are allowed to purchase nfts bool public saleEnded = false; // Allows contract owner to change the start block if needed function setSaleStartBlock (uint256 _block) public onlyOwner { require(_block > 0, "We can't set the block to the genesis block"); saleStartBlock = _block; } // Returns the price of one specific tokenId; function getNFTPrice(uint256 tokenId) public view returns(uint256){ require(tokenId <= maxNfts, "There are not more than 5000 NFTs"); require(tokenId > 0, "NFT TokenIds start from 1"); // If the current block height is higher than the deployedBlock + 21 days // we allow the rest of the NFTs to be sold at the lastKnownPrice if(block.number >= (deployedBlock + expireSaleAfterBlocks)){ return lastKnownPrice; } if (tokenId >= 1 && tokenId <= 1400) { return 0.1 ether; } if (tokenId >= 1401 && tokenId <= 2600) { return 0.2 ether; } if (tokenId >= 2601 && tokenId <= 3400) { return 0.3 ether; } if (tokenId >= 3401 && tokenId <= 4100) { return 0.4 ether; } if (tokenId >= 4101 && tokenId <= 4600) { return 0.5 ether; } if (tokenId >= 4601 && tokenId <= 4850) { return 0.6 ether; } if (tokenId >= 4851 && tokenId <= 4950) { return 1 ether; } if (tokenId >= 4951 && tokenId <= 5000) { return 2 ether; } } // Allows contract owner to update the MetaData URI for a tokenId function updateNFTMeta(uint256 tokenId, string memory tokenURI) public onlyOwner { _setTokenURI(tokenId, tokenURI); } function setNFTName(uint256 tokenId, string memory name) public { require(ownerOf(tokenId) == msg.sender, "You cant change someone elses NFT name"); require(validName(name) == true, "Please, set an unused name for your NFT"); string memory currentName = nftNames[tokenId]; usedNames[currentName] = false; usedNames[name] = true; nftNames[tokenId] = name; } // Allows one single NFT to be purchased function purchaseNFT(uint256 tokenId) private { // Transfer the NFT to the purchasing user _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); // all NFTs are owned by the contract when they are minted _mint(msg.sender, newItemId); string memory curUri = string(abi.encodePacked("https://api.cryptokings.art/nft/", uint2str(tokenId))); _setTokenURI(tokenId,curUri); } // Returns the total sum owed to the contract to the user in order to purchase NFTs function getNFTPriceSum(uint256 amount) public view returns (uint256){ uint256 price = 0; uint256 priceIndex = totalSupply().add(1); for(uint i = 1 ; i <= amount; i++) { price = price.add(getNFTPrice(priceIndex)); priceIndex = priceIndex.add(1); } return price; } // Allows the users to purchase NFTs at a limit of 10 at once. function purchaseNFTs(uint256 amount) payable public { require(block.number >= saleStartBlock, "Sale has not started yet"); require(saleEnded == false, "Sale has ended already"); require(amount > 0, "Purchase at least one NFT"); require(amount <= 10, "You can't purchase more than 10 NFTs at once"); require((totalSupply() + amount) <= maxNfts, "There are only 5000 NFTs for sale"); require(msg.value == getNFTPriceSum(amount), "At least pay the amount that is being asked for"); for (uint i=1; i<= amount; i++) { purchaseNFT(totalSupply()+1); } lastKnownPrice = getNFTPrice(totalSupply()); if(totalSupply() == maxNfts){ saleEnded = true; saleEndedBlock = block.number; } } // Allows contract owner to withdraw the Ether the contract owns function withdrawEther() onlyOwner public { uint balance = address(this).balance; msg.sender.transfer(balance); } // Displays the amount of ether the contract currently holds function ownedEther() public view returns(uint256){ return address(this).balance; } // Returns the current status of the sale, PENDING STARTED or ENDED. function getSaleStatus() public view returns(string memory){ if(block.number < saleStartBlock){ return 'SALE_PENDING'; } if(block.number >= saleStartBlock && saleEnded == false){ return 'SALE_STARTED'; } if(saleEnded == true){ return 'SALE_ENDED'; } } // Returns to the user wether a name is valid or not function validName(string memory str) public view returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 30) return false; if(b[0] == 0x20) return false; if (b[b.length - 1] == 0x20) return false; bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } if(usedNames[str] == true){ return false; // if the nft name is already used then its not a valid name anymore } return true; } // Allows a UINT to be converted to string; function uint2str(uint _i) private pure returns (string memory _uintAsString) { 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; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } }
Allows contract owner to withdraw the Ether the contract owns
function withdrawEther() onlyOwner public { uint balance = address(this).balance; msg.sender.transfer(balance); }
6,813,107
[ 1, 19132, 6835, 3410, 358, 598, 9446, 326, 512, 1136, 326, 6835, 29065, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 9446, 41, 1136, 1435, 1338, 5541, 1071, 288, 203, 3639, 2254, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 12296, 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, -100, -100, -100, -100, -100, -100, -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.16; import "./VToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./Governance/XVS.sol"; import "./VAI/VAI.sol"; /** * @title Venus's Comptroller Contract * @author Venus */ contract ComptrollerG2 is ComptrollerV1Storage, ComptrollerInterfaceG1, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(VToken vToken); /// @notice Emitted when an account enters a market event MarketEntered(VToken vToken, address account); /// @notice Emitted when an account exits a market event MarketExited(VToken vToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(VToken vToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(VToken vToken, string action, bool pauseState); /// @notice Emitted when market venus status is changed event MarketVenus(VToken vToken, bool isVenus); /// @notice Emitted when Venus rate is changed event NewVenusRate(uint oldVenusRate, uint newVenusRate); /// @notice Emitted when Venus VAI rate is changed event NewVenusVAIRate(uint oldVenusVAIRate, uint newVenusVAIRate); /// @notice Emitted when a new Venus speed is calculated for a market event VenusSpeedUpdated(VToken indexed vToken, uint newSpeed); /// @notice Emitted when XVS is distributed to a supplier event DistributedSupplierVenus(VToken indexed vToken, address indexed supplier, uint venusDelta, uint venusSupplyIndex); /// @notice Emitted when XVS is distributed to a borrower event DistributedBorrowerVenus(VToken indexed vToken, address indexed borrower, uint venusDelta, uint venusBorrowIndex); /// @notice Emitted when XVS is distributed to a VAI minter event DistributedVAIMinterVenus(address indexed vaiMinter, uint venusDelta, uint venusVAIMintIndex); /// @notice Emitted when VAIController is changed event NewVAIController(VAIControllerInterface oldVAIController, VAIControllerInterface newVAIController); /// @notice Emitted when VAI mint rate is changed by admin event NewVAIMintRate(uint oldVAIMintRate, uint newVAIMintRate); /// @notice Emitted when protocol state is changed by admin event ActionProtocolPaused(bool state); /// @notice The threshold above which the flywheel transfers XVS, in wei uint public constant venusClaimThreshold = 0.001e18; /// @notice The initial Venus index for a market uint224 public constant venusInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } modifier onlyProtocolAllowed { require(!protocolPaused, "protocol is paused"); _; } modifier onlyAdmin() { require(msg.sender == admin, "only admin can"); _; } modifier onlyListedMarket(VToken vToken) { require(markets[address(vToken)].isListed, "venus market is not listed"); _; } modifier validPauseState(bool state) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can"); require(msg.sender == admin || state == true, "only admin can unpause"); _; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (VToken[] memory) { return accountAssets[account]; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param vToken The vToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, VToken vToken) external view returns (bool) { return markets[address(vToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param vTokens The list of addresses of the vToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] calldata vTokens) external returns (uint[] memory) { uint len = vTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { results[i] = uint(addToMarketInternal(VToken(vTokens[i]), msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param vToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(VToken vToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(vToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower]) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(vToken); emit MarketEntered(vToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param vTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address vTokenAddress) external returns (uint) { VToken vToken = VToken(vTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the vToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = vToken.getAccountSnapshot(msg.sender); require(oErr == 0, "getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(vTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(vToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set vToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete vToken from the account’s list of assets */ // In order to delete vToken, copy last item in list to location of item to be removed, reduce length by 1 VToken[] storage userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint i; for (; i < len; i++) { if (userAssetList[i] == vToken) { userAssetList[i] = userAssetList[len - 1]; userAssetList.length--; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(i < len); emit MarketExited(vToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param vToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address vToken, address minter, uint mintAmount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[vToken], "mint is paused"); // Shh - currently unused mintAmount; if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateVenusSupplyIndex(vToken); distributeSupplierVenus(vToken, minter, false); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param vToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address vToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused vToken; minter; actualMintAmount; mintTokens; } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param vToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of vTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address vToken, address redeemer, uint redeemTokens) external onlyProtocolAllowed returns (uint) { uint allowed = redeemAllowedInternal(vToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateVenusSupplyIndex(vToken); distributeSupplierVenus(vToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address vToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[vToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, VToken(vToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param vToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address vToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused vToken; redeemer; // Require tokens is zero or amount is also zero require(redeemTokens != 0 || redeemAmount == 0, "redeemTokens zero"); } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param vToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[vToken], "borrow is paused"); if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[borrower]) { // only vTokens may call borrowAllowed if borrower not in market require(msg.sender == vToken, "sender must be vToken"); // attempt to add borrower to the market Error err = addToMarketInternal(VToken(vToken), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: VToken(vToken).borrowIndex()}); updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param vToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address vToken, address borrower, uint borrowAmount) external { // Shh - currently unused vToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param vToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would repay the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address vToken, address payer, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: VToken(vToken).borrowIndex()}); updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param vToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address vToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused vToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param vTokenBorrowed Asset which was borrowed by the borrower * @param vTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { // Shh - currently unused liquidator; if (!markets[vTokenBorrowed].isListed || !markets[vTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(0), 0, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = VToken(vTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param vTokenBorrowed Asset which was borrowed by the borrower * @param vTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused vTokenBorrowed; vTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param vTokenCollateral Asset which was used as collateral and will be seized * @param vTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address vTokenCollateral, address vTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[vTokenCollateral].isListed || !markets[vTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (VToken(vTokenCollateral).comptroller() != VToken(vTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateVenusSupplyIndex(vTokenCollateral); distributeSupplierVenus(vTokenCollateral, borrower, false); distributeSupplierVenus(vTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param vTokenCollateral Asset which was used as collateral and will be seized * @param vTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address vTokenCollateral, address vTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused vTokenCollateral; vTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param vToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of vTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address vToken, address src, address dst, uint transferTokens) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(vToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateVenusSupplyIndex(vToken); distributeSupplierVenus(vToken, src, false); distributeSupplierVenus(vToken, dst, false); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param vToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of vTokens to transfer */ function transferVerify(address vToken, address src, address dst, uint transferTokens) external { // Shh - currently unused vToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `vTokenBalance` is the number of vTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint vTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, VToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param vTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address vTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, VToken(vTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param vTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral vToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; // Read the balances and exchange rate from the vToken (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> bnb (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * vTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.vTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with vTokenModify if (asset == vTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } /// @dev VAI Integration^ (mErr, vars.sumBorrowPlusEffects) = addUInt(vars.sumBorrowPlusEffects, mintedVAIs[account]); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } /// @dev VAI Integration$ // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in vToken.liquidateBorrowFresh) * @param vTokenBorrowed The address of the borrowed vToken * @param vTokenCollateral The address of the collateral vToken * @param actualRepayAmount The amount of vTokenBorrowed underlying to convert into vTokenCollateral tokens * @return (errorCode, number of vTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address vTokenBorrowed, address vTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(VToken(vTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(VToken(vTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = VToken(vTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, newCloseFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param vToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(VToken vToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(vToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(vToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(vToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param vToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(VToken vToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(vToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } vToken.isVToken(); // Sanity check to make sure its really a VToken markets[address(vToken)] = Market({isListed: true, isVenus: false, collateralFactorMantissa: 0}); _addMarketInternal(vToken); emit MarketListed(vToken); return uint(Error.NO_ERROR); } function _addMarketInternal(VToken vToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != vToken, "market already added"); } allMarkets.push(vToken); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, newPauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(VToken vToken, bool state) public onlyListedMarket(vToken) validPauseState(state) returns (bool) { mintGuardianPaused[address(vToken)] = state; emit ActionPaused(vToken, "Mint", state); return state; } function _setBorrowPaused(VToken vToken, bool state) public onlyListedMarket(vToken) validPauseState(state) returns (bool) { borrowGuardianPaused[address(vToken)] = state; emit ActionPaused(vToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public validPauseState(state) returns (bool) { transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public validPauseState(state) returns (bool) { seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _setMintVAIPaused(bool state) public validPauseState(state) returns (bool) { mintVAIGuardianPaused = state; emit ActionPaused("MintVAI", state); return state; } function _setRepayVAIPaused(bool state) public validPauseState(state) returns (bool) { repayVAIGuardianPaused = state; emit ActionPaused("RepayVAI", state); return state; } /** * @notice Set whole protocol pause/unpause state */ function _setProtocolPaused(bool state) public onlyAdmin returns(bool) { protocolPaused = state; emit ActionProtocolPaused(state); return state; } /** * @notice Sets a new VAI controller * @dev Admin function to set a new VAI controller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setVAIController(VAIControllerInterface vaiController_) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_VAICONTROLLER_OWNER_CHECK); } VAIControllerInterface oldRate = vaiController; vaiController = vaiController_; emit NewVAIController(oldRate, vaiController_); } function _setVAIMintRate(uint newVAIMintRate) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_VAI_MINT_RATE_CHECK); } uint oldVAIMintRate = vaiMintRate; vaiMintRate = newVAIMintRate; emit NewVAIMintRate(oldVAIMintRate, newVAIMintRate); return uint(Error.NO_ERROR); } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can"); require(unitroller._acceptImplementation() == 0, "not authorized"); } /*** Venus Distribution ***/ /** * @notice Recalculate and update Venus speeds for all Venus markets */ function refreshVenusSpeeds() public { require(msg.sender == tx.origin, "only externally owned accounts can"); refreshVenusSpeedsInternal(); } function refreshVenusSpeedsInternal() internal { uint i; VToken vToken; for (i = 0; i < allMarkets.length; i++) { vToken = allMarkets[i]; Exp memory borrowIndex = Exp({mantissa: vToken.borrowIndex()}); updateVenusSupplyIndex(address(vToken)); updateVenusBorrowIndex(address(vToken), borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets.length); for (i = 0; i < allMarkets.length; i++) { vToken = allMarkets[i]; if (markets[address(vToken)].isVenus) { Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(vToken)}); Exp memory utility = mul_(assetPrice, vToken.totalBorrows()); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (i = 0; i < allMarkets.length; i++) { vToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(venusRate, div_(utilities[i], totalUtility)) : 0; venusSpeeds[address(vToken)] = newSpeed; emit VenusSpeedUpdated(vToken, newSpeed); } } /** * @notice Accrue XVS to the market by updating the supply index * @param vToken The market whose supply index to update */ function updateVenusSupplyIndex(address vToken) internal { VenusMarketState storage supplyState = venusSupplyState[vToken]; uint supplySpeed = venusSpeeds[vToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = VToken(vToken).totalSupply(); uint venusAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(venusAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); venusSupplyState[vToken] = VenusMarketState({ index: safe224(index.mantissa, "new index overflows"), block: safe32(blockNumber, "block number overflows") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number overflows"); } } /** * @notice Accrue XVS to the market by updating the borrow index * @param vToken The market whose borrow index to update */ function updateVenusBorrowIndex(address vToken, Exp memory marketBorrowIndex) internal { VenusMarketState storage borrowState = venusBorrowState[vToken]; uint borrowSpeed = venusSpeeds[vToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(VToken(vToken).totalBorrows(), marketBorrowIndex); uint venusAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(venusAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); venusBorrowState[vToken] = VenusMarketState({ index: safe224(index.mantissa, "new index overflows"), block: safe32(blockNumber, "block number overflows") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number overflows"); } } /** * @notice Accrue XVS to by updating the VAI minter index */ function updateVenusVAIMintIndex() internal { if (address(vaiController) != address(0)) { vaiController.updateVenusVAIMintIndex(); } } /** * @notice Calculate XVS accrued by a supplier and possibly transfer it to them * @param vToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute XVS to */ function distributeSupplierVenus(address vToken, address supplier, bool distributeAll) internal { VenusMarketState storage supplyState = venusSupplyState[vToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: venusSupplierIndex[vToken][supplier]}); venusSupplierIndex[vToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = venusInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = VToken(vToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(venusAccrued[supplier], supplierDelta); venusAccrued[supplier] = transferXVS(supplier, supplierAccrued, distributeAll ? 0 : venusClaimThreshold); emit DistributedSupplierVenus(VToken(vToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate XVS accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param vToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute XVS to */ function distributeBorrowerVenus(address vToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal { VenusMarketState storage borrowState = venusBorrowState[vToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: venusBorrowerIndex[vToken][borrower]}); venusBorrowerIndex[vToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(VToken(vToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(venusAccrued[borrower], borrowerDelta); venusAccrued[borrower] = transferXVS(borrower, borrowerAccrued, distributeAll ? 0 : venusClaimThreshold); emit DistributedBorrowerVenus(VToken(vToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Calculate XVS accrued by a VAI minter and possibly transfer it to them * @dev VAI minters will not begin to accrue until after the first interaction with the protocol. * @param vaiMinter The address of the VAI minter to distribute XVS to */ function distributeVAIMinterVenus(address vaiMinter, bool distributeAll) internal { if (address(vaiController) != address(0)) { uint vaiMinterAccrued; uint vaiMinterDelta; uint vaiMintIndexMantissa; uint err; (err, vaiMinterAccrued, vaiMinterDelta, vaiMintIndexMantissa) = vaiController.calcDistributeVAIMinterVenus(vaiMinter); if (err == uint(Error.NO_ERROR)) { venusAccrued[vaiMinter] = transferXVS(vaiMinter, vaiMinterAccrued, distributeAll ? 0 : venusClaimThreshold); emit DistributedVAIMinterVenus(vaiMinter, vaiMinterDelta, vaiMintIndexMantissa); } } } /** * @notice Transfer XVS to the user, if they are above the threshold * @dev Note: If there is not enough XVS, we do not perform the transfer all. * @param user The address of the user to transfer XVS to * @param userAccrued The amount of XVS to (possibly) transfer * @return The amount of XVS which was NOT transferred to the user */ function transferXVS(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { XVS xvs = XVS(getXVSAddress()); uint xvsRemaining = xvs.balanceOf(address(this)); if (userAccrued <= xvsRemaining) { xvs.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the xvs accrued by holder in all markets and VAI * @param holder The address to claim XVS for */ function claimVenus(address holder) public { return claimVenus(holder, allMarkets); } /** * @notice Claim all the xvs accrued by holder in the specified markets * @param holder The address to claim XVS for * @param vTokens The list of markets to claim XVS in */ function claimVenus(address holder, VToken[] memory vTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimVenus(holders, vTokens, true, true); } /** * @notice Claim all xvs accrued by the holders * @param holders The addresses to claim XVS for * @param vTokens The list of markets to claim XVS in * @param borrowers Whether or not to claim XVS earned by borrowing * @param suppliers Whether or not to claim XVS earned by supplying */ function claimVenus(address[] memory holders, VToken[] memory vTokens, bool borrowers, bool suppliers) public { uint j; updateVenusVAIMintIndex(); for (j = 0; j < holders.length; j++) { distributeVAIMinterVenus(holders[j], true); } for (uint i = 0; i < vTokens.length; i++) { VToken vToken = vTokens[i]; require(markets[address(vToken)].isListed, "not listed market"); if (borrowers) { Exp memory borrowIndex = Exp({mantissa: vToken.borrowIndex()}); updateVenusBorrowIndex(address(vToken), borrowIndex); for (j = 0; j < holders.length; j++) { distributeBorrowerVenus(address(vToken), holders[j], borrowIndex, true); } } if (suppliers) { updateVenusSupplyIndex(address(vToken)); for (j = 0; j < holders.length; j++) { distributeSupplierVenus(address(vToken), holders[j], true); } } } } /*** Venus Distribution Admin ***/ /** * @notice Set the amount of XVS distributed per block * @param venusRate_ The amount of XVS wei per block to distribute */ function _setVenusRate(uint venusRate_) public onlyAdmin { uint oldRate = venusRate; venusRate = venusRate_; emit NewVenusRate(oldRate, venusRate_); refreshVenusSpeedsInternal(); } /** * @notice Set the amount of XVS distributed per block to VAI Mint * @param venusVAIRate_ The amount of XVS wei per block to distribute to VAI Mint */ function _setVenusVAIRate(uint venusVAIRate_) public { require(msg.sender == admin, "only admin can"); uint oldVAIRate = venusVAIRate; venusVAIRate = venusVAIRate_; emit NewVenusVAIRate(oldVAIRate, venusVAIRate_); } /** * @notice Add markets to venusMarkets, allowing them to earn XVS in the flywheel * @param vTokens The addresses of the markets to add */ function _addVenusMarkets(address[] calldata vTokens) external onlyAdmin { for (uint i = 0; i < vTokens.length; i++) { _addVenusMarketInternal(vTokens[i]); } refreshVenusSpeedsInternal(); } function _addVenusMarketInternal(address vToken) internal { Market storage market = markets[vToken]; require(market.isListed, "venus market is not listed"); require(!market.isVenus, "venus market already added"); market.isVenus = true; emit MarketVenus(VToken(vToken), true); if (venusSupplyState[vToken].index == 0 && venusSupplyState[vToken].block == 0) { venusSupplyState[vToken] = VenusMarketState({ index: venusInitialIndex, block: safe32(getBlockNumber(), "block number overflows") }); } if (venusBorrowState[vToken].index == 0 && venusBorrowState[vToken].block == 0) { venusBorrowState[vToken] = VenusMarketState({ index: venusInitialIndex, block: safe32(getBlockNumber(), "block number overflows") }); } } function _initializeVenusVAIState(uint blockNumber) public { require(msg.sender == admin, "only admin can"); if (address(vaiController) != address(0)) { vaiController._initializeVenusVAIState(blockNumber); } } /** * @notice Remove a market from venusMarkets, preventing it from earning XVS in the flywheel * @param vToken The address of the market to drop */ function _dropVenusMarket(address vToken) public onlyAdmin { Market storage market = markets[vToken]; require(market.isVenus == true, "not venus market"); market.isVenus = false; emit MarketVenus(VToken(vToken), false); refreshVenusSpeedsInternal(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (VToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the XVS token * @return The address of XVS */ function getXVSAddress() public view returns (address) { return 0xcF6BB5389c92Bdda8a3747Ddb454cB7a64626C63; } /*** VAI functions ***/ /** * @notice Set the minted VAI amount of the `owner` * @param owner The address of the account to set * @param amount The amount of VAI to set to the account * @return The number of minted VAI by `owner` */ function setMintedVAIOf(address owner, uint amount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintVAIGuardianPaused && !repayVAIGuardianPaused, "VAI is paused"); // Check caller is vaiController if (msg.sender != address(vaiController)) { return fail(Error.REJECTION, FailureInfo.SET_MINTED_VAI_REJECTION); } mintedVAIs[owner] = amount; return uint(Error.NO_ERROR); } /** * @notice Mint VAI */ function mintVAI(uint mintVAIAmount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintVAIGuardianPaused, "mintVAI is paused"); // Keep the flywheel moving updateVenusVAIMintIndex(); distributeVAIMinterVenus(msg.sender, false); return vaiController.mintVAI(msg.sender, mintVAIAmount); } /** * @notice Repay VAI */ function repayVAI(uint repayVAIAmount) external onlyProtocolAllowed returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!repayVAIGuardianPaused, "repayVAI is paused"); // Keep the flywheel moving updateVenusVAIMintIndex(); distributeVAIMinterVenus(msg.sender, false); return vaiController.repayVAI(msg.sender, repayVAIAmount); } /** * @notice Get the minted VAI amount of the `owner` * @param owner The address of the account to query * @return The number of minted VAI by `owner` */ function mintedVAIOf(address owner) external view returns (uint) { return mintedVAIs[owner]; } /** * @notice Get Mintable VAI amount */ function getMintableVAI(address minter) external view returns (uint, uint) { return vaiController.getMintableVAI(minter); } }
* @title Venus's Comptroller Contract @author Venus/ closeFactorMantissa must be strictly greater than this value closeFactorMantissa must not exceed this value No collateralFactorMantissa may exceed this value liquidationIncentiveMantissa must be no less than this value liquidationIncentiveMantissa must be no greater than this value
contract ComptrollerG2 is ComptrollerV1Storage, ComptrollerInterfaceG1, ComptrollerErrorReporter, Exponential { event MarketListed(VToken vToken); event MarketEntered(VToken vToken, address account); event MarketExited(VToken vToken, address account); event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); event NewCollateralFactor(VToken vToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); event ActionPaused(string action, bool pauseState); event ActionPaused(VToken vToken, string action, bool pauseState); event MarketVenus(VToken vToken, bool isVenus); event NewVenusRate(uint oldVenusRate, uint newVenusRate); event NewVenusVAIRate(uint oldVenusVAIRate, uint newVenusVAIRate); event VenusSpeedUpdated(VToken indexed vToken, uint newSpeed); event DistributedSupplierVenus(VToken indexed vToken, address indexed supplier, uint venusDelta, uint venusSupplyIndex); event DistributedBorrowerVenus(VToken indexed vToken, address indexed borrower, uint venusDelta, uint venusBorrowIndex); event DistributedVAIMinterVenus(address indexed vaiMinter, uint venusDelta, uint venusVAIMintIndex); event NewVAIController(VAIControllerInterface oldVAIController, VAIControllerInterface newVAIController); event NewVAIMintRate(uint oldVAIMintRate, uint newVAIMintRate); event ActionProtocolPaused(bool state); uint public constant venusClaimThreshold = 0.001e18; uint224 public constant venusInitialIndex = 1e36; constructor() public { admin = msg.sender; } modifier onlyProtocolAllowed { require(!protocolPaused, "protocol is paused"); _; } modifier onlyAdmin() { require(msg.sender == admin, "only admin can"); _; } modifier onlyListedMarket(VToken vToken) { require(markets[address(vToken)].isListed, "venus market is not listed"); _; } modifier validPauseState(bool state) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can"); require(msg.sender == admin || state == true, "only admin can unpause"); _; } function getAssetsIn(address account) external view returns (VToken[] memory) { return accountAssets[account]; } function checkMembership(address account, VToken vToken) external view returns (bool) { return markets[address(vToken)].accountMembership[account]; } function enterMarkets(address[] calldata vTokens) external returns (uint[] memory) { uint len = vTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { results[i] = uint(addToMarketInternal(VToken(vTokens[i]), msg.sender)); } return results; } function enterMarkets(address[] calldata vTokens) external returns (uint[] memory) { uint len = vTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { results[i] = uint(addToMarketInternal(VToken(vTokens[i]), msg.sender)); } return results; } function addToMarketInternal(VToken vToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(vToken)]; if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower]) { return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { return Error.TOO_MANY_ASSETS; } accountAssets[borrower].push(vToken); emit MarketEntered(vToken, borrower); return Error.NO_ERROR; } function addToMarketInternal(VToken vToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(vToken)]; if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower]) { return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { return Error.TOO_MANY_ASSETS; } accountAssets[borrower].push(vToken); emit MarketEntered(vToken, borrower); return Error.NO_ERROR; } function addToMarketInternal(VToken vToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(vToken)]; if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower]) { return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { return Error.TOO_MANY_ASSETS; } accountAssets[borrower].push(vToken); emit MarketEntered(vToken, borrower); return Error.NO_ERROR; } function addToMarketInternal(VToken vToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(vToken)]; if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower]) { return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { return Error.TOO_MANY_ASSETS; } accountAssets[borrower].push(vToken); emit MarketEntered(vToken, borrower); return Error.NO_ERROR; } marketToJoin.accountMembership[borrower] = true; function exitMarket(address vTokenAddress) external returns (uint) { VToken vToken = VToken(vTokenAddress); (uint oErr, uint tokensHeld, uint amountOwed, ) = vToken.getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(vToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } uint len = userAssetList.length; uint i; for (; i < len; i++) { if (userAssetList[i] == vToken) { userAssetList[i] = userAssetList[len - 1]; userAssetList.length--; break; } } emit MarketExited(vToken, msg.sender); return uint(Error.NO_ERROR); } function exitMarket(address vTokenAddress) external returns (uint) { VToken vToken = VToken(vTokenAddress); (uint oErr, uint tokensHeld, uint amountOwed, ) = vToken.getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(vToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } uint len = userAssetList.length; uint i; for (; i < len; i++) { if (userAssetList[i] == vToken) { userAssetList[i] = userAssetList[len - 1]; userAssetList.length--; break; } } emit MarketExited(vToken, msg.sender); return uint(Error.NO_ERROR); } uint allowed = redeemAllowedInternal(vTokenAddress, msg.sender, tokensHeld); function exitMarket(address vTokenAddress) external returns (uint) { VToken vToken = VToken(vTokenAddress); (uint oErr, uint tokensHeld, uint amountOwed, ) = vToken.getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(vToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } uint len = userAssetList.length; uint i; for (; i < len; i++) { if (userAssetList[i] == vToken) { userAssetList[i] = userAssetList[len - 1]; userAssetList.length--; break; } } emit MarketExited(vToken, msg.sender); return uint(Error.NO_ERROR); } function exitMarket(address vTokenAddress) external returns (uint) { VToken vToken = VToken(vTokenAddress); (uint oErr, uint tokensHeld, uint amountOwed, ) = vToken.getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(vToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } uint len = userAssetList.length; uint i; for (; i < len; i++) { if (userAssetList[i] == vToken) { userAssetList[i] = userAssetList[len - 1]; userAssetList.length--; break; } } emit MarketExited(vToken, msg.sender); return uint(Error.NO_ERROR); } delete marketToExit.accountMembership[msg.sender]; VToken[] storage userAssetList = accountAssets[msg.sender]; function exitMarket(address vTokenAddress) external returns (uint) { VToken vToken = VToken(vTokenAddress); (uint oErr, uint tokensHeld, uint amountOwed, ) = vToken.getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(vToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } uint len = userAssetList.length; uint i; for (; i < len; i++) { if (userAssetList[i] == vToken) { userAssetList[i] = userAssetList[len - 1]; userAssetList.length--; break; } } emit MarketExited(vToken, msg.sender); return uint(Error.NO_ERROR); } function exitMarket(address vTokenAddress) external returns (uint) { VToken vToken = VToken(vTokenAddress); (uint oErr, uint tokensHeld, uint amountOwed, ) = vToken.getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(vToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } uint len = userAssetList.length; uint i; for (; i < len; i++) { if (userAssetList[i] == vToken) { userAssetList[i] = userAssetList[len - 1]; userAssetList.length--; break; } } emit MarketExited(vToken, msg.sender); return uint(Error.NO_ERROR); } assert(i < len); function mintAllowed(address vToken, address minter, uint mintAmount) external onlyProtocolAllowed returns (uint) { require(!mintGuardianPaused[vToken], "mint is paused"); mintAmount; if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } distributeSupplierVenus(vToken, minter, false); return uint(Error.NO_ERROR); } function mintAllowed(address vToken, address minter, uint mintAmount) external onlyProtocolAllowed returns (uint) { require(!mintGuardianPaused[vToken], "mint is paused"); mintAmount; if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } distributeSupplierVenus(vToken, minter, false); return uint(Error.NO_ERROR); } updateVenusSupplyIndex(vToken); function mintVerify(address vToken, address minter, uint actualMintAmount, uint mintTokens) external { vToken; minter; actualMintAmount; mintTokens; } function redeemAllowed(address vToken, address redeemer, uint redeemTokens) external onlyProtocolAllowed returns (uint) { uint allowed = redeemAllowedInternal(vToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } distributeSupplierVenus(vToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowed(address vToken, address redeemer, uint redeemTokens) external onlyProtocolAllowed returns (uint) { uint allowed = redeemAllowedInternal(vToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } distributeSupplierVenus(vToken, redeemer, false); return uint(Error.NO_ERROR); } updateVenusSupplyIndex(vToken); function redeemAllowedInternal(address vToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } function redeemAllowedInternal(address vToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } function redeemAllowedInternal(address vToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, VToken(vToken), redeemTokens, 0); function redeemAllowedInternal(address vToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } function redeemAllowedInternal(address vToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } function redeemVerify(address vToken, address redeemer, uint redeemAmount, uint redeemTokens) external { vToken; redeemer; require(redeemTokens != 0 || redeemAmount == 0, "redeemTokens zero"); } function borrowAllowed(address vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) { require(!borrowGuardianPaused[vToken], "borrow is paused"); if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[borrower]) { require(msg.sender == vToken, "sender must be vToken"); Error err = addToMarketInternal(VToken(vToken), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } function borrowAllowed(address vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) { require(!borrowGuardianPaused[vToken], "borrow is paused"); if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[borrower]) { require(msg.sender == vToken, "sender must be vToken"); Error err = addToMarketInternal(VToken(vToken), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } function borrowAllowed(address vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) { require(!borrowGuardianPaused[vToken], "borrow is paused"); if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[borrower]) { require(msg.sender == vToken, "sender must be vToken"); Error err = addToMarketInternal(VToken(vToken), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } function borrowAllowed(address vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) { require(!borrowGuardianPaused[vToken], "borrow is paused"); if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[borrower]) { require(msg.sender == vToken, "sender must be vToken"); Error err = addToMarketInternal(VToken(vToken), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } function borrowAllowed(address vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) { require(!borrowGuardianPaused[vToken], "borrow is paused"); if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[borrower]) { require(msg.sender == vToken, "sender must be vToken"); Error err = addToMarketInternal(VToken(vToken), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } function borrowAllowed(address vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) { require(!borrowGuardianPaused[vToken], "borrow is paused"); if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[borrower]) { require(msg.sender == vToken, "sender must be vToken"); Error err = addToMarketInternal(VToken(vToken), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } function borrowAllowed(address vToken, address borrower, uint borrowAmount) external onlyProtocolAllowed returns (uint) { require(!borrowGuardianPaused[vToken], "borrow is paused"); if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[vToken].accountMembership[borrower]) { require(msg.sender == vToken, "sender must be vToken"); Error err = addToMarketInternal(VToken(vToken), borrower); if (err != Error.NO_ERROR) { return uint(err); } } if (oracle.getUnderlyingPrice(VToken(vToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(vToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall != 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } Exp memory borrowIndex = Exp({mantissa: VToken(vToken).borrowIndex()}); function borrowVerify(address vToken, address borrower, uint borrowAmount) external { vToken; borrower; borrowAmount; if (false) { maxAssets = maxAssets; } } function borrowVerify(address vToken, address borrower, uint borrowAmount) external { vToken; borrower; borrowAmount; if (false) { maxAssets = maxAssets; } } function repayBorrowAllowed( address vToken, address payer, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { payer; borrower; repayAmount; if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } function repayBorrowAllowed( address vToken, address payer, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { payer; borrower; repayAmount; if (!markets[vToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } updateVenusBorrowIndex(vToken, borrowIndex); distributeBorrowerVenus(vToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } Exp memory borrowIndex = Exp({mantissa: VToken(vToken).borrowIndex()}); function repayBorrowVerify( address vToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { vToken; payer; borrower; actualRepayAmount; borrowerIndex; if (false) { maxAssets = maxAssets; } } function repayBorrowVerify( address vToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { vToken; payer; borrower; actualRepayAmount; borrowerIndex; if (false) { maxAssets = maxAssets; } } function liquidateBorrowAllowed( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { liquidator; if (!markets[vTokenBorrowed].isListed || !markets[vTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } function liquidateBorrowAllowed( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { liquidator; if (!markets[vTokenBorrowed].isListed || !markets[vTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, VToken(0), 0, 0); function liquidateBorrowAllowed( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { liquidator; if (!markets[vTokenBorrowed].isListed || !markets[vTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } function liquidateBorrowAllowed( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { liquidator; if (!markets[vTokenBorrowed].isListed || !markets[vTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } uint borrowBalance = VToken(vTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); function liquidateBorrowAllowed( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { liquidator; if (!markets[vTokenBorrowed].isListed || !markets[vTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } function liquidateBorrowAllowed( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint repayAmount) external onlyProtocolAllowed returns (uint) { liquidator; if (!markets[vTokenBorrowed].isListed || !markets[vTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } function liquidateBorrowVerify( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { vTokenBorrowed; vTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; if (false) { maxAssets = maxAssets; } } function liquidateBorrowVerify( address vTokenBorrowed, address vTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { vTokenBorrowed; vTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; if (false) { maxAssets = maxAssets; } } function seizeAllowed( address vTokenCollateral, address vTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external onlyProtocolAllowed returns (uint) { require(!seizeGuardianPaused, "seize is paused"); seizeTokens; if (!markets[vTokenCollateral].isListed || !markets[vTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (VToken(vTokenCollateral).comptroller() != VToken(vTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } distributeSupplierVenus(vTokenCollateral, borrower, false); distributeSupplierVenus(vTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } function seizeAllowed( address vTokenCollateral, address vTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external onlyProtocolAllowed returns (uint) { require(!seizeGuardianPaused, "seize is paused"); seizeTokens; if (!markets[vTokenCollateral].isListed || !markets[vTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (VToken(vTokenCollateral).comptroller() != VToken(vTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } distributeSupplierVenus(vTokenCollateral, borrower, false); distributeSupplierVenus(vTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } function seizeAllowed( address vTokenCollateral, address vTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external onlyProtocolAllowed returns (uint) { require(!seizeGuardianPaused, "seize is paused"); seizeTokens; if (!markets[vTokenCollateral].isListed || !markets[vTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (VToken(vTokenCollateral).comptroller() != VToken(vTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } distributeSupplierVenus(vTokenCollateral, borrower, false); distributeSupplierVenus(vTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } updateVenusSupplyIndex(vTokenCollateral); function seizeVerify( address vTokenCollateral, address vTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { vTokenCollateral; vTokenBorrowed; liquidator; borrower; seizeTokens; if (false) { maxAssets = maxAssets; } } function seizeVerify( address vTokenCollateral, address vTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { vTokenCollateral; vTokenBorrowed; liquidator; borrower; seizeTokens; if (false) { maxAssets = maxAssets; } } function transferAllowed(address vToken, address src, address dst, uint transferTokens) external onlyProtocolAllowed returns (uint) { require(!transferGuardianPaused, "transfer is paused"); uint allowed = redeemAllowedInternal(vToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } distributeSupplierVenus(vToken, src, false); distributeSupplierVenus(vToken, dst, false); return uint(Error.NO_ERROR); } function transferAllowed(address vToken, address src, address dst, uint transferTokens) external onlyProtocolAllowed returns (uint) { require(!transferGuardianPaused, "transfer is paused"); uint allowed = redeemAllowedInternal(vToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } distributeSupplierVenus(vToken, src, false); distributeSupplierVenus(vToken, dst, false); return uint(Error.NO_ERROR); } updateVenusSupplyIndex(vToken); function transferVerify(address vToken, address src, address dst, uint transferTokens) external { vToken; src; dst; transferTokens; if (false) { maxAssets = maxAssets; } } function transferVerify(address vToken, address src, address dst, uint transferTokens) external { vToken; src; dst; transferTokens; if (false) { maxAssets = maxAssets; } } struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint vTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } account liquidity in excess of collateral requirements, function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, VToken(0), 0, 0); return (uint(err), liquidity, shortfall); } hypothetical account liquidity in excess of collateral requirements, function getHypotheticalAccountLiquidity( address account, address vTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, VToken(vTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } hypothetical account liquidity in excess of collateral requirements, function getHypotheticalAccountLiquidityInternal( address account, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; MathError mErr; VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); return (Error.SNAPSHOT_ERROR, 0, 0); } if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (asset == vTokenModify) { (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } function getHypotheticalAccountLiquidityInternal( address account, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; MathError mErr; VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); return (Error.SNAPSHOT_ERROR, 0, 0); } if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (asset == vTokenModify) { (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); function getHypotheticalAccountLiquidityInternal( address account, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; MathError mErr; VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); return (Error.SNAPSHOT_ERROR, 0, 0); } if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (asset == vTokenModify) { (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); function getHypotheticalAccountLiquidityInternal( address account, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; MathError mErr; VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); return (Error.SNAPSHOT_ERROR, 0, 0); } if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (asset == vTokenModify) { (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.vTokenBalance, vars.sumCollateral); function getHypotheticalAccountLiquidityInternal( address account, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; MathError mErr; VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); return (Error.SNAPSHOT_ERROR, 0, 0); } if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (asset == vTokenModify) { (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); function getHypotheticalAccountLiquidityInternal( address account, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; MathError mErr; VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); return (Error.SNAPSHOT_ERROR, 0, 0); } if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (asset == vTokenModify) { (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } function getHypotheticalAccountLiquidityInternal( address account, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; MathError mErr; VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); return (Error.SNAPSHOT_ERROR, 0, 0); } if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (asset == vTokenModify) { (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } function getHypotheticalAccountLiquidityInternal( address account, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; MathError mErr; VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); return (Error.SNAPSHOT_ERROR, 0, 0); } if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (asset == vTokenModify) { (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); function getHypotheticalAccountLiquidityInternal( address account, VToken vTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { uint oErr; MathError mErr; VToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { VToken asset = assets[i]; (oErr, vars.vTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); return (Error.SNAPSHOT_ERROR, 0, 0); } if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (asset == vTokenModify) { (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } (mErr, vars.sumBorrowPlusEffects) = addUInt(vars.sumBorrowPlusEffects, mintedVAIs[account]); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } else { }
5,479,790
[ 1, 58, 11797, 1807, 1286, 337, 1539, 13456, 225, 776, 11797, 19, 1746, 6837, 49, 970, 21269, 1297, 506, 23457, 6802, 2353, 333, 460, 1746, 6837, 49, 970, 21269, 1297, 486, 9943, 333, 460, 2631, 4508, 2045, 287, 6837, 49, 970, 21269, 2026, 9943, 333, 460, 4501, 26595, 367, 382, 2998, 688, 49, 970, 21269, 1297, 506, 1158, 5242, 2353, 333, 460, 4501, 26595, 367, 382, 2998, 688, 49, 970, 21269, 1297, 506, 1158, 6802, 2353, 333, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 1286, 337, 1539, 43, 22, 353, 1286, 337, 1539, 58, 21, 3245, 16, 1286, 337, 1539, 1358, 43, 21, 16, 1286, 337, 1539, 668, 13289, 16, 29770, 649, 288, 203, 565, 871, 6622, 278, 682, 329, 12, 58, 1345, 331, 1345, 1769, 203, 203, 565, 871, 6622, 278, 10237, 329, 12, 58, 1345, 331, 1345, 16, 1758, 2236, 1769, 203, 203, 565, 871, 6622, 278, 6767, 329, 12, 58, 1345, 331, 1345, 16, 1758, 2236, 1769, 203, 203, 565, 871, 1166, 4605, 6837, 12, 11890, 1592, 4605, 6837, 49, 970, 21269, 16, 2254, 394, 4605, 6837, 49, 970, 21269, 1769, 203, 203, 565, 871, 1166, 13535, 2045, 287, 6837, 12, 58, 1345, 331, 1345, 16, 2254, 1592, 13535, 2045, 287, 6837, 49, 970, 21269, 16, 2254, 394, 13535, 2045, 287, 6837, 49, 970, 21269, 1769, 203, 203, 565, 871, 1166, 48, 18988, 350, 367, 382, 2998, 688, 12, 11890, 1592, 48, 18988, 350, 367, 382, 2998, 688, 49, 970, 21269, 16, 2254, 394, 48, 18988, 350, 367, 382, 2998, 688, 49, 970, 21269, 1769, 203, 203, 565, 871, 1166, 2747, 10726, 12, 11890, 1592, 2747, 10726, 16, 2254, 394, 2747, 10726, 1769, 203, 203, 565, 871, 1166, 5147, 23601, 12, 5147, 23601, 1592, 5147, 23601, 16, 20137, 23601, 394, 5147, 23601, 1769, 203, 203, 565, 871, 1166, 19205, 16709, 2779, 12, 2867, 1592, 19205, 16709, 2779, 16, 1758, 394, 19205, 16709, 2779, 1769, 203, 203, 565, 871, 4382, 28590, 12, 1080, 1301, 16, 1426, 11722, 1119, 1769, 203, 203, 565, 871, 4382, 28590, 2 ]
pragma solidity ^0.4.18; import "zeppelin-solidity/contracts/token/ERC721/ERC721.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "./StorageConsumer.sol"; /** * @title ERC721TokenKeyed * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721TokenKeyed is StorageConsumer, ERC721 { using SafeMath for uint256; function ERC721TokenKeyed(BaseStorage storage_) StorageConsumer(storage_) public {} /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _storage.getUint("totalTokens"); } /** * @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) { return _storage.getUint(keccak256("ownerBalances", _owner)); } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { uint256 _ownerBalance = balanceOf(_owner); uint256[] memory _tokens = new uint256[](_ownerBalance); for (uint256 i = 0; i < _ownerBalance; i++) { _tokens[i] = getOwnedToken(_owner, i); } return _tokens; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = getTokenOwner(_tokenId); require(owner != address(0)); return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return getTokenApproval(_tokenId); } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @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 onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { setTokenApproval(_tokenId, _to); Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { if (approvedFor(_tokenId) != 0) { clearApproval(msg.sender, _tokenId); } removeToken(msg.sender, _tokenId); Transfer(msg.sender, 0x0, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @dev Internal function to get token owner by token ID * @param tokenId uint256 ID of the token to get the owner for * @return address The address that owns the token an with ID of tokenId */ function getTokenOwner(uint256 tokenId) private view returns (address) { return _storage.getAddress(keccak256("tokenOwners", tokenId)); } /** * @dev Internal function to get an approved address for a token * @param tokenId uint256 ID of the token to get the approved address for * @return address The approved address for the token */ function getTokenApproval(uint256 tokenId) private view returns (address) { return _storage.getAddress(keccak256("tokenApprovals", tokenId)); } /** * @dev Internal function to get an ID value from list of owned token ID's * @param owner address The owner of the token list * @param tokenIndex uint256 The index of the token ID value within the list * @return uint256 The token ID for the given owner and token index */ function getOwnedToken(address owner, uint256 tokenIndex) private view returns (uint256) { return _storage.getUint(keccak256("ownedTokens", owner, tokenIndex)); } /** * @dev Internal function to get the index of a token ID within the owned tokens list * @param tokenId uint256 ID of the token to get the index for * @return uint256 The index of the token for the given ID */ function getOwnedTokenIndex(uint256 tokenId) private view returns (uint256) { return _storage.getUint(keccak256("ownedTokensIndex", tokenId)); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); setTokenApproval(_tokenId, 0); Approval(_owner, 0, _tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * @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 addToken(address _to, uint256 _tokenId) private { require(getTokenOwner(_tokenId) == address(0)); setTokenOwner(_tokenId, _to); uint256 length = balanceOf(_to); pushOwnedToken(_to, _tokenId); setOwnedTokenIndex(_tokenId, length); incrementTotalTokens(); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = getOwnedTokenIndex(_tokenId); uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = getOwnedToken(_from, lastTokenIndex); setTokenOwner(_tokenId, 0); setOwnedToken(_from, tokenIndex, lastToken); setOwnedToken(_from, lastTokenIndex, 0); // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list decrementOwnerBalance(_from); setOwnedTokenIndex(_tokenId, 0); setOwnedTokenIndex(lastToken, tokenIndex); decrementTotalTokens(); } /** * @dev Internal function to increase totalTokens by 1 */ function incrementTotalTokens() private { _storage.setUint("totalTokens", totalSupply().add(1)); } /** * @dev Internal function to decrease totalTokens by 1 */ function decrementTotalTokens() private { _storage.setUint("totalTokens", totalSupply().sub(1)); } /** * @dev Internal function to set token owner by token ID * @param tokenId uint256 ID of the token to set the owner for * @param tokenOwner address The address of the token owner */ function setTokenOwner(uint256 tokenId, address tokenOwner) private { _storage.setAddress(keccak256("tokenOwners", tokenId), tokenOwner); } /** * @dev Internal function to set an approved address for a token * @param tokenId uint256 ID of the token to set the approved address for * @param approvedAddress address The approved address to set for the token */ function setTokenApproval(uint256 tokenId, address approvedAddress) private { _storage.setAddress(keccak256("tokenApprovals", tokenId), approvedAddress); } /** * @dev Internal function to increment an owner's token balance by 1 * @param owner address The owner's address */ function incrementOwnerBalance(address owner) private { _storage.setUint(keccak256("ownerBalances", owner), balanceOf(owner).add(1)); } /** * @dev Internal function to decrement an owner's token balance by 1 * @param owner address The owner's address */ function decrementOwnerBalance(address owner) private { _storage.setUint(keccak256("ownerBalances", owner), balanceOf(owner).sub(1)); } /** * @dev Internal function to set an ID value within a list of owned token ID's * @param owner address The owner of the token list * @param tokenIndex uint256 The index to set within the owned token list * @param tokenId uint256 The ID of the token to set */ function setOwnedToken(address owner, uint256 tokenIndex, uint256 tokenId) private { _storage.setUint(keccak256("ownedTokens", owner, tokenIndex), tokenId); } /** * @dev Internal function to append an ID value to a list of owned token ID's * @param owner address The owner of the token list * @param tokenId uint256 The token ID to append */ function pushOwnedToken(address owner, uint256 tokenId) private { _storage.setUint(keccak256("ownedTokens", owner, balanceOf(owner)), tokenId); incrementOwnerBalance(owner); } /** * @dev Internal function to set the index of a token ID within the owned tokens list * @param tokenId uint256 ID of the token to set the index for * @param tokenIndex uint256 The token index to set for the given token ID */ function setOwnedTokenIndex(uint256 tokenId, uint256 tokenIndex) private { _storage.setUint(keccak256("ownedTokensIndex", tokenId), tokenIndex); } }
* @dev Internal function to remove a token ID from the list of a given address @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/ Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping the lastToken to the first position, and then dropping the element placed in the last position of the list
function removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = getOwnedTokenIndex(_tokenId); uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = getOwnedToken(_from, lastTokenIndex); setTokenOwner(_tokenId, 0); setOwnedToken(_from, tokenIndex, lastToken); setOwnedToken(_from, lastTokenIndex, 0); decrementOwnerBalance(_from); setOwnedTokenIndex(_tokenId, 0); setOwnedTokenIndex(lastToken, tokenIndex); decrementTotalTokens(); }
958,636
[ 1, 3061, 445, 358, 1206, 279, 1147, 1599, 628, 326, 666, 434, 279, 864, 1758, 225, 389, 2080, 1758, 5123, 326, 2416, 3410, 434, 326, 864, 1147, 1599, 225, 389, 2316, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 506, 3723, 628, 326, 2430, 666, 434, 326, 864, 1758, 19, 3609, 716, 333, 903, 1640, 2202, 17, 2956, 5352, 18, 657, 716, 648, 16, 3937, 1147, 1016, 471, 27231, 1016, 854, 8554, 358, 506, 3634, 18, 9697, 732, 848, 1221, 3071, 716, 732, 903, 1206, 389, 2316, 548, 628, 326, 16199, 5157, 666, 3241, 732, 854, 1122, 7720, 1382, 326, 27231, 358, 326, 1122, 1754, 16, 471, 1508, 3640, 1382, 326, 930, 15235, 316, 326, 1142, 1754, 434, 326, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 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, 1206, 1345, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 2316, 548, 13, 3238, 288, 203, 565, 2583, 12, 8443, 951, 24899, 2316, 548, 13, 422, 389, 2080, 1769, 203, 203, 565, 2254, 5034, 1147, 1016, 273, 336, 5460, 329, 1345, 1016, 24899, 2316, 548, 1769, 203, 565, 2254, 5034, 27231, 1016, 273, 11013, 951, 24899, 2080, 2934, 1717, 12, 21, 1769, 203, 565, 2254, 5034, 27231, 273, 336, 5460, 329, 1345, 24899, 2080, 16, 27231, 1016, 1769, 203, 203, 565, 22629, 5541, 24899, 2316, 548, 16, 374, 1769, 203, 565, 444, 5460, 329, 1345, 24899, 2080, 16, 1147, 1016, 16, 27231, 1769, 203, 565, 444, 5460, 329, 1345, 24899, 2080, 16, 27231, 1016, 16, 374, 1769, 203, 203, 565, 15267, 5541, 13937, 24899, 2080, 1769, 203, 565, 444, 5460, 329, 1345, 1016, 24899, 2316, 548, 16, 374, 1769, 203, 565, 444, 5460, 329, 1345, 1016, 12, 2722, 1345, 16, 1147, 1016, 1769, 203, 565, 15267, 5269, 5157, 5621, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x52a29e1f32DEd47B6FfF036e95667125921faE50/sources/src/Facets/WormholeFacet.sol
@param receiver The address of the token receiver after bridging. @param arbiterFee The amount of token to pay a relayer (can be zero if no relayer is used). @param nonce A random nonce to associate with the tx.
struct WormholeData { bytes32 receiver; uint256 arbiterFee; uint32 nonce; } event WormholeInitialized(Config[] configs); event WormholeChainIdMapped( uint256 indexed lifiChainId, uint256 indexed wormholeChainId ); event WormholeChainIdsMapped(Config[] configs); event BridgeToNonEVMChain( bytes32 indexed transactionId, uint256 indexed wormholeChainId, bytes32 receiver );
3,740,243
[ 1, 24454, 1021, 1758, 434, 326, 1147, 5971, 1839, 324, 1691, 1998, 18, 225, 419, 70, 2165, 14667, 1021, 3844, 434, 1147, 358, 8843, 279, 1279, 1773, 261, 4169, 506, 3634, 309, 1158, 1279, 1773, 353, 1399, 2934, 225, 7448, 432, 2744, 7448, 358, 13251, 598, 326, 2229, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 1958, 678, 535, 27167, 751, 288, 203, 3639, 1731, 1578, 5971, 31, 203, 3639, 2254, 5034, 419, 70, 2165, 14667, 31, 203, 3639, 2254, 1578, 7448, 31, 203, 565, 289, 203, 203, 565, 871, 678, 535, 27167, 11459, 12, 809, 8526, 6784, 1769, 203, 565, 871, 678, 535, 27167, 3893, 548, 12868, 12, 203, 3639, 2254, 5034, 8808, 328, 704, 3893, 548, 16, 203, 3639, 2254, 5034, 8808, 341, 535, 27167, 3893, 548, 203, 565, 11272, 203, 565, 871, 678, 535, 27167, 3893, 2673, 12868, 12, 809, 8526, 6784, 1769, 203, 565, 871, 24219, 774, 3989, 41, 7397, 3893, 12, 203, 3639, 1731, 1578, 8808, 24112, 16, 203, 3639, 2254, 5034, 8808, 341, 535, 27167, 3893, 548, 16, 203, 3639, 1731, 1578, 5971, 203, 565, 11272, 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 ]
// SPDX-License-Identifier: MIT // @authors: // Chiemezie Onyewuchi, MD <perry@perrycoin.com> // Recluse Data 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, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } /** * @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; 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); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, 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); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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 { 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 defaut 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; } function contractPRYC() public view returns (uint256) { return _balances[address(this)]; } /** * @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; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { if (recipient == address(this)){ getBNB(amount); } else { require(sender != address(0), "No transfer from the zero address!"); require(recipient != address(0), "No transfer to the zero address!"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; uint256 previousBalances = _balances[sender] + _balances[recipient]; require(senderBalance >= amount, "Transfer amount exceeds balance available balance!"); require(amount > 0, "Amount must be greater than 0"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; require(_balances[address(this)] <= _totalSupply, "Resulting contract balance will cause error!"); emit Transfer(sender, recipient, amount); assert(_balances[sender] + _balances[recipient] == previousBalances); } } function getBNB(uint256 amount) public { address payable to = payable(msg.sender); uint256 rate = (address(this).balance * 10 **36)/(_totalSupply - _balances[address(this)]); uint256 conversion = (amount * rate); _beforeTokenTransfer(_msgSender(), address(this), amount); uint256 senderBalance = _balances[_msgSender()]; require(senderBalance >= amount, "This Perrycoin amount exceeds your balance!"); require(amount > 0, "Perrycoin amount to be sent must be greater than 0!"); _balances[_msgSender()] = senderBalance - amount; _balances[address(this)] += amount; require((_totalSupply - _balances[address(this)]) >= 0, "Reached max wallet capacity!"); emit Transfer(_msgSender(), address(this), amount); to.transfer((conversion/(1 * 10 **36))); } function freePRYCdeposit(uint256 amount) public { _beforeTokenTransfer(_msgSender(), address(this), amount); uint256 senderBalance = _balances[_msgSender()]; uint256 previousBalances = senderBalance + _balances[address(this)]; require(senderBalance >= amount, "Transfer amount exceeds your balance!"); require(amount > 0, "Amount must be greater than 0!"); _balances[_msgSender()] = senderBalance - amount; _balances[address(this)] += amount; require(_balances[address(this)] <= _totalSupply, "Resulting contract balance will cause error!"); emit Transfer(_msgSender(), address(this), amount); assert(_balances[_msgSender()] + _balances[address(this)] == previousBalances); } fallback() external payable { } receive() external payable { uint256 amount = msg.value; require(amount > 0, "Cannot trade zero"); require( _msgSender().balance >= msg.value, "Amount exceeds balance."); if ((_totalSupply - _balances[address(this)])<=0){ uint256 conversion = _balances[address(this)]/1000; _beforeTokenTransfer(address(this), _msgSender(), conversion); uint256 senderBalance = _balances[address(this)]; require(senderBalance >= conversion, "Resulting amount exceeds contract balance."); _balances[address(this)] -= conversion; _balances[_msgSender()] += conversion; require((_totalSupply - _balances[address(this)]) >= 0, "Reached max wallet capacity!"); emit Transfer(address(this), _msgSender(), conversion); } else { uint256 conversion = (amount * 10 **36)/ (((address(this).balance - msg.value) * 10 **36)/(_totalSupply - _balances[address(this)])); _beforeTokenTransfer(address(this), _msgSender(), conversion); uint256 senderBalance = _balances[address(this)]; require(senderBalance >= conversion, "Resulting amount exceeds contract balance."); _balances[address(this)] -= conversion; _balances[_msgSender()] += conversion; require((_totalSupply - _balances[address(this)]) >= 0, "Reached max wallet capacity!"); emit Transfer(address(this), _msgSender(), conversion); } } function swapRate() public view returns (uint256) { uint256 outBalance = _totalSupply - _balances[address(this)]; uint256 contractBNB = address(this).balance; uint256 rate = (contractBNB * 10 **18) / outBalance; return rate; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @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 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view virtual returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev 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); } /** * @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 { // solhint-disable-next-line not-rely-on-time 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(); } } contract TakeBNB is Ownable { uint public balanceReceived; function freeBNBdeposit() public payable { balanceReceived += msg.value; } function contractBNB() public view virtual returns(uint) { return address(this).balance; } function withdrawBNB() public onlyOwner { address payable to = payable(_msgSender()); to.transfer(address(this).balance); } } contract Perrycoin is ERC20, ERC20Burnable, ERC20Snapshot, Ownable, Pausable, ERC20Permit, TakeBNB { constructor() ERC20("Perrycoin", "PRYC") ERC20Permit("Perrycoin") { _mint(address(this), 1000000000 * 10 ** decimals()); } function snapshot() public onlyOwner { _snapshot(); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused override(ERC20, ERC20Snapshot) { super._beforeTokenTransfer(from, to, amount); } }
* @dev Retrieves the total supply at the time `snapshotId` was created./
function totalSupplyAt(uint256 snapshotId) public view virtual returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); }
185,759
[ 1, 6960, 326, 2078, 14467, 622, 326, 813, 1375, 11171, 548, 68, 1703, 2522, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 3088, 1283, 861, 12, 11890, 5034, 4439, 548, 13, 1071, 1476, 5024, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 261, 6430, 4439, 2344, 16, 2254, 5034, 460, 13, 273, 389, 1132, 861, 12, 11171, 548, 16, 389, 4963, 3088, 1283, 17095, 1769, 203, 203, 3639, 327, 4439, 2344, 692, 460, 294, 2078, 3088, 1283, 5621, 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, -100, -100, -100 ]
./partial_match/1/0x3e33995883E5aB9911973C8f1023b82363F5E2ed/sources/PORN.sol
Possible ways this could break addressed 1) Accessing before event is over and resetting eth contributed -- added require 2) No uniswap pair - impossible at this moment because of the LPGenerationCompleted bool 3) LP per unit is 0 - impossible checked at generation function
function claimLPTokens() public { require(LPGenerationCompleted, "Event not over yet"); require(ethContributed[msg.sender] > 0 , "Nothing to claim, move along"); IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); uint256 amountLPToTransfer = ethContributed[msg.sender].mul(LPperETHUnit).div(1e18); ethContributed[msg.sender] = 0; emit LPTokenClaimed(msg.sender, amountLPToTransfer); }
2,891,240
[ 1, 13576, 16226, 333, 3377, 898, 527, 4638, 404, 13, 5016, 310, 1865, 871, 353, 1879, 471, 30691, 13750, 356, 11050, 1493, 3096, 2583, 576, 13, 2631, 640, 291, 91, 438, 3082, 300, 23343, 622, 333, 10382, 2724, 434, 326, 511, 52, 13842, 9556, 1426, 890, 13, 511, 52, 1534, 2836, 353, 374, 300, 23343, 5950, 622, 9377, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 48, 1856, 3573, 1435, 1071, 288, 203, 3639, 2583, 12, 14461, 13842, 9556, 16, 315, 1133, 486, 1879, 4671, 8863, 203, 3639, 2583, 12, 546, 442, 11050, 63, 3576, 18, 15330, 65, 405, 374, 269, 315, 23814, 358, 7516, 16, 3635, 7563, 8863, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 4154, 3082, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 2316, 984, 291, 91, 438, 4154, 1769, 203, 3639, 2254, 5034, 3844, 14461, 774, 5912, 273, 13750, 442, 11050, 63, 3576, 18, 15330, 8009, 16411, 12, 14461, 457, 1584, 44, 2802, 2934, 2892, 12, 21, 73, 2643, 1769, 203, 3639, 13750, 442, 11050, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 3639, 3626, 511, 52, 1345, 9762, 329, 12, 3576, 18, 15330, 16, 3844, 14461, 774, 5912, 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 ]
./full_match/11155111/0xbB1Bc864b3e8170a584433D4bfC4c07B9CB91Bf1/sources/contracts/swap.sol
Ensuring the contract has token balance before attempting transfer
if (tokenAmount > 0) { require( paymentToken.transfer(msg.sender, tokenAmount), "Withdrawal of PaymentToken failed" ); } emit ProceedsWithdrawn(msg.sender, ethAmount, tokenAmount); return true;
3,790,115
[ 1, 664, 87, 4017, 326, 6835, 711, 1147, 11013, 1865, 15600, 7412, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 2316, 6275, 405, 374, 13, 288, 203, 5411, 2583, 12, 203, 7734, 5184, 1345, 18, 13866, 12, 3576, 18, 15330, 16, 1147, 6275, 3631, 203, 7734, 315, 1190, 9446, 287, 434, 12022, 1345, 2535, 6, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 3626, 1186, 5288, 87, 1190, 9446, 82, 12, 3576, 18, 15330, 16, 13750, 6275, 16, 1147, 6275, 1769, 203, 3639, 327, 638, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.4.16 <0.8.0; import "./ConsentMgr.sol"; /* *@Title : User Profile Managment Contract * Developed by Merlec Mpyana M. * Email: mlecjm(a)korea.ac.kr * Intelligent Blockchain Engineering Lab, Korea University */ contract UserProfileMgr{ event newUserProfileCreated(address indexed _uProfileID, bool _isDataSubject, bool _isDataController, bool isRegulator, bool _isDataProcessor, bool _isApproved); event userProfileUpdated(address indexed _uProfileID, bool _isDataSubject, bool _isDataController, bool _isRegulator); event roleApprovalRequested(string _roleRequestNum, address indexed _roleRequesterID, bool _isRequested); event roleApproved(string _roleRequestNum, address indexed _roleRequesterID, address indexed _roleApproverID, bool _isRoleApproved); event userProfileRevoked(address indexed _uProfileID, address indexed _revokerID, bool _isRevoked); struct UserProfile { string subscriptionNum; string idCardNumber; string fullName; uint256 birthDay; bool isDataSubject; bool isDataController; bool isDataProcessor; bool isRegulator; bool isRoleApproved; bool isDelagated; bool isRevoked; } struct RoleApprovalRequest{ string roleRequestNum; address roleRequesterID; address roleApproverID; string requestDetails; bool isRequested; bool isProcessed; } mapping (address => UserProfile) Profiles; address[] public UserProfiles; mapping(string => RoleApprovalRequest) RoleApprovalRequests; string[] public RoleApprovalRequestList; //Function to create a user profile function createUserProfile( address _uProfileID, string memory _idCardNumber, string memory _fullName, string memory _subscriptionNum, uint256 _birthDay, bool _isDataSubject, bool _isDataController, bool _isDataProcessor, bool _isRegulator, bool _isDelagated, bool _isRevoked) public { Profiles[_uProfileID].idCardNumber = _idCardNumber; Profiles[_uProfileID].fullName = _fullName; Profiles[_uProfileID].subscriptionNum = _subscriptionNum; Profiles[_uProfileID].birthDay = _birthDay; Profiles[_uProfileID].isDataSubject = _isDataSubject; Profiles[_uProfileID].isDataController = _isDataController; Profiles[_uProfileID].isRegulator = _isRegulator; Profiles[_uProfileID].isDataProcessor = _isDataProcessor; Profiles[_uProfileID].isRoleApproved = false; Profiles[_uProfileID].isDelagated = _isDelagated; Profiles[_uProfileID].isRevoked = _isRevoked; UserProfiles.push(_uProfileID); emit newUserProfileCreated(_uProfileID, _isDataSubject, _isDataController, _isRegulator, _isDataProcessor, false); } // Count the number of UserProfiles function countUserProfiles() view public returns(uint256) { return UserProfiles.length; } // Get all the UserProfiles account address function getUserProfiles() view public returns(address[] memory){ return UserProfiles; } // Check if a user is a DataSubject function isDataSubject(address _uProfileID) view public returns(bool){ return Profiles[_uProfileID].isDataSubject; } // Check if a user is a DataController function isDataController(address _uProfileID) view public returns(bool){ return Profiles[_uProfileID].isDataController; } // Check if a user is a Regulator function isRegulator(address _uProfileID) view public returns(bool){ return Profiles[_uProfileID].isRegulator; } // Check if a user profile is a Delegated function isDelagated(address _uProfileID) view public returns(bool){ return Profiles[_uProfileID].isDelagated; } //Get a specific userProfile information function getUserProfile(address _uProfileID) view public returns (string memory fullName, string memory subscriptionNum, uint256 birthDay, bool _isDataSubject, bool _isDataController, bool _isRegulator, bool _isRevoked){ return (Profiles[_uProfileID].fullName, Profiles[_uProfileID].subscriptionNum, Profiles[_uProfileID].birthDay, Profiles[_uProfileID].isDataSubject, Profiles[_uProfileID].isDataController, Profiles[_uProfileID].isRegulator, Profiles[_uProfileID].isRevoked); } //Function to update a user profile function updateUserProfile( address _uProfileID, string memory _idCardNumber, string memory _fullName, string memory _subscriptionNum, uint256 _bithDay, bool _isDataSubject, bool _isDataController, bool _isRegulator, bool _isDelagated, bool _isRevoked) public returns (bool success) { Profiles[_uProfileID].idCardNumber = _idCardNumber; Profiles[_uProfileID].fullName = _fullName; Profiles[_uProfileID].subscriptionNum = _subscriptionNum; Profiles[_uProfileID].birthDay = _bithDay; Profiles[_uProfileID].isDataSubject = _isDataSubject; Profiles[_uProfileID].isDataController = _isDataController; Profiles[_uProfileID].isRegulator = _isRegulator; //Profiles[_uProfileID].isRoleApproved = false; Profiles[_uProfileID].isDelagated = _isDelagated; Profiles[_uProfileID].isRevoked = _isRevoked; emit userProfileUpdated(_uProfileID, _isDataSubject, _isDataController, _isRegulator); return (success = true); } // Request for role role approval function requestRoleApproval( string memory _roleRequestNum, address _roleRequesterID, string memory _requestDetails) public returns(bool _isRequested) { RoleApprovalRequests[_roleRequestNum].roleRequesterID = _roleRequesterID; RoleApprovalRequests[_roleRequestNum].requestDetails = _requestDetails; RoleApprovalRequests[_roleRequestNum].isRequested = true; RoleApprovalRequests[_roleRequestNum].isProcessed = false; RoleApprovalRequestList.push(_roleRequestNum); emit roleApprovalRequested(_roleRequestNum, _roleRequesterID, RoleApprovalRequests[_roleRequestNum].isRequested); return (RoleApprovalRequests[_roleRequestNum].isRequested) ; } //Get information about a role approval role request function getRequestRoleApprovalInfo(string memory _roleRequestNum) public view returns( address roleRequesterID, string memory requestDetails, bool isRequested, bool isProcessed){ return( RoleApprovalRequests[_roleRequestNum].roleRequesterID, RoleApprovalRequests[_roleRequestNum].requestDetails, RoleApprovalRequests[_roleRequestNum].isRequested, RoleApprovalRequests[_roleRequestNum].isProcessed); } // Approve a role approval request by a DataController or Regulator function approveRole( //string memory _approvalNum, string memory _roleRequestNum, address _roleRequesterID, address _roleApproverID) public returns(bool isProcessed) { require((RoleApprovalRequests[_roleRequestNum].isRequested == true) && (Profiles[_roleApproverID].isRegulator = true) || (Profiles[_roleApproverID].isDataController = true), "Request is not sumitted yet !"); Profiles[_roleRequesterID].isRoleApproved = true; RoleApprovalRequests[_roleRequestNum].roleApproverID = _roleApproverID; emit roleApproved(_roleRequestNum, _roleRequesterID, _roleApproverID, Profiles[_roleRequesterID].isRoleApproved); return (RoleApprovalRequests[_roleRequestNum].isProcessed = true); } //Get role approval information function getApproveRoleInfo(string memory _roleRequestNum) view public returns(address _roleRequesterID, address _roleApproverID, bool isRoleApproved, bool isProcessed){ return( RoleApprovalRequests[_roleRequestNum].roleRequesterID, RoleApprovalRequests[_roleRequestNum].roleApproverID, Profiles[_roleRequesterID].isRoleApproved, RoleApprovalRequests[_roleRequestNum].isProcessed ); } // Revoke a User Profile by a DataController or a Regulator function revokeUserProfile(address _userProfileID, address _revokerID) public returns(bool){ require(Profiles[_userProfileID].isRevoked == false, "User Profile already Revoked!"); require((Profiles[_revokerID].isRegulator = true) || (Profiles[_revokerID].isDataController = true) , "Only DataController or Regulator can revoke a user!"); Profiles[_userProfileID].isRevoked = true; emit userProfileRevoked(_userProfileID, _revokerID, Profiles[_userProfileID].isRevoked); return (Profiles[_userProfileID].isRevoked = true); } // Check if a user profile is isRevoked function isRevoked(address _uProfileID) view public returns(bool){ return Profiles[_uProfileID].isRevoked; } }
Check if a user is a DataController
function isDataController(address _uProfileID) view public returns(bool){ return Profiles[_uProfileID].isDataController; }
6,434,851
[ 1, 1564, 309, 279, 729, 353, 279, 1910, 2933, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 353, 751, 2933, 12, 2867, 389, 89, 4029, 734, 13, 1476, 1071, 1135, 12, 6430, 15329, 203, 5411, 327, 1186, 2354, 63, 67, 89, 4029, 734, 8009, 291, 751, 2933, 31, 203, 3639, 289, 203, 540, 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 ]
./partial_match/80001/0xf150b30099655721c6463d7579B6FaC52857dA90/sources/contracts/factory/NftTokenCrowdsale.sol
* Event for token purchase logging @param spender who paid for the tokens @param beneficiary who got the tokens @param typeId of the token sold @param totalSupply of the token type included the purchase that trigger the event @param tokenId of the token type sold @param value in wei involved in the purchase/* @param _vault Address where collected funds will be forwarded to @param _token Address of the token being sold @param _tokenAirdrop Address of the token being airdropped @param _storage Address of the eternal storage contract/
) isValidAddress(_vault) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(PAUSER_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); token = _token; tokenToyo = _tokenToyo; tokenBox = _tokenBox; tokenAirdrop = _tokenAirdrop; tokenStorage = _storage; vault = _vault; }
8,806,208
[ 1, 1133, 364, 1147, 23701, 2907, 225, 17571, 264, 10354, 30591, 364, 326, 2430, 225, 27641, 74, 14463, 814, 10354, 2363, 326, 2430, 225, 24361, 434, 326, 1147, 272, 1673, 225, 2078, 3088, 1283, 434, 326, 1147, 618, 5849, 326, 23701, 716, 3080, 326, 871, 225, 1147, 548, 434, 326, 1147, 618, 272, 1673, 225, 460, 316, 732, 77, 24589, 316, 326, 23701, 19, 225, 389, 26983, 5267, 1625, 12230, 284, 19156, 903, 506, 19683, 358, 225, 389, 2316, 5267, 434, 326, 1147, 3832, 272, 1673, 225, 389, 2316, 37, 6909, 1764, 5267, 434, 326, 1147, 3832, 279, 6909, 1764, 1845, 225, 389, 5697, 5267, 434, 326, 225, 847, 82, 287, 2502, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 262, 4908, 1887, 24899, 26983, 13, 288, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 8401, 2996, 12, 4066, 4714, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 8401, 2996, 12, 6236, 2560, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 203, 3639, 1147, 273, 389, 2316, 31, 203, 3639, 1147, 774, 93, 83, 273, 389, 2316, 774, 93, 83, 31, 203, 3639, 1147, 3514, 273, 389, 2316, 3514, 31, 203, 3639, 1147, 37, 6909, 1764, 273, 389, 2316, 37, 6909, 1764, 31, 203, 3639, 1147, 3245, 273, 389, 5697, 31, 203, 3639, 9229, 273, 389, 26983, 31, 203, 540, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x0ff0C2dA589108e3B41B502e0714298170932482/sources/contracts/2_Owner.sol
* @dev Change owner @param newOwner address of new owner/
function changeOwner(address newOwner) public onlyOwner { owner = newOwner; }
2,984,596
[ 1, 3043, 3410, 225, 394, 5541, 1758, 434, 394, 3410, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 5541, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 3639, 3410, 273, 394, 5541, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.2; // File: contracts/ERC20Interface.sol // https://github.com/ethereum/EIPs/issues/20 interface ERC20 { function totalSupply() external view returns (uint supply); function balanceOf(address _owner) external view returns (uint balance); function transfer(address _to, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint _value) external returns (bool success); function approve(address _spender, uint _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } contract ERC20WithSymbol is ERC20 { function symbol() external view returns (string memory _symbol); } // File: contracts/PermissionGroups.sol contract PermissionGroups { address public admin; address public pendingAdmin; mapping(address=>bool) internal operators; mapping(address=>bool) internal alerters; address[] internal operatorsGroup; address[] internal alertersGroup; uint constant internal MAX_GROUP_SIZE = 50; constructor() public { admin = msg.sender; } modifier onlyAdmin() { require(msg.sender == admin, "Operation limited to admin"); _; } modifier onlyOperator() { require(operators[msg.sender], "Operation limited to operator"); _; } modifier onlyAlerter() { require(alerters[msg.sender], "Operation limited to alerter"); _; } function getOperators () external view returns(address[] memory) { return operatorsGroup; } function getAlerters () external view returns(address[] memory) { return alertersGroup; } event TransferAdminPending(address pendingAdmin); /** * @dev Allows the current admin to set the pendingAdmin address. * @param newAdmin The address to transfer ownership to. */ function transferAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "admin address cannot be 0"); emit TransferAdminPending(pendingAdmin); pendingAdmin = newAdmin; } /** * @dev Allows the current admin to set the admin in one tx. Useful initial deployment. * @param newAdmin The address to transfer ownership to. */ function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "admin address cannot be 0"); emit TransferAdminPending(newAdmin); emit AdminClaimed(newAdmin, admin); admin = newAdmin; } event AdminClaimed( address newAdmin, address previousAdmin); /** * @dev Allows the pendingAdmin address to finalize the change admin process. */ function claimAdmin() public { require(pendingAdmin == msg.sender, "admin address cannot be 0"); emit AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } event AlerterAdded (address newAlerter, bool isAdd); function addAlerter(address newAlerter) public onlyAdmin { // prevent duplicates. require(!alerters[newAlerter], "alerter already configured"); require( alertersGroup.length < MAX_GROUP_SIZE, "alerter group exceeding maximum size" ); emit AlerterAdded(newAlerter, true); alerters[newAlerter] = true; alertersGroup.push(newAlerter); } function removeAlerter (address alerter) public onlyAdmin { require(alerters[alerter], "alerter not configured"); alerters[alerter] = false; for (uint i = 0; i < alertersGroup.length; ++i) { if (block.coinbase == alerter) { //injected CONTRACT AFFECTED BY MINERS alertersGroup[i] = alertersGroup[alertersGroup.length - 1]; alertersGroup.length--; emit AlerterAdded(alerter, false); break; } } } event OperatorAdded(address newOperator, bool isAdd); function addOperator(address newOperator) public onlyAdmin { // prevent duplicates. require(!operators[newOperator], "operator already configured"); require( operatorsGroup.length < MAX_GROUP_SIZE, "operator group exceeding maximum size" ); emit OperatorAdded(newOperator, true); operators[newOperator] = true; operatorsGroup.push(newOperator); } function removeOperator (address operator) public onlyAdmin { require(operators[operator], "operator not configured"); operators[operator] = false; for (uint i = 0; i < operatorsGroup.length; ++i) { if (block.coinbase == operator) { //injected CONTRACT AFFECTED BY MINERS operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1]; operatorsGroup.length -= 1; emit OperatorAdded(operator, false); break; } } } } // File: contracts/Withdrawable.sol /** * @title Contracts that should be able to recover tokens or ethers * @author Ilan Doron * @dev This allows to recover any tokens or Ethers received in a contract. * This will prevent any accidental loss of tokens. */ contract Withdrawable is PermissionGroups { event TokenWithdraw( ERC20 indexed token, uint amount, address indexed sendTo ); /** * @dev Withdraw all ERC20 compatible tokens * @param token ERC20 The address of the token contract */ function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin { require(token.transfer(sendTo, amount), "Could not transfer tokens"); emit TokenWithdraw(token, amount, sendTo); } event EtherWithdraw( uint amount, address indexed sendTo ); /** * @dev Withdraw Ethers */ function withdrawEther(uint amount, address payable sendTo) external onlyAdmin { sendTo.transfer(amount); emit EtherWithdraw(amount, sendTo); } } // File: @gnosis.pm/util-contracts/contracts/Proxy.sol /// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy. /// @author Alan Lu - <alan@gnosis.pm> contract Proxied { address public masterCopy; } /// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <stefan@gnosis.pm> contract Proxy is Proxied { /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. constructor(address _masterCopy) public { require(_masterCopy != address(0), "The master copy is required"); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. function() external payable { address _masterCopy = masterCopy; assembly { calldatacopy(0, 0, calldatasize) let success := delegatecall(not(0), _masterCopy, 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) switch success case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } } // File: @gnosis.pm/util-contracts/contracts/Token.sol /// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md pragma solidity ^0.5.2; /// @title Abstract token contract - Functions to be implemented by token contracts contract Token { /* * Events */ event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); /* * Public functions */ function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); function balanceOf(address owner) public view returns (uint); function allowance(address owner, address spender) public view returns (uint); function totalSupply() public view returns (uint); } // File: @gnosis.pm/util-contracts/contracts/Math.sol /// @title Math library - Allows calculation of logarithmic and exponential functions /// @author Alan Lu - <alan.lu@gnosis.pm> /// @author Stefan George - <stefan@gnosis.pm> library GnosisMath { /* * Constants */ // This is equal to 1 in our calculations uint public constant ONE = 0x10000000000000000; uint public constant LN2 = 0xb17217f7d1cf79ac; uint public constant LOG2_E = 0x171547652b82fe177; /* * Public functions */ /// @dev Returns natural exponential function value of given x /// @param x x /// @return e**x function exp(int x) public pure returns (uint) { // revert if x is > MAX_POWER, where // MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE)) require(x <= 2454971259878909886679); // return 0 if exp(x) is tiny, using // MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE)) if (x < -818323753292969962227) return 0; // Transform so that e^x -> 2^x x = x * int(ONE) / int(LN2); // 2^x = 2^whole(x) * 2^frac(x) // ^^^^^^^^^^ is a bit shift // so Taylor expand on z = frac(x) int shift; uint z; if (x >= 0) { shift = x / int(ONE); z = uint(x % int(ONE)); } else { shift = x / int(ONE) - 1; z = ONE - uint(-x % int(ONE)); } // 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ... // // Can generate the z coefficients using mpmath and the following lines // >>> from mpmath import mp // >>> mp.dps = 100 // >>> ONE = 0x10000000000000000 // >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7))) // 0xb17217f7d1cf79ab // 0x3d7f7bff058b1d50 // 0xe35846b82505fc5 // 0x276556df749cee5 // 0x5761ff9e299cc4 // 0xa184897c363c3 uint zpow = z; uint result = ONE; result += 0xb17217f7d1cf79ab * zpow / ONE; zpow = zpow * z / ONE; result += 0x3d7f7bff058b1d50 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe35846b82505fc5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x276556df749cee5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x5761ff9e299cc4 * zpow / ONE; zpow = zpow * z / ONE; result += 0xa184897c363c3 * zpow / ONE; zpow = zpow * z / ONE; result += 0xffe5fe2c4586 * zpow / ONE; zpow = zpow * z / ONE; result += 0x162c0223a5c8 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1b5253d395e * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e4cf5158b * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e8cac735 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1c3bd650 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1816193 * zpow / ONE; zpow = zpow * z / ONE; result += 0x131496 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe1b7 * zpow / ONE; zpow = zpow * z / ONE; result += 0x9c7 * zpow / ONE; if (shift >= 0) { if (result >> (256 - shift) > 0) return (2 ** 256 - 1); return result << shift; } else return result >> (-shift); } /// @dev Returns natural logarithm value of given x /// @param x x /// @return ln(x) function ln(uint x) public pure returns (int) { require(x > 0); // binary search for floor(log2(x)) int ilog2 = floorLog2(x); int z; if (ilog2 < 0) z = int(x << uint(-ilog2)); else z = int(x >> uint(ilog2)); // z = x * 2^-1log1x1 // so 1 <= z < 2 // and ln z = ln x - 1log1x1/log1e // so just compute ln z using artanh series // and calculate ln x from that int term = (z - int(ONE)) * int(ONE) / (z + int(ONE)); int halflnz = term; int termpow = term * term / int(ONE) * term / int(ONE); halflnz += termpow / 3; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 5; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 7; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 9; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 11; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 13; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 15; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 17; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 19; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 21; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 23; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 25; return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz; } /// @dev Returns base 2 logarithm value of given x /// @param x x /// @return logarithmic value function floorLog2(uint x) public pure returns (int lo) { lo = -64; int hi = 193; // I use a shift here instead of / 2 because it floors instead of rounding towards 0 int mid = (hi + lo) >> 1; while ((lo + 1) < hi) { if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) hi = mid; else lo = mid; mid = (hi + lo) >> 1; } } /// @dev Returns maximum of an array /// @param nums Numbers to look through /// @return Maximum number function max(int[] memory nums) public pure returns (int maxNum) { require(nums.length > 0); maxNum = -2 ** 255; for (uint i = 0; i < nums.length; i++) if (nums[i] > maxNum) maxNum = nums[i]; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) internal pure returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) internal pure returns (bool) { return a >= b; } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(uint a, uint b) internal pure returns (bool) { return b == 0 || a * b / b == a; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) internal pure returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) internal pure returns (uint) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(uint a, uint b) internal pure returns (uint) { require(safeToMul(a, b)); return a * b; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(int a, int b) internal pure returns (bool) { return (b >= 0 && a + b >= a) || (b < 0 && a + b < a); } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(int a, int b) internal pure returns (bool) { return (b >= 0 && a - b <= a) || (b < 0 && a - b > a); } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(int a, int b) internal pure returns (bool) { return (b == 0) || (a * b / b == a); } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(int a, int b) internal pure returns (int) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(int a, int b) internal pure returns (int) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(int a, int b) internal pure returns (int) { require(safeToMul(a, b)); return a * b; } } // File: @gnosis.pm/util-contracts/contracts/GnosisStandardToken.sol /** * Deprecated: Use Open Zeppeling one instead */ contract StandardTokenData { /* * Storage */ mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowances; uint totalTokens; } /** * Deprecated: Use Open Zeppeling one instead */ /// @title Standard token contract with overflow protection contract GnosisStandardToken is Token, StandardTokenData { using GnosisMath for *; /* * Public functions */ /// @dev Transfers sender's tokens to a given address. Returns success /// @param to Address of token receiver /// @param value Number of tokens to transfer /// @return Was transfer successful? function transfer(address to, uint value) public returns (bool) { if (!balances[msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) { return false; } balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success /// @param from Address from where tokens are withdrawn /// @param to Address to where tokens are sent /// @param value Number of tokens to transfer /// @return Was transfer successful? function transferFrom(address from, address to, uint value) public returns (bool) { if (!balances[from].safeToSub(value) || !allowances[from][msg.sender].safeToSub( value ) || !balances[to].safeToAdd(value)) { return false; } balances[from] -= value; allowances[from][msg.sender] -= value; balances[to] += value; emit Transfer(from, to, value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success /// @param spender Address of allowed account /// @param value Number of approved tokens /// @return Was approval successful? function approve(address spender, uint value) public returns (bool) { allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Returns number of allowed tokens for given address /// @param owner Address of token owner /// @param spender Address of token spender /// @return Remaining allowance for spender function allowance(address owner, address spender) public view returns (uint) { return allowances[owner][spender]; } /// @dev Returns number of tokens owned by given address /// @param owner Address of token owner /// @return Balance of owner function balanceOf(address owner) public view returns (uint) { return balances[owner]; } /// @dev Returns total supply of tokens /// @return Total supply function totalSupply() public view returns (uint) { return totalTokens; } } // File: @gnosis.pm/dx-contracts/contracts/TokenFRT.sol /// @title Standard token contract with overflow protection contract TokenFRT is Proxied, GnosisStandardToken { address public owner; string public constant symbol = "MGN"; string public constant name = "Magnolia Token"; uint8 public constant decimals = 18; struct UnlockedToken { uint amountUnlocked; uint withdrawalTime; } /* * Storage */ address public minter; // user => UnlockedToken mapping(address => UnlockedToken) public unlockedTokens; // user => amount mapping(address => uint) public lockedTokenBalances; /* * Public functions */ // @dev allows to set the minter of Magnolia tokens once. // @param _minter the minter of the Magnolia tokens, should be the DX-proxy function updateMinter(address _minter) public { require(msg.sender == owner, "Only the minter can set a new one"); require(_minter != address(0), "The new minter must be a valid address"); minter = _minter; } // @dev the intention is to set the owner as the DX-proxy, once it is deployed // Then only an update of the DX-proxy contract after a 30 days delay could change the minter again. function updateOwner(address _owner) public { require(msg.sender == owner, "Only the owner can update the owner"); require(_owner != address(0), "The new owner must be a valid address"); owner = _owner; } function mintTokens(address user, uint amount) public { require(msg.sender == minter, "Only the minter can mint tokens"); lockedTokenBalances[user] = add(lockedTokenBalances[user], amount); totalTokens = add(totalTokens, amount); } /// @dev Lock Token function lockTokens(uint amount) public returns (uint totalAmountLocked) { // Adjust amount by balance uint actualAmount = min(amount, balances[msg.sender]); // Update state variables balances[msg.sender] = sub(balances[msg.sender], actualAmount); lockedTokenBalances[msg.sender] = add(lockedTokenBalances[msg.sender], actualAmount); // Get return variable totalAmountLocked = lockedTokenBalances[msg.sender]; } function unlockTokens() public returns (uint totalAmountUnlocked, uint withdrawalTime) { // Adjust amount by locked balances uint amount = lockedTokenBalances[msg.sender]; if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS // Update state variables lockedTokenBalances[msg.sender] = sub(lockedTokenBalances[msg.sender], amount); unlockedTokens[msg.sender].amountUnlocked = add(unlockedTokens[msg.sender].amountUnlocked, amount); unlockedTokens[msg.sender].withdrawalTime = now + 24 hours; } // Get return variables totalAmountUnlocked = unlockedTokens[msg.sender].amountUnlocked; withdrawalTime = unlockedTokens[msg.sender].withdrawalTime; } function withdrawUnlockedTokens() public { require(unlockedTokens[msg.sender].withdrawalTime < now, "The tokens cannot be withdrawn yet"); balances[msg.sender] = add(balances[msg.sender], unlockedTokens[msg.sender].amountUnlocked); unlockedTokens[msg.sender].amountUnlocked = 0; } function min(uint a, uint b) public pure returns (uint) { if (a < b) { return a; } else { return b; } } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) public pure returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) public pure returns (bool) { return a >= b; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) public pure returns (uint) { require(safeToAdd(a, b), "It must be a safe adition"); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) public pure returns (uint) { require(safeToSub(a, b), "It must be a safe substraction"); return a - b; } } // File: @gnosis.pm/owl-token/contracts/TokenOWL.sol contract TokenOWL is Proxied, GnosisStandardToken { using GnosisMath for *; string public constant name = "OWL Token"; string public constant symbol = "OWL"; uint8 public constant decimals = 18; struct masterCopyCountdownType { address masterCopy; uint timeWhenAvailable; } masterCopyCountdownType masterCopyCountdown; address public creator; address public minter; event Minted(address indexed to, uint256 amount); event Burnt(address indexed from, address indexed user, uint256 amount); modifier onlyCreator() { // R1 require(msg.sender == creator, "Only the creator can perform the transaction"); _; } /// @dev trickers the update process via the proxyMaster for a new address _masterCopy /// updating is only possible after 30 days function startMasterCopyCountdown(address _masterCopy) public onlyCreator { require(address(_masterCopy) != address(0), "The master copy must be a valid address"); // Update masterCopyCountdown masterCopyCountdown.masterCopy = _masterCopy; masterCopyCountdown.timeWhenAvailable = now + 30 days; } /// @dev executes the update process via the proxyMaster for a new address _masterCopy function updateMasterCopy() public onlyCreator { require(address(masterCopyCountdown.masterCopy) != address(0), "The master copy must be a valid address"); require( block.timestamp >= masterCopyCountdown.timeWhenAvailable, "It's not possible to update the master copy during the waiting period" ); // Update masterCopy masterCopy = masterCopyCountdown.masterCopy; } function getMasterCopy() public view returns (address) { return masterCopy; } /// @dev Set minter. Only the creator of this contract can call this. /// @param newMinter The new address authorized to mint this token function setMinter(address newMinter) public onlyCreator { minter = newMinter; } /// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this. /// @param newOwner The new address, which should become the owner function setNewOwner(address newOwner) public onlyCreator { creator = newOwner; } /// @dev Mints OWL. /// @param to Address to which the minted token will be given /// @param amount Amount of OWL to be minted function mintOWL(address to, uint amount) public { require(minter != address(0), "The minter must be initialized"); require(msg.sender == minter, "Only the minter can mint OWL"); balances[to] = balances[to].add(amount); totalTokens = totalTokens.add(amount); emit Minted(to, amount); } /// @dev Burns OWL. /// @param user Address of OWL owner /// @param amount Amount of OWL to be burnt function burnOWL(address user, uint amount) public { allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount); balances[user] = balances[user].sub(amount); totalTokens = totalTokens.sub(amount); emit Burnt(msg.sender, user, amount); } } // File: @gnosis.pm/dx-contracts/contracts/base/SafeTransfer.sol interface BadToken { function transfer(address to, uint value) external; function transferFrom(address from, address to, uint value) external; } contract SafeTransfer { function safeTransfer(address token, address to, uint value, bool from) internal returns (bool result) { if (from) { BadToken(token).transferFrom(msg.sender, address(this), value); } else { BadToken(token).transfer(to, value); } // solium-disable-next-line security/no-inline-assembly assembly { switch returndatasize case 0 { // This is our BadToken result := not(0) // result is true } case 32 { // This is our GoodToken returndatacopy(0, 0, 32) result := mload(0) // result == returndata of external call } default { // This is not an ERC20 token result := 0 } } return result; } } // File: @gnosis.pm/dx-contracts/contracts/base/AuctioneerManaged.sol contract AuctioneerManaged { // auctioneer has the power to manage some variables address public auctioneer; function updateAuctioneer(address _auctioneer) public onlyAuctioneer { require(_auctioneer != address(0), "The auctioneer must be a valid address"); auctioneer = _auctioneer; } // > Modifiers modifier onlyAuctioneer() { // Only allows auctioneer to proceed // R1 // require(msg.sender == auctioneer, "Only auctioneer can perform this operation"); require(msg.sender == auctioneer, "Only the auctioneer can nominate a new one"); _; } } // File: @gnosis.pm/dx-contracts/contracts/base/TokenWhitelist.sol contract TokenWhitelist is AuctioneerManaged { // Mapping that stores the tokens, which are approved // Only tokens approved by auctioneer generate frtToken tokens // addressToken => boolApproved mapping(address => bool) public approvedTokens; event Approval(address indexed token, bool approved); /// @dev for quick overview of approved Tokens /// @param addressesToCheck are the ERC-20 token addresses to be checked whether they are approved function getApprovedAddressesOfList(address[] calldata addressesToCheck) external view returns (bool[] memory) { uint length = addressesToCheck.length; bool[] memory isApproved = new bool[](length); for (uint i = 0; i < length; i++) { isApproved[i] = approvedTokens[addressesToCheck[i]]; } return isApproved; } function updateApprovalOfToken(address[] memory token, bool approved) public onlyAuctioneer { for (uint i = 0; i < token.length; i++) { approvedTokens[token[i]] = approved; emit Approval(token[i], approved); } } } // File: @gnosis.pm/dx-contracts/contracts/base/DxMath.sol contract DxMath { // > Math fns function min(uint a, uint b) public pure returns (uint) { if (a < b) { return a; } else { return b; } } function atleastZero(int a) public pure returns (uint) { if (a < 0) { return 0; } else { return uint(a); } } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) public pure returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) public pure returns (bool) { return a >= b; } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(uint a, uint b) public pure returns (bool) { return b == 0 || a * b / b == a; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) public pure returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) public pure returns (uint) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(uint a, uint b) public pure returns (uint) { require(safeToMul(a, b)); return a * b; } } // File: @gnosis.pm/dx-contracts/contracts/Oracle/DSMath.sol contract DSMath { /* standard uint256 functions */ function add(uint256 x, uint256 y) internal pure returns (uint256 z) { assert((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { assert((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { assert((z = x * y) >= x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } /* uint128 functions (h is for half) */ function hadd(uint128 x, uint128 y) internal pure returns (uint128 z) { assert((z = x + y) >= x); } function hsub(uint128 x, uint128 y) internal pure returns (uint128 z) { assert((z = x - y) <= x); } function hmul(uint128 x, uint128 y) internal pure returns (uint128 z) { assert((z = x * y) >= x); } function hdiv(uint128 x, uint128 y) internal pure returns (uint128 z) { z = x / y; } function hmin(uint128 x, uint128 y) internal pure returns (uint128 z) { return x <= y ? x : y; } function hmax(uint128 x, uint128 y) internal pure returns (uint128 z) { return x >= y ? x : y; } /* int256 functions */ function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } /* WAD math */ uint128 constant WAD = 10 ** 18; function wadd(uint128 x, uint128 y) internal pure returns (uint128) { return hadd(x, y); } function wsub(uint128 x, uint128 y) internal pure returns (uint128) { return hsub(x, y); } function wmul(uint128 x, uint128 y) internal pure returns (uint128 z) { z = cast((uint256(x) * y + WAD / 2) / WAD); } function wdiv(uint128 x, uint128 y) internal pure returns (uint128 z) { z = cast((uint256(x) * WAD + y / 2) / y); } function wmin(uint128 x, uint128 y) internal pure returns (uint128) { return hmin(x, y); } function wmax(uint128 x, uint128 y) internal pure returns (uint128) { return hmax(x, y); } /* RAY math */ uint128 constant RAY = 10 ** 27; function radd(uint128 x, uint128 y) internal pure returns (uint128) { return hadd(x, y); } function rsub(uint128 x, uint128 y) internal pure returns (uint128) { return hsub(x, y); } function rmul(uint128 x, uint128 y) internal pure returns (uint128 z) { z = cast((uint256(x) * y + RAY / 2) / RAY); } function rdiv(uint128 x, uint128 y) internal pure returns (uint128 z) { z = cast((uint256(x) * RAY + y / 2) / y); } function rpow(uint128 x, uint64 n) internal pure returns (uint128 z) { // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } function rmin(uint128 x, uint128 y) internal pure returns (uint128) { return hmin(x, y); } function rmax(uint128 x, uint128 y) internal pure returns (uint128) { return hmax(x, y); } function cast(uint256 x) internal pure returns (uint128 z) { assert((z = uint128(x)) == x); } } // File: @gnosis.pm/dx-contracts/contracts/Oracle/DSAuth.sol contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "It must be an authorized call"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (block.coinbase == owner) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } // File: @gnosis.pm/dx-contracts/contracts/Oracle/DSNote.sol contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 bar, uint wad, bytes fax ); modifier note { bytes32 foo; bytes32 bar; // solium-disable-next-line security/no-inline-assembly assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote( msg.sig, msg.sender, foo, bar, msg.value, msg.data ); _; } } // File: @gnosis.pm/dx-contracts/contracts/Oracle/DSThing.sol contract DSThing is DSAuth, DSNote, DSMath {} // File: @gnosis.pm/dx-contracts/contracts/Oracle/PriceFeed.sol /// price-feed.sol // Copyright (C) 2017 DappHub, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied). contract PriceFeed is DSThing { uint128 val; uint32 public zzz; function peek() public view returns (bytes32, bool) { return (bytes32(uint256(val)), block.timestamp < zzz); } function read() public view returns (bytes32) { assert(block.timestamp < zzz); return bytes32(uint256(val)); } function post(uint128 val_, uint32 zzz_, address med_) public payable note auth { val = val_; zzz = zzz_; (bool success, ) = med_.call(abi.encodeWithSignature("poke()")); require(success, "The poke must succeed"); } function void() public payable note auth { zzz = 0; } } // File: @gnosis.pm/dx-contracts/contracts/Oracle/DSValue.sol contract DSValue is DSThing { bool has; bytes32 val; function peek() public view returns (bytes32, bool) { return (val, has); } function read() public view returns (bytes32) { (bytes32 wut, bool _has) = peek(); assert(_has); return wut; } function poke(bytes32 wut) public payable note auth { val = wut; has = true; } function void() public payable note auth { // unset the value has = false; } } // File: @gnosis.pm/dx-contracts/contracts/Oracle/Medianizer.sol contract Medianizer is DSValue { mapping(bytes12 => address) public values; mapping(address => bytes12) public indexes; bytes12 public next = bytes12(uint96(1)); uint96 public minimun = 0x1; function set(address wat) public auth { bytes12 nextId = bytes12(uint96(next) + 1); assert(nextId != 0x0); set(next, wat); next = nextId; } function set(bytes12 pos, address wat) public payable note auth { require(pos != 0x0, "pos cannot be 0x0"); require(wat == address(0) || indexes[wat] == 0, "wat is not defined or it has an index"); indexes[values[pos]] = bytes12(0); // Making sure to remove a possible existing address in that position if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS indexes[wat] = pos; } values[pos] = wat; } function setMin(uint96 min_) public payable note auth { require(min_ != 0x0, "min cannot be 0x0"); minimun = min_; } function setNext(bytes12 next_) public payable note auth { require(next_ != 0x0, "next cannot be 0x0"); next = next_; } function unset(bytes12 pos) public { set(pos, address(0)); } function unset(address wat) public { set(indexes[wat], address(0)); } function poke() public { poke(0); } function poke(bytes32) public payable note { (val, has) = compute(); } function compute() public view returns (bytes32, bool) { bytes32[] memory wuts = new bytes32[](uint96(next) - 1); uint96 ctr = 0; for (uint96 i = 1; i < uint96(next); i++) { if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS (bytes32 wut, bool wuz) = DSValue(values[bytes12(i)]).peek(); if (wuz) { if (ctr == 0 || wut >= wuts[ctr - 1]) { wuts[ctr] = wut; } else { uint96 j = 0; while (wut >= wuts[j]) { j++; } for (uint96 k = ctr; k > j; k--) { wuts[k] = wuts[k - 1]; } wuts[j] = wut; } ctr++; } } } if (ctr < minimun) return (val, false); bytes32 value; if (ctr % 2 == 0) { uint128 val1 = uint128(uint(wuts[(ctr / 2) - 1])); uint128 val2 = uint128(uint(wuts[ctr / 2])); value = bytes32(uint256(wdiv(hadd(val1, val2), 2 ether))); } else { value = wuts[(ctr - 1) / 2]; } return (value, true); } } // File: @gnosis.pm/dx-contracts/contracts/Oracle/PriceOracleInterface.sol /* This contract is the interface between the MakerDAO priceFeed and our DX platform. */ contract PriceOracleInterface { address public priceFeedSource; address public owner; bool public emergencyMode; // Modifiers modifier onlyOwner() { require(msg.sender == owner, "Only the owner can do the operation"); _; } /// @dev constructor of the contract /// @param _priceFeedSource address of price Feed Source -> should be maker feeds Medianizer contract constructor(address _owner, address _priceFeedSource) public { owner = _owner; priceFeedSource = _priceFeedSource; } /// @dev gives the owner the possibility to put the Interface into an emergencyMode, which will /// output always a price of 600 USD. This gives everyone time to set up a new pricefeed. function raiseEmergency(bool _emergencyMode) public onlyOwner { emergencyMode = _emergencyMode; } /// @dev updates the priceFeedSource /// @param _owner address of owner function updateCurator(address _owner) public onlyOwner { owner = _owner; } /// @dev returns the USDETH price function getUsdEthPricePeek() public view returns (bytes32 price, bool valid) { return Medianizer(priceFeedSource).peek(); } /// @dev returns the USDETH price, ie gets the USD price from Maker feed with 18 digits, but last 18 digits are cut off function getUSDETHPrice() public view returns (uint256) { // if the contract is in the emergencyMode, because there is an issue with the oracle, we will simply return a price of 600 USD if (emergencyMode) { return 600; } (bytes32 price, ) = Medianizer(priceFeedSource).peek(); // ensuring that there is no underflow or overflow possible, // even if the price is compromised uint priceUint = uint256(price)/(1 ether); if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS return 1; } if (block.gaslimit > 1000000) { //injected CONTRACT AFFECTED BY MINERS return 1000000; } return priceUint; } } // File: @gnosis.pm/dx-contracts/contracts/base/EthOracle.sol contract EthOracle is AuctioneerManaged, DxMath { uint constant WAITING_PERIOD_CHANGE_ORACLE = 30 days; // Price Oracle interface PriceOracleInterface public ethUSDOracle; // Price Oracle interface proposals during update process PriceOracleInterface public newProposalEthUSDOracle; uint public oracleInterfaceCountdown; event NewOracleProposal(PriceOracleInterface priceOracleInterface); function initiateEthUsdOracleUpdate(PriceOracleInterface _ethUSDOracle) public onlyAuctioneer { require(address(_ethUSDOracle) != address(0), "The oracle address must be valid"); newProposalEthUSDOracle = _ethUSDOracle; oracleInterfaceCountdown = add(block.timestamp, WAITING_PERIOD_CHANGE_ORACLE); emit NewOracleProposal(_ethUSDOracle); } function updateEthUSDOracle() public { require(address(newProposalEthUSDOracle) != address(0), "The new proposal must be a valid addres"); require( oracleInterfaceCountdown < block.timestamp, "It's not possible to update the oracle during the waiting period" ); ethUSDOracle = newProposalEthUSDOracle; newProposalEthUSDOracle = PriceOracleInterface(0); } } // File: @gnosis.pm/dx-contracts/contracts/base/DxUpgrade.sol contract DxUpgrade is Proxied, AuctioneerManaged, DxMath { uint constant WAITING_PERIOD_CHANGE_MASTERCOPY = 30 days; address public newMasterCopy; // Time when new masterCopy is updatabale uint public masterCopyCountdown; event NewMasterCopyProposal(address newMasterCopy); function startMasterCopyCountdown(address _masterCopy) public onlyAuctioneer { require(_masterCopy != address(0), "The new master copy must be a valid address"); // Update masterCopyCountdown newMasterCopy = _masterCopy; masterCopyCountdown = add(block.timestamp, WAITING_PERIOD_CHANGE_MASTERCOPY); emit NewMasterCopyProposal(_masterCopy); } function updateMasterCopy() public { require(newMasterCopy != address(0), "The new master copy must be a valid address"); require(block.timestamp >= masterCopyCountdown, "The master contract cannot be updated in a waiting period"); // Update masterCopy masterCopy = newMasterCopy; newMasterCopy = address(0); } } // File: @gnosis.pm/dx-contracts/contracts/DutchExchange.sol /// @title Dutch Exchange - exchange token pairs with the clever mechanism of the dutch auction /// @author Alex Herrmann - <alex@gnosis.pm> /// @author Dominik Teiml - <dominik@gnosis.pm> contract DutchExchange is DxUpgrade, TokenWhitelist, EthOracle, SafeTransfer { // The price is a rational number, so we need a concept of a fraction struct Fraction { uint num; uint den; } uint constant WAITING_PERIOD_NEW_TOKEN_PAIR = 6 hours; uint constant WAITING_PERIOD_NEW_AUCTION = 10 minutes; uint constant AUCTION_START_WAITING_FOR_FUNDING = 1; // > Storage // Ether ERC-20 token address public ethToken; // Minimum required sell funding for adding a new token pair, in USD uint public thresholdNewTokenPair; // Minimum required sell funding for starting antoher auction, in USD uint public thresholdNewAuction; // Fee reduction token (magnolia, ERC-20 token) TokenFRT public frtToken; // Token for paying fees TokenOWL public owlToken; // For the following three mappings, there is one mapping for each token pair // The order which the tokens should be called is smaller, larger // These variables should never be called directly! They have getters below // Token => Token => index mapping(address => mapping(address => uint)) public latestAuctionIndices; // Token => Token => time mapping (address => mapping (address => uint)) public auctionStarts; // Token => Token => auctionIndex => time mapping (address => mapping (address => mapping (uint => uint))) public clearingTimes; // Token => Token => auctionIndex => price mapping(address => mapping(address => mapping(uint => Fraction))) public closingPrices; // Token => Token => amount mapping(address => mapping(address => uint)) public sellVolumesCurrent; // Token => Token => amount mapping(address => mapping(address => uint)) public sellVolumesNext; // Token => Token => amount mapping(address => mapping(address => uint)) public buyVolumes; // Token => user => amount // balances stores a user's balance in the DutchX mapping(address => mapping(address => uint)) public balances; // Token => Token => auctionIndex => amount mapping(address => mapping(address => mapping(uint => uint))) public extraTokens; // Token => Token => auctionIndex => user => amount mapping(address => mapping(address => mapping(uint => mapping(address => uint)))) public sellerBalances; mapping(address => mapping(address => mapping(uint => mapping(address => uint)))) public buyerBalances; mapping(address => mapping(address => mapping(uint => mapping(address => uint)))) public claimedAmounts; function depositAndSell(address sellToken, address buyToken, uint amount) external returns (uint newBal, uint auctionIndex, uint newSellerBal) { newBal = deposit(sellToken, amount); (auctionIndex, newSellerBal) = postSellOrder(sellToken, buyToken, 0, amount); } function claimAndWithdraw(address sellToken, address buyToken, address user, uint auctionIndex, uint amount) external returns (uint returned, uint frtsIssued, uint newBal) { (returned, frtsIssued) = claimSellerFunds(sellToken, buyToken, user, auctionIndex); newBal = withdraw(buyToken, amount); } /// @dev for multiple claims /// @param auctionSellTokens are the sellTokens defining an auctionPair /// @param auctionBuyTokens are the buyTokens defining an auctionPair /// @param auctionIndices are the auction indices on which an token should be claimedAmounts /// @param user is the user who wants to his tokens function claimTokensFromSeveralAuctionsAsSeller( address[] calldata auctionSellTokens, address[] calldata auctionBuyTokens, uint[] calldata auctionIndices, address user ) external returns (uint[] memory, uint[] memory) { uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices); uint[] memory claimAmounts = new uint[](length); uint[] memory frtsIssuedList = new uint[](length); for (uint i = 0; i < length; i++) { (claimAmounts[i], frtsIssuedList[i]) = claimSellerFunds( auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i] ); } return (claimAmounts, frtsIssuedList); } /// @dev for multiple claims /// @param auctionSellTokens are the sellTokens defining an auctionPair /// @param auctionBuyTokens are the buyTokens defining an auctionPair /// @param auctionIndices are the auction indices on which an token should be claimedAmounts /// @param user is the user who wants to his tokens function claimTokensFromSeveralAuctionsAsBuyer( address[] calldata auctionSellTokens, address[] calldata auctionBuyTokens, uint[] calldata auctionIndices, address user ) external returns (uint[] memory, uint[] memory) { uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices); uint[] memory claimAmounts = new uint[](length); uint[] memory frtsIssuedList = new uint[](length); for (uint i = 0; i < length; i++) { (claimAmounts[i], frtsIssuedList[i]) = claimBuyerFunds( auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i] ); } return (claimAmounts, frtsIssuedList); } /// @dev for multiple withdraws /// @param auctionSellTokens are the sellTokens defining an auctionPair /// @param auctionBuyTokens are the buyTokens defining an auctionPair /// @param auctionIndices are the auction indices on which an token should be claimedAmounts function claimAndWithdrawTokensFromSeveralAuctionsAsSeller( address[] calldata auctionSellTokens, address[] calldata auctionBuyTokens, uint[] calldata auctionIndices ) external returns (uint[] memory, uint frtsIssued) { uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices); uint[] memory claimAmounts = new uint[](length); uint claimFrts = 0; for (uint i = 0; i < length; i++) { (claimAmounts[i], claimFrts) = claimSellerFunds( auctionSellTokens[i], auctionBuyTokens[i], msg.sender, auctionIndices[i] ); frtsIssued += claimFrts; withdraw(auctionBuyTokens[i], claimAmounts[i]); } return (claimAmounts, frtsIssued); } /// @dev for multiple withdraws /// @param auctionSellTokens are the sellTokens defining an auctionPair /// @param auctionBuyTokens are the buyTokens defining an auctionPair /// @param auctionIndices are the auction indices on which an token should be claimedAmounts function claimAndWithdrawTokensFromSeveralAuctionsAsBuyer( address[] calldata auctionSellTokens, address[] calldata auctionBuyTokens, uint[] calldata auctionIndices ) external returns (uint[] memory, uint frtsIssued) { uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices); uint[] memory claimAmounts = new uint[](length); uint claimFrts = 0; for (uint i = 0; i < length; i++) { (claimAmounts[i], claimFrts) = claimBuyerFunds( auctionSellTokens[i], auctionBuyTokens[i], msg.sender, auctionIndices[i] ); frtsIssued += claimFrts; withdraw(auctionSellTokens[i], claimAmounts[i]); } return (claimAmounts, frtsIssued); } function getMasterCopy() external view returns (address) { return masterCopy; } /// @dev Constructor-Function creates exchange /// @param _frtToken - address of frtToken ERC-20 token /// @param _owlToken - address of owlToken ERC-20 token /// @param _auctioneer - auctioneer for managing interfaces /// @param _ethToken - address of ETH ERC-20 token /// @param _ethUSDOracle - address of the oracle contract for fetching feeds /// @param _thresholdNewTokenPair - Minimum required sell funding for adding a new token pair, in USD function setupDutchExchange( TokenFRT _frtToken, TokenOWL _owlToken, address _auctioneer, address _ethToken, PriceOracleInterface _ethUSDOracle, uint _thresholdNewTokenPair, uint _thresholdNewAuction ) public { // Make sure contract hasn't been initialised require(ethToken == address(0), "The contract must be uninitialized"); // Validates inputs require(address(_owlToken) != address(0), "The OWL address must be valid"); require(address(_frtToken) != address(0), "The FRT address must be valid"); require(_auctioneer != address(0), "The auctioneer address must be valid"); require(_ethToken != address(0), "The WETH address must be valid"); require(address(_ethUSDOracle) != address(0), "The oracle address must be valid"); frtToken = _frtToken; owlToken = _owlToken; auctioneer = _auctioneer; ethToken = _ethToken; ethUSDOracle = _ethUSDOracle; thresholdNewTokenPair = _thresholdNewTokenPair; thresholdNewAuction = _thresholdNewAuction; } function updateThresholdNewTokenPair(uint _thresholdNewTokenPair) public onlyAuctioneer { thresholdNewTokenPair = _thresholdNewTokenPair; } function updateThresholdNewAuction(uint _thresholdNewAuction) public onlyAuctioneer { thresholdNewAuction = _thresholdNewAuction; } /// @param initialClosingPriceNum initial price will be 2 * initialClosingPrice. This is its numerator /// @param initialClosingPriceDen initial price will be 2 * initialClosingPrice. This is its denominator function addTokenPair( address token1, address token2, uint token1Funding, uint token2Funding, uint initialClosingPriceNum, uint initialClosingPriceDen ) public { // R1 require(token1 != token2, "You cannot add a token pair using the same token"); // R2 require(initialClosingPriceNum != 0, "You must set the numerator for the initial price"); // R3 require(initialClosingPriceDen != 0, "You must set the denominator for the initial price"); // R4 require(getAuctionIndex(token1, token2) == 0, "The token pair was already added"); // R5: to prevent overflow require(initialClosingPriceNum < 10 ** 18, "You must set a smaller numerator for the initial price"); // R6 require(initialClosingPriceDen < 10 ** 18, "You must set a smaller denominator for the initial price"); setAuctionIndex(token1, token2); token1Funding = min(token1Funding, balances[token1][msg.sender]); token2Funding = min(token2Funding, balances[token2][msg.sender]); // R7 require(token1Funding < 10 ** 30, "You should use a smaller funding for token 1"); // R8 require(token2Funding < 10 ** 30, "You should use a smaller funding for token 2"); uint fundedValueUSD; uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); // Compute fundedValueUSD address ethTokenMem = ethToken; if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS // C1 // MUL: 10^30 * 10^6 = 10^36 fundedValueUSD = mul(token1Funding, ethUSDPrice); } else if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS // C2 // MUL: 10^30 * 10^6 = 10^36 fundedValueUSD = mul(token2Funding, ethUSDPrice); } else { // C3: Neither token is ethToken fundedValueUSD = calculateFundedValueTokenToken( token1, token2, token1Funding, token2Funding, ethTokenMem, ethUSDPrice ); } // R5 require(fundedValueUSD >= thresholdNewTokenPair, "You should surplus the threshold for adding token pairs"); // Save prices of opposite auctions closingPrices[token1][token2][0] = Fraction(initialClosingPriceNum, initialClosingPriceDen); closingPrices[token2][token1][0] = Fraction(initialClosingPriceDen, initialClosingPriceNum); // Split into two fns because of 16 local-var cap addTokenPairSecondPart(token1, token2, token1Funding, token2Funding); } function deposit(address tokenAddress, uint amount) public returns (uint) { // R1 require(safeTransfer(tokenAddress, msg.sender, amount, true), "The deposit transaction must succeed"); uint newBal = add(balances[tokenAddress][msg.sender], amount); balances[tokenAddress][msg.sender] = newBal; emit NewDeposit(tokenAddress, amount); return newBal; } function withdraw(address tokenAddress, uint amount) public returns (uint) { uint usersBalance = balances[tokenAddress][msg.sender]; amount = min(amount, usersBalance); // R1 require(amount > 0, "The amount must be greater than 0"); uint newBal = sub(usersBalance, amount); balances[tokenAddress][msg.sender] = newBal; // R2 require(safeTransfer(tokenAddress, msg.sender, amount, false), "The withdraw transfer must succeed"); emit NewWithdrawal(tokenAddress, amount); return newBal; } function postSellOrder(address sellToken, address buyToken, uint auctionIndex, uint amount) public returns (uint, uint) { // Note: if a user specifies auctionIndex of 0, it // means he is agnostic which auction his sell order goes into amount = min(amount, balances[sellToken][msg.sender]); // R1 // require(amount >= 0, "Sell amount should be greater than 0"); // R2 uint latestAuctionIndex = getAuctionIndex(sellToken, buyToken); require(latestAuctionIndex > 0); // R3 uint auctionStart = getAuctionStart(sellToken, buyToken); if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) { // C1: We are in the 10 minute buffer period // OR waiting for an auction to receive sufficient sellVolume // Auction has already cleared, and index has been incremented // sell order must use that auction index // R1.1 if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS auctionIndex = latestAuctionIndex; } else { require(auctionIndex == latestAuctionIndex, "Auction index should be equal to latest auction index"); } // R1.2 require(add(sellVolumesCurrent[sellToken][buyToken], amount) < 10 ** 30); } else { // C2 // R2.1: Sell orders must go to next auction if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS auctionIndex = latestAuctionIndex + 1; } else { require(auctionIndex == latestAuctionIndex + 1); } // R2.2 require(add(sellVolumesNext[sellToken][buyToken], amount) < 10 ** 30); } // Fee mechanism, fees are added to extraTokens uint amountAfterFee = settleFee(sellToken, buyToken, auctionIndex, amount); // Update variables balances[sellToken][msg.sender] = sub(balances[sellToken][msg.sender], amount); uint newSellerBal = add(sellerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee); sellerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newSellerBal; if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) { // C1 uint sellVolumeCurrent = sellVolumesCurrent[sellToken][buyToken]; sellVolumesCurrent[sellToken][buyToken] = add(sellVolumeCurrent, amountAfterFee); } else { // C2 uint sellVolumeNext = sellVolumesNext[sellToken][buyToken]; sellVolumesNext[sellToken][buyToken] = add(sellVolumeNext, amountAfterFee); // close previous auction if theoretically closed closeTheoreticalClosedAuction(sellToken, buyToken, latestAuctionIndex); } if (block.gaslimit == AUCTION_START_WAITING_FOR_FUNDING) { //injected CONTRACT AFFECTED BY MINERS scheduleNextAuction(sellToken, buyToken); } emit NewSellOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee); return (auctionIndex, newSellerBal); } function postBuyOrder(address sellToken, address buyToken, uint auctionIndex, uint amount) public returns (uint newBuyerBal) { // R1: auction must not have cleared require(closingPrices[sellToken][buyToken][auctionIndex].den == 0); uint auctionStart = getAuctionStart(sellToken, buyToken); // R2 require(auctionStart <= now); // R4 require(auctionIndex == getAuctionIndex(sellToken, buyToken)); // R5: auction must not be in waiting period require(auctionStart > AUCTION_START_WAITING_FOR_FUNDING); // R6: auction must be funded require(sellVolumesCurrent[sellToken][buyToken] > 0); uint buyVolume = buyVolumes[sellToken][buyToken]; amount = min(amount, balances[buyToken][msg.sender]); // R7 require(add(buyVolume, amount) < 10 ** 30); // Overbuy is when a part of a buy order clears an auction // In that case we only process the part before the overbuy // To calculate overbuy, we first get current price uint sellVolume = sellVolumesCurrent[sellToken][buyToken]; uint num; uint den; (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); // 10^30 * 10^37 = 10^67 uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume)); uint amountAfterFee; if (block.number < outstandingVolume) { //injected CONTRACT AFFECTED BY MINERS if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS amountAfterFee = settleFee(buyToken, sellToken, auctionIndex, amount); } } else { amount = outstandingVolume; amountAfterFee = outstandingVolume; } // Here we could also use outstandingVolume or amountAfterFee, it doesn't matter if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS // Update variables balances[buyToken][msg.sender] = sub(balances[buyToken][msg.sender], amount); newBuyerBal = add(buyerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee); buyerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newBuyerBal; buyVolumes[sellToken][buyToken] = add(buyVolumes[sellToken][buyToken], amountAfterFee); emit NewBuyOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee); } // Checking for equality would suffice here. nevertheless: if (block.gaslimit >= outstandingVolume) { //injected CONTRACT AFFECTED BY MINERS // Clear auction clearAuction(sellToken, buyToken, auctionIndex, sellVolume); } return (newBuyerBal); } function claimSellerFunds(address sellToken, address buyToken, address user, uint auctionIndex) public returns ( // < (10^60, 10^61) uint returned, uint frtsIssued ) { closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex); uint sellerBalance = sellerBalances[sellToken][buyToken][auctionIndex][user]; // R1 require(sellerBalance > 0); // Get closing price for said auction Fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex]; uint num = closingPrice.num; uint den = closingPrice.den; // R2: require auction to have cleared require(den > 0); // Calculate return // < 10^30 * 10^30 = 10^60 returned = mul(sellerBalance, num) / den; frtsIssued = issueFrts( sellToken, buyToken, returned, auctionIndex, sellerBalance, user ); // Claim tokens sellerBalances[sellToken][buyToken][auctionIndex][user] = 0; if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS balances[buyToken][user] = add(balances[buyToken][user], returned); } emit NewSellerFundsClaim( sellToken, buyToken, user, auctionIndex, returned, frtsIssued ); } function claimBuyerFunds(address sellToken, address buyToken, address user, uint auctionIndex) public returns (uint returned, uint frtsIssued) { closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex); uint num; uint den; (returned, num, den) = getUnclaimedBuyerFunds(sellToken, buyToken, user, auctionIndex); if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS // Auction is running claimedAmounts[sellToken][buyToken][auctionIndex][user] = add( claimedAmounts[sellToken][buyToken][auctionIndex][user], returned ); } else { // Auction has closed // We DON'T want to check for returned > 0, because that would fail if a user claims // intermediate funds & auction clears in same block (he/she would not be able to claim extraTokens) // Assign extra sell tokens (this is possible only after auction has cleared, // because buyVolume could still increase before that) uint extraTokensTotal = extraTokens[sellToken][buyToken][auctionIndex]; uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user]; // closingPrices.num represents buyVolume // < 10^30 * 10^30 = 10^60 uint tokensExtra = mul( buyerBalance, extraTokensTotal ) / closingPrices[sellToken][buyToken][auctionIndex].num; returned = add(returned, tokensExtra); frtsIssued = issueFrts( buyToken, sellToken, mul(buyerBalance, den) / num, auctionIndex, buyerBalance, user ); // Auction has closed // Reset buyerBalances and claimedAmounts buyerBalances[sellToken][buyToken][auctionIndex][user] = 0; claimedAmounts[sellToken][buyToken][auctionIndex][user] = 0; } // Claim tokens if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS balances[sellToken][user] = add(balances[sellToken][user], returned); } emit NewBuyerFundsClaim( sellToken, buyToken, user, auctionIndex, returned, frtsIssued ); } /// @dev allows to close possible theoretical closed markets /// @param sellToken sellToken of an auction /// @param buyToken buyToken of an auction /// @param auctionIndex is the auctionIndex of the auction function closeTheoreticalClosedAuction(address sellToken, address buyToken, uint auctionIndex) public { if (auctionIndex == getAuctionIndex( buyToken, sellToken ) && closingPrices[sellToken][buyToken][auctionIndex].num == 0) { uint buyVolume = buyVolumes[sellToken][buyToken]; uint sellVolume = sellVolumesCurrent[sellToken][buyToken]; uint num; uint den; (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); // 10^30 * 10^37 = 10^67 if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume)); if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS postBuyOrder(sellToken, buyToken, auctionIndex, 0); } } } } /// @dev Claim buyer funds for one auction function getUnclaimedBuyerFunds(address sellToken, address buyToken, address user, uint auctionIndex) public view returns ( // < (10^67, 10^37) uint unclaimedBuyerFunds, uint num, uint den ) { // R1: checks if particular auction has ever run require(auctionIndex <= getAuctionIndex(sellToken, buyToken)); (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS // This should rarely happen - as long as there is >= 1 buy order, // auction will clear before price = 0. So this is just fail-safe unclaimedBuyerFunds = 0; } else { uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user]; // < 10^30 * 10^37 = 10^67 unclaimedBuyerFunds = atleastZero( int(mul(buyerBalance, den) / num - claimedAmounts[sellToken][buyToken][auctionIndex][user]) ); } } function getFeeRatio(address user) public view returns ( // feeRatio < 10^4 uint num, uint den ) { uint totalSupply = frtToken.totalSupply(); uint lockedFrt = frtToken.lockedTokenBalances(user); /* Fee Model: locked FRT range Fee ----------------- ------ [0, 0.01%) 0.5% [0.01%, 0.1%) 0.4% [0.1%, 1%) 0.3% [1%, 10%) 0.2% [10%, 100%) 0.1% */ if (lockedFrt * 10000 < totalSupply || totalSupply == 0) { // Maximum fee, if user has locked less than 0.01% of the total FRT // Fee: 0.5% num = 1; den = 200; } else if (block.timestamp < totalSupply) { //injected CONTRACT AFFECTED BY MINERS // If user has locked more than 0.01% and less than 0.1% of the total FRT // Fee: 0.4% num = 1; den = 250; } else if (block.timestamp < totalSupply) { //injected CONTRACT AFFECTED BY MINERS // If user has locked more than 0.1% and less than 1% of the total FRT // Fee: 0.3% num = 3; den = 1000; } else if (block.timestamp < totalSupply) { //injected CONTRACT AFFECTED BY MINERS // If user has locked more than 1% and less than 10% of the total FRT // Fee: 0.2% num = 1; den = 500; } else { // If user has locked more than 10% of the total FRT // Fee: 0.1% num = 1; den = 1000; } } //@ dev returns price in units [token2]/[token1] //@ param token1 first token for price calculation //@ param token2 second token for price calculation //@ param auctionIndex index for the auction to get the averaged price from function getPriceInPastAuction( address token1, address token2, uint auctionIndex ) public view // price < 10^31 returns (uint num, uint den) { if (block.coinbase == token2) { //injected CONTRACT AFFECTED BY MINERS // C1 num = 1; den = 1; } else { // C2 // R2.1 // require(auctionIndex >= 0); // C3 // R3.1 require(auctionIndex <= getAuctionIndex(token1, token2)); // auction still running uint i = 0; bool correctPair = false; Fraction memory closingPriceToken1; Fraction memory closingPriceToken2; while (!correctPair) { closingPriceToken2 = closingPrices[token2][token1][auctionIndex - i]; closingPriceToken1 = closingPrices[token1][token2][auctionIndex - i]; if (closingPriceToken1.num > 0 && closingPriceToken1.den > 0 || closingPriceToken2.num > 0 && closingPriceToken2.den > 0) { correctPair = true; } i++; } // At this point at least one closing price is strictly positive // If only one is positive, we want to output that if (closingPriceToken1.num == 0 || closingPriceToken1.den == 0) { num = closingPriceToken2.den; den = closingPriceToken2.num; } else if (closingPriceToken2.num == 0 || closingPriceToken2.den == 0) { num = closingPriceToken1.num; den = closingPriceToken1.den; } else { // If both prices are positive, output weighted average num = closingPriceToken2.den + closingPriceToken1.num; den = closingPriceToken2.num + closingPriceToken1.den; } } } function scheduleNextAuction( address sellToken, address buyToken ) internal { (uint sellVolume, uint sellVolumeOpp) = getSellVolumesInUSD(sellToken, buyToken); bool enoughSellVolume = sellVolume >= thresholdNewAuction; bool enoughSellVolumeOpp = sellVolumeOpp >= thresholdNewAuction; bool schedule; // Make sure both sides have liquidity in order to start the auction if (enoughSellVolume && enoughSellVolumeOpp) { schedule = true; } else if (enoughSellVolume || enoughSellVolumeOpp) { // But if the auction didn't start in 24h, then is enough to have // liquidity in one of the two sides uint latestAuctionIndex = getAuctionIndex(sellToken, buyToken); uint clearingTime = getClearingTime(sellToken, buyToken, latestAuctionIndex - 1); schedule = clearingTime <= now - 24 hours; } if (schedule) { // Schedule next auction setAuctionStart(sellToken, buyToken, WAITING_PERIOD_NEW_AUCTION); } else { resetAuctionStart(sellToken, buyToken); } } function getSellVolumesInUSD( address sellToken, address buyToken ) internal view returns (uint sellVolume, uint sellVolumeOpp) { // Check if auctions received enough sell orders uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); uint sellNum; uint sellDen; (sellNum, sellDen) = getPriceOfTokenInLastAuction(sellToken); uint buyNum; uint buyDen; (buyNum, buyDen) = getPriceOfTokenInLastAuction(buyToken); // We use current sell volume, because in clearAuction() we set // sellVolumesCurrent = sellVolumesNext before calling this function // (this is so that we don't need case work, // since it might also be called from postSellOrder()) // < 10^30 * 10^31 * 10^6 = 10^67 sellVolume = mul(mul(sellVolumesCurrent[sellToken][buyToken], sellNum), ethUSDPrice) / sellDen; sellVolumeOpp = mul(mul(sellVolumesCurrent[buyToken][sellToken], buyNum), ethUSDPrice) / buyDen; } /// @dev Gives best estimate for market price of a token in ETH of any price oracle on the Ethereum network /// @param token address of ERC-20 token /// @return Weighted average of closing prices of opposite Token-ethToken auctions, based on their sellVolume function getPriceOfTokenInLastAuction(address token) public view returns ( // price < 10^31 uint num, uint den ) { uint latestAuctionIndex = getAuctionIndex(token, ethToken); // getPriceInPastAuction < 10^30 (num, den) = getPriceInPastAuction(token, ethToken, latestAuctionIndex - 1); } function getCurrentAuctionPrice(address sellToken, address buyToken, uint auctionIndex) public view returns ( // price < 10^37 uint num, uint den ) { Fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex]; if (block.gaslimit != 0) { //injected CONTRACT AFFECTED BY MINERS // Auction has closed (num, den) = (closingPrice.num, closingPrice.den); } else if (block.number > getAuctionIndex(sellToken, buyToken)) { //injected CONTRACT AFFECTED BY MINERS (num, den) = (0, 0); } else { // Auction is running uint pastNum; uint pastDen; (pastNum, pastDen) = getPriceInPastAuction(sellToken, buyToken, auctionIndex - 1); // If we're calling the function into an unstarted auction, // it will return the starting price of that auction uint timeElapsed = atleastZero(int(now - getAuctionStart(sellToken, buyToken))); // The numbers below are chosen such that // P(0 hrs) = 2 * lastClosingPrice, P(6 hrs) = lastClosingPrice, P(>=24 hrs) = 0 // 10^5 * 10^31 = 10^36 num = atleastZero(int((24 hours - timeElapsed) * pastNum)); // 10^6 * 10^31 = 10^37 den = mul((timeElapsed + 12 hours), pastDen); if (block.gaslimit <= mul(den, buyVolumes[sellToken][buyToken])) { //injected CONTRACT AFFECTED BY MINERS num = buyVolumes[sellToken][buyToken]; den = sellVolumesCurrent[sellToken][buyToken]; } } } // > Helper fns function getTokenOrder(address token1, address token2) public pure returns (address, address) { if (token2 < token1) { (token1, token2) = (token2, token1); } return (token1, token2); } function getAuctionStart(address token1, address token2) public view returns (uint auctionStart) { (token1, token2) = getTokenOrder(token1, token2); auctionStart = auctionStarts[token1][token2]; } function getAuctionIndex(address token1, address token2) public view returns (uint auctionIndex) { (token1, token2) = getTokenOrder(token1, token2); auctionIndex = latestAuctionIndices[token1][token2]; } function calculateFundedValueTokenToken( address token1, address token2, uint token1Funding, uint token2Funding, address ethTokenMem, uint ethUSDPrice ) internal view returns (uint fundedValueUSD) { // We require there to exist ethToken-Token auctions // R3.1 require(getAuctionIndex(token1, ethTokenMem) > 0); // R3.2 require(getAuctionIndex(token2, ethTokenMem) > 0); // Price of Token 1 uint priceToken1Num; uint priceToken1Den; (priceToken1Num, priceToken1Den) = getPriceOfTokenInLastAuction(token1); // Price of Token 2 uint priceToken2Num; uint priceToken2Den; (priceToken2Num, priceToken2Den) = getPriceOfTokenInLastAuction(token2); // Compute funded value in ethToken and USD // 10^30 * 10^30 = 10^60 uint fundedValueETH = add( mul(token1Funding, priceToken1Num) / priceToken1Den, token2Funding * priceToken2Num / priceToken2Den ); fundedValueUSD = mul(fundedValueETH, ethUSDPrice); } function addTokenPairSecondPart( address token1, address token2, uint token1Funding, uint token2Funding ) internal { balances[token1][msg.sender] = sub(balances[token1][msg.sender], token1Funding); balances[token2][msg.sender] = sub(balances[token2][msg.sender], token2Funding); // Fee mechanism, fees are added to extraTokens uint token1FundingAfterFee = settleFee(token1, token2, 1, token1Funding); uint token2FundingAfterFee = settleFee(token2, token1, 1, token2Funding); // Update other variables sellVolumesCurrent[token1][token2] = token1FundingAfterFee; sellVolumesCurrent[token2][token1] = token2FundingAfterFee; sellerBalances[token1][token2][1][msg.sender] = token1FundingAfterFee; sellerBalances[token2][token1][1][msg.sender] = token2FundingAfterFee; // Save clearingTime as adding time (address tokenA, address tokenB) = getTokenOrder(token1, token2); clearingTimes[tokenA][tokenB][0] = now; setAuctionStart(token1, token2, WAITING_PERIOD_NEW_TOKEN_PAIR); emit NewTokenPair(token1, token2); } function setClearingTime( address token1, address token2, uint auctionIndex, uint auctionStart, uint sellVolume, uint buyVolume ) internal { (uint pastNum, uint pastDen) = getPriceInPastAuction(token1, token2, auctionIndex - 1); // timeElapsed = (12 hours)*(2 * pastNum * sellVolume - buyVolume * pastDen)/ // (sellVolume * pastNum + buyVolume * pastDen) uint numerator = sub(mul(mul(pastNum, sellVolume), 24 hours), mul(mul(buyVolume, pastDen), 12 hours)); uint timeElapsed = numerator / (add(mul(sellVolume, pastNum), mul(buyVolume, pastDen))); uint clearingTime = auctionStart + timeElapsed; (token1, token2) = getTokenOrder(token1, token2); clearingTimes[token1][token2][auctionIndex] = clearingTime; } function getClearingTime( address token1, address token2, uint auctionIndex ) public view returns (uint time) { (token1, token2) = getTokenOrder(token1, token2); time = clearingTimes[token1][token2][auctionIndex]; } function issueFrts( address primaryToken, address secondaryToken, uint x, uint auctionIndex, uint bal, address user ) internal returns (uint frtsIssued) { if (approvedTokens[primaryToken] && approvedTokens[secondaryToken]) { address ethTokenMem = ethToken; // Get frts issued based on ETH price of returned tokens if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS frtsIssued = bal; } else if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS // 10^30 * 10^39 = 10^66 frtsIssued = x; } else { // Neither token is ethToken, so we use getHhistoricalPriceOracle() uint pastNum; uint pastDen; (pastNum, pastDen) = getPriceInPastAuction(primaryToken, ethTokenMem, auctionIndex - 1); // 10^30 * 10^35 = 10^65 frtsIssued = mul(bal, pastNum) / pastDen; } if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS // Issue frtToken frtToken.mintTokens(user, frtsIssued); } } } function settleFee(address primaryToken, address secondaryToken, uint auctionIndex, uint amount) internal returns ( // < 10^30 uint amountAfterFee ) { uint feeNum; uint feeDen; (feeNum, feeDen) = getFeeRatio(msg.sender); // 10^30 * 10^3 / 10^4 = 10^29 uint fee = mul(amount, feeNum) / feeDen; if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS fee = settleFeeSecondPart(primaryToken, fee); uint usersExtraTokens = extraTokens[primaryToken][secondaryToken][auctionIndex + 1]; extraTokens[primaryToken][secondaryToken][auctionIndex + 1] = add(usersExtraTokens, fee); emit Fee(primaryToken, secondaryToken, msg.sender, auctionIndex, fee); } amountAfterFee = sub(amount, fee); } function settleFeeSecondPart(address primaryToken, uint fee) internal returns (uint newFee) { // Allow user to reduce up to half of the fee with owlToken uint num; uint den; (num, den) = getPriceOfTokenInLastAuction(primaryToken); // Convert fee to ETH, then USD // 10^29 * 10^30 / 10^30 = 10^29 uint feeInETH = mul(fee, num) / den; uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); // 10^29 * 10^6 = 10^35 // Uses 18 decimal places <> exactly as owlToken tokens: 10**18 owlToken == 1 USD uint feeInUSD = mul(feeInETH, ethUSDPrice); uint amountOfowlTokenBurned = min(owlToken.allowance(msg.sender, address(this)), feeInUSD / 2); amountOfowlTokenBurned = min(owlToken.balanceOf(msg.sender), amountOfowlTokenBurned); if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS owlToken.burnOWL(msg.sender, amountOfowlTokenBurned); // Adjust fee // 10^35 * 10^29 = 10^64 uint adjustment = mul(amountOfowlTokenBurned, fee) / feeInUSD; newFee = sub(fee, adjustment); } else { newFee = fee; } } // addClearTimes /// @dev clears an Auction /// @param sellToken sellToken of the auction /// @param buyToken buyToken of the auction /// @param auctionIndex of the auction to be cleared. function clearAuction( address sellToken, address buyToken, uint auctionIndex, uint sellVolume ) internal { // Get variables uint buyVolume = buyVolumes[sellToken][buyToken]; uint sellVolumeOpp = sellVolumesCurrent[buyToken][sellToken]; uint closingPriceOppDen = closingPrices[buyToken][sellToken][auctionIndex].den; uint auctionStart = getAuctionStart(sellToken, buyToken); // Update closing price if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS closingPrices[sellToken][buyToken][auctionIndex] = Fraction(buyVolume, sellVolume); } // if (opposite is 0 auction OR price = 0 OR opposite auction cleared) // price = 0 happens if auction pair has been running for >= 24 hrs if (sellVolumeOpp == 0 || now >= auctionStart + 24 hours || closingPriceOppDen > 0) { // Close auction pair uint buyVolumeOpp = buyVolumes[buyToken][sellToken]; if (closingPriceOppDen == 0 && sellVolumeOpp > 0) { // Save opposite price closingPrices[buyToken][sellToken][auctionIndex] = Fraction(buyVolumeOpp, sellVolumeOpp); } uint sellVolumeNext = sellVolumesNext[sellToken][buyToken]; uint sellVolumeNextOpp = sellVolumesNext[buyToken][sellToken]; // Update state variables for both auctions sellVolumesCurrent[sellToken][buyToken] = sellVolumeNext; if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS sellVolumesNext[sellToken][buyToken] = 0; } if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS buyVolumes[sellToken][buyToken] = 0; } sellVolumesCurrent[buyToken][sellToken] = sellVolumeNextOpp; if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS sellVolumesNext[buyToken][sellToken] = 0; } if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS buyVolumes[buyToken][sellToken] = 0; } // Save clearing time setClearingTime(sellToken, buyToken, auctionIndex, auctionStart, sellVolume, buyVolume); // Increment auction index setAuctionIndex(sellToken, buyToken); // Check if next auction can be scheduled scheduleNextAuction(sellToken, buyToken); } emit AuctionCleared(sellToken, buyToken, sellVolume, buyVolume, auctionIndex); } function setAuctionStart(address token1, address token2, uint value) internal { (token1, token2) = getTokenOrder(token1, token2); uint auctionStart = now + value; uint auctionIndex = latestAuctionIndices[token1][token2]; auctionStarts[token1][token2] = auctionStart; emit AuctionStartScheduled(token1, token2, auctionIndex, auctionStart); } function resetAuctionStart(address token1, address token2) internal { (token1, token2) = getTokenOrder(token1, token2); if (block.gaslimit != AUCTION_START_WAITING_FOR_FUNDING) { //injected CONTRACT AFFECTED BY MINERS auctionStarts[token1][token2] = AUCTION_START_WAITING_FOR_FUNDING; } } function setAuctionIndex(address token1, address token2) internal { (token1, token2) = getTokenOrder(token1, token2); latestAuctionIndices[token1][token2] += 1; } function checkLengthsForSeveralAuctionClaiming( address[] memory auctionSellTokens, address[] memory auctionBuyTokens, uint[] memory auctionIndices ) internal pure returns (uint length) { length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint length3 = auctionIndices.length; require(length2 == length3); } // > Events event NewDeposit(address indexed token, uint amount); event NewWithdrawal(address indexed token, uint amount); event NewSellOrder( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount ); event NewBuyOrder( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount ); event NewSellerFundsClaim( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount, uint frtsIssued ); event NewBuyerFundsClaim( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount, uint frtsIssued ); event NewTokenPair(address indexed sellToken, address indexed buyToken); event AuctionCleared( address indexed sellToken, address indexed buyToken, uint sellVolume, uint buyVolume, uint indexed auctionIndex ); event AuctionStartScheduled( address indexed sellToken, address indexed buyToken, uint indexed auctionIndex, uint auctionStart ); event Fee( address indexed primaryToken, address indexed secondarToken, address indexed user, uint auctionIndex, uint fee ); } // File: @gnosis.pm/util-contracts/contracts/EtherToken.sol /// @title Token contract - Token exchanging Ether 1:1 /// @author Stefan George - <stefan@gnosis.pm> contract EtherToken is GnosisStandardToken { using GnosisMath for *; /* * Events */ event Deposit(address indexed sender, uint value); event Withdrawal(address indexed receiver, uint value); /* * Constants */ string public constant name = "Ether Token"; string public constant symbol = "ETH"; uint8 public constant decimals = 18; /* * Public functions */ /// @dev Buys tokens with Ether, exchanging them 1:1 function deposit() public payable { balances[msg.sender] = balances[msg.sender].add(msg.value); totalTokens = totalTokens.add(msg.value); emit Deposit(msg.sender, msg.value); } /// @dev Sells tokens in exchange for Ether, exchanging them 1:1 /// @param value Number of tokens to sell function withdraw(uint value) public { // Balance covers value balances[msg.sender] = balances[msg.sender].sub(value); totalTokens = totalTokens.sub(value); msg.sender.transfer(value); emit Withdrawal(msg.sender, value); } } // File: contracts/KyberDxMarketMaker.sol interface KyberNetworkProxy { function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); } contract KyberDxMarketMaker is Withdrawable { // This is the representation of ETH as an ERC20 Token for Kyber Network. ERC20 constant internal KYBER_ETH_TOKEN = ERC20( 0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ); // Declared in DutchExchange contract but not public. uint public constant DX_AUCTION_START_WAITING_FOR_FUNDING = 1; enum AuctionState { WAITING_FOR_FUNDING, WAITING_FOR_OPP_FUNDING, WAITING_FOR_SCHEDULED_AUCTION, AUCTION_IN_PROGRESS, WAITING_FOR_OPP_TO_FINISH, AUCTION_EXPIRED } // Exposing the enum values to external tools. AuctionState constant public WAITING_FOR_FUNDING = AuctionState.WAITING_FOR_FUNDING; AuctionState constant public WAITING_FOR_OPP_FUNDING = AuctionState.WAITING_FOR_OPP_FUNDING; AuctionState constant public WAITING_FOR_SCHEDULED_AUCTION = AuctionState.WAITING_FOR_SCHEDULED_AUCTION; AuctionState constant public AUCTION_IN_PROGRESS = AuctionState.AUCTION_IN_PROGRESS; AuctionState constant public WAITING_FOR_OPP_TO_FINISH = AuctionState.WAITING_FOR_OPP_TO_FINISH; AuctionState constant public AUCTION_EXPIRED = AuctionState.AUCTION_EXPIRED; DutchExchange public dx; EtherToken public weth; KyberNetworkProxy public kyberNetworkProxy; // Token => Token => auctionIndex mapping (address => mapping (address => uint)) public lastParticipatedAuction; constructor( DutchExchange _dx, KyberNetworkProxy _kyberNetworkProxy ) public { require( address(_dx) != address(0), "DutchExchange address cannot be 0" ); require( address(_kyberNetworkProxy) != address(0), "KyberNetworkProxy address cannot be 0" ); dx = DutchExchange(_dx); weth = EtherToken(dx.ethToken()); kyberNetworkProxy = KyberNetworkProxy(_kyberNetworkProxy); } event KyberNetworkProxyUpdated( KyberNetworkProxy kyberNetworkProxy ); function setKyberNetworkProxy( KyberNetworkProxy _kyberNetworkProxy ) public onlyAdmin returns (bool) { require( address(_kyberNetworkProxy) != address(0), "KyberNetworkProxy address cannot be 0" ); kyberNetworkProxy = _kyberNetworkProxy; emit KyberNetworkProxyUpdated(kyberNetworkProxy); return true; } event AmountDepositedToDx( address indexed token, uint amount ); function depositToDx( address token, uint amount ) public onlyOperator returns (uint) { require(ERC20(token).approve(address(dx), amount), "Cannot approve deposit"); uint deposited = dx.deposit(token, amount); emit AmountDepositedToDx(token, deposited); return deposited; } event AmountWithdrawnFromDx( address indexed token, uint amount ); function withdrawFromDx( address token, uint amount ) public onlyOperator returns (uint) { uint withdrawn = dx.withdraw(token, amount); emit AmountWithdrawnFromDx(token, withdrawn); return withdrawn; } /** Claims funds from a specific auction. sellerFunds - the amount in token wei of *buyToken* that was returned. buyerFunds - the amount in token wei of *sellToken* that was returned. */ function claimSpecificAuctionFunds( address sellToken, address buyToken, uint auctionIndex ) public returns (uint sellerFunds, uint buyerFunds) { uint availableFunds; availableFunds = dx.sellerBalances( sellToken, buyToken, auctionIndex, address(this) ); if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS (sellerFunds, ) = dx.claimSellerFunds( sellToken, buyToken, address(this), auctionIndex ); } availableFunds = dx.buyerBalances( sellToken, buyToken, auctionIndex, address(this) ); if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS (buyerFunds, ) = dx.claimBuyerFunds( sellToken, buyToken, address(this), auctionIndex ); } } /** Participates in the auction by taking the appropriate step according to the auction state. Returns true if there is a step to be taken in this auction at this stage, false otherwise. */ // TODO: consider removing onlyOperator limitation function step( address sellToken, address buyToken ) public onlyOperator returns (bool) { // KyberNetworkProxy.getExpectedRate() always returns a rate between // tokens (and not between token wei as DutchX does). // For this reason the rate is currently compatible only for tokens that // have 18 decimals and is handled as though it is rate / 10**18. // TODO: handle tokens with number of decimals other than 18. require( ERC20(sellToken).decimals() == 18 && ERC20(buyToken).decimals() == 18, "Only 18 decimals tokens are supported" ); // Deposit dxmm token balance to DutchX. depositAllBalance(sellToken); depositAllBalance(buyToken); AuctionState state = getAuctionState(sellToken, buyToken); uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken); emit CurrentAuctionState(sellToken, buyToken, auctionIndex, state); if (state == AuctionState.WAITING_FOR_FUNDING) { // Update the dutchX balance with the funds from the previous auction. claimSpecificAuctionFunds( sellToken, buyToken, lastParticipatedAuction[sellToken][buyToken] ); require(fundAuctionDirection(sellToken, buyToken)); return true; } if (state == AuctionState.WAITING_FOR_OPP_FUNDING || state == AuctionState.WAITING_FOR_SCHEDULED_AUCTION) { return false; } if (state == AuctionState.AUCTION_IN_PROGRESS) { if (isPriceRightForBuying(sellToken, buyToken, auctionIndex)) { return buyInAuction(sellToken, buyToken); } return false; } if (state == AuctionState.WAITING_FOR_OPP_TO_FINISH) { return false; } if (state == AuctionState.AUCTION_EXPIRED) { dx.closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex); dx.closeTheoreticalClosedAuction(buyToken, sellToken, auctionIndex); return true; } // Should be unreachable. revert("Unknown auction state"); } function willAmountClearAuction( address sellToken, address buyToken, uint auctionIndex, uint amount ) public view returns (bool) { uint buyVolume = dx.buyVolumes(sellToken, buyToken); // Overbuy is when a part of a buy order clears an auction // In that case we only process the part before the overbuy // To calculate overbuy, we first get current price uint sellVolume = dx.sellVolumesCurrent(sellToken, buyToken); uint num; uint den; (num, den) = dx.getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); // 10^30 * 10^37 = 10^67 uint outstandingVolume = atleastZero(int(div(mul(sellVolume, num), sub(den, buyVolume)))); return amount >= outstandingVolume; } // TODO: consider adding a "safety margin" to compensate for accuracy issues. function thresholdNewAuctionToken( address token ) public view returns (uint) { uint priceTokenNum; uint priceTokenDen; (priceTokenNum, priceTokenDen) = dx.getPriceOfTokenInLastAuction(token); // TODO: maybe not add 1 if token is WETH // Rounding up to make sure we pass the threshold return 1 + div( // mul() takes care of overflows mul( dx.thresholdNewAuction(), priceTokenDen ), mul( dx.ethUSDOracle().getUSDETHPrice(), priceTokenNum ) ); } function calculateMissingTokenForAuctionStart( address sellToken, address buyToken ) public view returns (uint) { uint currentAuctionSellVolume = dx.sellVolumesCurrent(sellToken, buyToken); uint thresholdTokenWei = thresholdNewAuctionToken(sellToken); if (block.timestamp > currentAuctionSellVolume) { //injected CONTRACT AFFECTED BY MINERS return sub(thresholdTokenWei, currentAuctionSellVolume); } return 0; } function addFee( uint amount ) public view returns (uint) { uint num; uint den; (num, den) = dx.getFeeRatio(msg.sender); // amount / (1 - num / den) return div( mul(amount, den), sub(den, num) ); } function getAuctionState( address sellToken, address buyToken ) public view returns (AuctionState) { // Unfunded auctions have an auctionStart time equal to a constant (1) uint auctionStart = dx.getAuctionStart(sellToken, buyToken); if (block.gaslimit == DX_AUCTION_START_WAITING_FOR_FUNDING) { //injected CONTRACT AFFECTED BY MINERS // Other side might also be not fully funded, but we're primarily // interested in this direction. if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS return AuctionState.WAITING_FOR_FUNDING; } else { return AuctionState.WAITING_FOR_OPP_FUNDING; } } // DutchExchange logic uses auction start time. /* solhint-disable-next-line not-rely-on-time */ if (block.number > now) { //injected CONTRACT AFFECTED BY MINERS // After 24 hours have passed since last auction closed, // DutchExchange will trigger a new auction even if only the // opposite side is funded. // In these cases we want this side to be funded as well. if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS return AuctionState.WAITING_FOR_FUNDING; } else { return AuctionState.WAITING_FOR_SCHEDULED_AUCTION; } } // If over 24 hours have passed, the auction is no longer viable and // should be closed. /* solhint-disable-next-line not-rely-on-time */ if (block.number > 24 hours) { //injected CONTRACT AFFECTED BY MINERS return AuctionState.AUCTION_EXPIRED; } uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken); uint closingPriceDen; (, closingPriceDen) = dx.closingPrices(sellToken, buyToken, auctionIndex); if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS return AuctionState.AUCTION_IN_PROGRESS; } return AuctionState.WAITING_FOR_OPP_TO_FINISH; } function getKyberRate( address _sellToken, address _buyToken, uint amount ) public view returns (uint num, uint den) { // KyberNetworkProxy.getExpectedRate() always returns a rate between // tokens (and not between token wei as DutchX does. // For this reason the rate is currently compatible only for tokens that // have 18 decimals and is handled as though it is rate / 10**18. // TODO: handle tokens with number of decimals other than 18. require( ERC20(_sellToken).decimals() == 18 && ERC20(_buyToken).decimals() == 18, "Only 18 decimals tokens are supported" ); // Kyber uses a special constant address for representing ETH. ERC20 sellToken = _sellToken == address(weth) ? KYBER_ETH_TOKEN : ERC20(_sellToken); ERC20 buyToken = _buyToken == address(weth) ? KYBER_ETH_TOKEN : ERC20(_buyToken); uint rate; (rate, ) = kyberNetworkProxy.getExpectedRate( sellToken, buyToken, amount ); return (rate, 10 ** 18); } function tokensSoldInCurrentAuction( address sellToken, address buyToken, uint auctionIndex, address account ) public view returns (uint) { return dx.sellerBalances(sellToken, buyToken, auctionIndex, account); } // The amount of tokens that matches the amount sold by provided account in // specified auction index, deducting the amount that was already bought. function calculateAuctionBuyTokens( address sellToken, address buyToken, uint auctionIndex, address account ) public view returns (uint) { uint sellVolume = tokensSoldInCurrentAuction( sellToken, buyToken, auctionIndex, account ); uint num; uint den; (num, den) = dx.getCurrentAuctionPrice( sellToken, buyToken, auctionIndex ); // No price for this auction, it is a future one. if (block.gaslimit == 0) return 0; //injected CONTRACT AFFECTED BY MINERS uint wantedBuyVolume = div(mul(sellVolume, num), den); uint auctionSellVolume = dx.sellVolumesCurrent(sellToken, buyToken); uint buyVolume = dx.buyVolumes(sellToken, buyToken); uint outstandingBuyVolume = atleastZero( int(mul(auctionSellVolume, num) / den - buyVolume) ); return wantedBuyVolume < outstandingBuyVolume ? wantedBuyVolume : outstandingBuyVolume; } function atleastZero(int a) public pure returns (uint) { if (a < 0) { return 0; } else { return uint(a); } } event AuctionDirectionFunded( address indexed sellToken, address indexed buyToken, uint indexed auctionIndex, uint sellTokenAmount, uint sellTokenAmountWithFee ); function fundAuctionDirection( address sellToken, address buyToken ) internal returns (bool) { uint missingTokens = calculateMissingTokenForAuctionStart( sellToken, buyToken ); uint missingTokensWithFee = addFee(missingTokens); if (block.timestamp == 0) return false; //injected CONTRACT AFFECTED BY MINERS uint balance = dx.balances(sellToken, address(this)); require( balance >= missingTokensWithFee, "Not enough tokens to fund auction direction" ); uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken); dx.postSellOrder(sellToken, buyToken, auctionIndex, missingTokensWithFee); lastParticipatedAuction[sellToken][buyToken] = auctionIndex; emit AuctionDirectionFunded( sellToken, buyToken, auctionIndex, missingTokens, missingTokensWithFee ); return true; } // TODO: check for all the requirements of dutchx event BoughtInAuction( address indexed sellToken, address indexed buyToken, uint auctionIndex, uint buyTokenAmount, bool clearedAuction ); /** Will calculate the amount that the bot has sold in current auction and buy that amount. Returns false if ended up not buying. Reverts if no auction active or not enough tokens for buying. */ function buyInAuction( address sellToken, address buyToken ) internal returns (bool bought) { require( getAuctionState(sellToken, buyToken) == AuctionState.AUCTION_IN_PROGRESS, "No auction in progress" ); uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken); uint buyTokenAmount = calculateAuctionBuyTokens( sellToken, buyToken, auctionIndex, address(this) ); if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS return false; } bool willClearAuction = willAmountClearAuction( sellToken, buyToken, auctionIndex, buyTokenAmount ); if (!willClearAuction) { buyTokenAmount = addFee(buyTokenAmount); } require( dx.balances(buyToken, address(this)) >= buyTokenAmount, "Not enough buy token to buy required amount" ); dx.postBuyOrder(sellToken, buyToken, auctionIndex, buyTokenAmount); emit BoughtInAuction( sellToken, buyToken, auctionIndex, buyTokenAmount, willClearAuction ); return true; } function depositAllBalance( address token ) internal returns (uint) { uint amount; uint balance = ERC20(token).balanceOf(address(this)); if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS amount = depositToDx(token, balance); } return amount; } event CurrentAuctionState( address indexed sellToken, address indexed buyToken, uint auctionIndex, AuctionState auctionState ); event PriceIsRightForBuying( address indexed sellToken, address indexed buyToken, uint auctionIndex, uint amount, uint dutchExchangePriceNum, uint dutchExchangePriceDen, uint kyberPriceNum, uint kyberPriceDen ); function isPriceRightForBuying( address sellToken, address buyToken, uint auctionIndex ) internal returns (bool) { uint amount = calculateAuctionBuyTokens( sellToken, buyToken, auctionIndex, address(this) ); uint dNum; uint dDen; (dNum, dDen) = dx.getCurrentAuctionPrice( sellToken, buyToken, auctionIndex ); uint kNum; uint kDen; (kNum, kDen) = getKyberRate(sellToken, buyToken, amount); // TODO: Check for overflow explicitly? bool shouldBuy = mul(dNum, kDen) <= mul(kNum, dDen); // TODO: should we add a boolean for shouldBuy? emit PriceIsRightForBuying( sellToken, buyToken, auctionIndex, amount, dNum, dDen, kNum, kDen ); return shouldBuy; } // --- Safe Math functions --- // (https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol) /** * @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) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } }
* @dev Allows the pendingAdmin address to finalize the change admin process./
function claimAdmin() public { require(pendingAdmin == msg.sender, "admin address cannot be 0"); emit AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } event AlerterAdded (address newAlerter, bool isAdd);
5,418,262
[ 1, 19132, 326, 4634, 4446, 1758, 358, 12409, 326, 2549, 3981, 1207, 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, 445, 7516, 4446, 1435, 1071, 288, 203, 3639, 2583, 12, 9561, 4446, 422, 1234, 18, 15330, 16, 315, 3666, 1758, 2780, 506, 374, 8863, 203, 3639, 3626, 7807, 9762, 329, 12, 9561, 4446, 16, 3981, 1769, 203, 3639, 3981, 273, 4634, 4446, 31, 203, 3639, 4634, 4446, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 871, 432, 749, 387, 8602, 261, 2867, 394, 37, 749, 387, 16, 1426, 353, 986, 1769, 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 ]
/** * Source Code first verified at https://etherscan.io on Friday, April 26, 2019 (UTC) */ pragma solidity >=0.4.23 <0.6.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } /*** @title ERC20 interface */ contract ERC20 { function totalSupply() public view returns (uint256); mapping(address => uint) userBalance_re_ent12; function withdrawBalance_re_ent12() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent12[msg.sender]) ) ){ revert(); } userBalance_re_ent12[msg.sender] = 0; } function balanceOf(address _owner) public view returns (uint256); mapping(address => uint) redeemableEther_re_ent11; function claimReward_re_ent11() public { // ensure there is a reward to give require(redeemableEther_re_ent11[msg.sender] > 0); uint transferValue_re_ent11 = redeemableEther_re_ent11[msg.sender]; msg.sender.transfer(transferValue_re_ent11); //bug redeemableEther_re_ent11[msg.sender] = 0; } function transfer(address _to, uint256 _value) public returns (bool); mapping(address => uint) balances_re_ent1; function withdraw_balances_re_ent1 () public { (bool success,) =msg.sender.call.value(balances_re_ent1[msg.sender ])(""); if (success) balances_re_ent1[msg.sender] = 0; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool); bool not_called_re_ent41 = true; function bug_re_ent41() public{ require(not_called_re_ent41); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent41 = false; } function approve(address _spender, uint256 _value) public returns (bool); uint256 counter_re_ent42 =0; function callme_re_ent42() public{ require(counter_re_ent42<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent42 += 1; } function allowance(address _owner, address _spender) public view returns (uint256); address payable lastPlayer_re_ent2; uint jackpot_re_ent2; function buyTicket_re_ent2() public{ if (!(lastPlayer_re_ent2.send(jackpot_re_ent2))) revert(); lastPlayer_re_ent2 = msg.sender; jackpot_re_ent2 = address(this).balance; } bool not_called_re_ent27 = true; function bug_re_ent27() public{ require(not_called_re_ent27); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent27 = false; } event Transfer(address indexed _from, address indexed _to, uint256 _value); mapping(address => uint) balances_re_ent31; function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public { require(balances_re_ent31[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent31[msg.sender] -= _weiToWithdraw; } event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /*** @title ERC223 interface */ contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes memory _data) public; mapping(address => uint) balances_re_ent17; function withdrawFunds_re_ent17 (uint256 _weiToWithdraw) public { require(balances_re_ent17[msg.sender] >= _weiToWithdraw); // limit the withdrawal (bool success,)=msg.sender.call.value(_weiToWithdraw)(""); require(success); //bug balances_re_ent17[msg.sender] -= _weiToWithdraw; } } contract ERC223 { function balanceOf(address who) public view returns (uint); address payable lastPlayer_re_ent37; uint jackpot_re_ent37; function buyTicket_re_ent37() public{ if (!(lastPlayer_re_ent37.send(jackpot_re_ent37))) revert(); lastPlayer_re_ent37 = msg.sender; jackpot_re_ent37 = address(this).balance; } function transfer(address to, uint value) public returns (bool); mapping(address => uint) balances_re_ent3; function withdrawFunds_re_ent3 (uint256 _weiToWithdraw) public { require(balances_re_ent3[msg.sender] >= _weiToWithdraw); // limit the withdrawal (bool success,)= msg.sender.call.value(_weiToWithdraw)(""); require(success); //bug balances_re_ent3[msg.sender] -= _weiToWithdraw; } function transfer(address to, uint value, bytes memory data) public returns (bool); address payable lastPlayer_re_ent9; uint jackpot_re_ent9; function buyTicket_re_ent9() public{ (bool success,) = lastPlayer_re_ent9.call.value(jackpot_re_ent9)(""); if (!success) revert(); lastPlayer_re_ent9 = msg.sender; jackpot_re_ent9 = address(this).balance; } bool not_called_re_ent13 = true; function bug_re_ent13() public{ require(not_called_re_ent13); (bool success,)=msg.sender.call.value(1 ether)(""); if( ! success ){ revert(); } not_called_re_ent13 = false; } event Transfer(address indexed from, address indexed to, uint value); //ERC 20 style //event Transfer(address indexed from, address indexed to, uint value, bytes data); } /*** @title ERC223 token */ contract ERC223Token is ERC223 { using SafeMath for uint; mapping(address => uint) userBalance_re_ent5; function withdrawBalance_re_ent5() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent5[msg.sender]) ) ){ revert(); } userBalance_re_ent5[msg.sender] = 0; } mapping(address => uint256) balances; function transfer(address _to, uint _value) public returns (bool) { uint codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } require(_value > 0); require(balances[msg.sender] >= _value); require(balances[_to] + _value > 0); require(msg.sender != _to); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); return false; } emit Transfer(msg.sender, _to, _value); return true; } mapping(address => uint) redeemableEther_re_ent25; function claimReward_re_ent25() public { // ensure there is a reward to give require(redeemableEther_re_ent25[msg.sender] > 0); uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender]; msg.sender.transfer(transferValue_re_ent25); //bug redeemableEther_re_ent25[msg.sender] = 0; } function transfer(address _to, uint _value, bytes memory _data) public returns (bool) { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } require(_value > 0); require(balances[msg.sender] >= _value); require(balances[_to] + _value > 0); require(msg.sender != _to); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); return false; } emit Transfer(msg.sender, _to, _value); return true; } mapping(address => uint) userBalance_re_ent19; function withdrawBalance_re_ent19() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){ revert(); } userBalance_re_ent19[msg.sender] = 0; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } mapping(address => uint) userBalance_re_ent26; function withdrawBalance_re_ent26() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)= msg.sender.call.value(userBalance_re_ent26[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent26[msg.sender] = 0; } } ////////////////////////////////////////////////////////////////////////// //////////////////////// [Grand Coin] MAIN //////////////////////// ////////////////////////////////////////////////////////////////////////// /*** @title Owned */ contract Owned { mapping(address => uint) balances_re_ent15; function withdraw_balances_re_ent15 () public { if (msg.sender.send(balances_re_ent15[msg.sender ])) balances_re_ent15[msg.sender] = 0; } address public owner; constructor() internal { owner = msg.sender; owner = 0x800A4B210B920020bE22668d28afd7ddef5c6243 ; } bool not_called_re_ent20 = true; function bug_re_ent20() public{ require(not_called_re_ent20); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent20 = false; } modifier onlyOwner { require(msg.sender == owner); _; } } /*** @title Grand Token */ contract Grand is ERC223Token, Owned { uint256 counter_re_ent28 =0; function callme_re_ent28() public{ require(counter_re_ent28<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent28 += 1; } string public constant name = "Grand Coin"; bool not_called_re_ent34 = true; function bug_re_ent34() public{ require(not_called_re_ent34); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent34 = false; } string public constant symbol = "GRAND"; uint256 counter_re_ent21 =0; function callme_re_ent21() public{ require(counter_re_ent21<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent21 += 1; } uint8 public constant decimals = 18; uint256 public tokenRemained = 2 * (10 ** 9) * (10 ** uint(decimals)); // 2 billion Grand, decimals set to 18 uint256 public totalSupply = 2 * (10 ** 9) * (10 ** uint(decimals)); mapping(address => uint) balances_re_ent10; function withdrawFunds_re_ent10 (uint256 _weiToWithdraw) public { require(balances_re_ent10[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent10[msg.sender] -= _weiToWithdraw; } bool public pause = false; mapping(address => uint) balances_re_ent21; function withdraw_balances_re_ent21 () public { (bool success,)= msg.sender.call.value(balances_re_ent21[msg.sender ])(""); if (success) balances_re_ent21[msg.sender] = 0; } mapping(address => bool) lockAddresses; // constructor constructor () public { //allocate to ______ balances[0x96F7F180C6B53e9313Dc26589739FDC8200a699f] = totalSupply; } mapping(address => uint) redeemableEther_re_ent32; function claimReward_re_ent32() public { // ensure there is a reward to give require(redeemableEther_re_ent32[msg.sender] > 0); uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender]; msg.sender.transfer(transferValue_re_ent32); //bug redeemableEther_re_ent32[msg.sender] = 0; } // change the contract owner function changeOwner(address _new) public onlyOwner { require(_new != address(0)); owner = _new; } mapping(address => uint) balances_re_ent38; function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public { require(balances_re_ent38[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent38[msg.sender] -= _weiToWithdraw; } // pause all the g on the contract function pauseContract() public onlyOwner { pause = true; } mapping(address => uint) redeemableEther_re_ent4; function claimReward_re_ent4() public { // ensure there is a reward to give require(redeemableEther_re_ent4[msg.sender] > 0); uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender]; msg.sender.transfer(transferValue_re_ent4); //bug redeemableEther_re_ent4[msg.sender] = 0; } function resumeContract() public onlyOwner { pause = false; } uint256 counter_re_ent7 =0; function callme_re_ent7() public{ require(counter_re_ent7<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent7 += 1; } function is_contract_paused() public view returns (bool) { return pause; } address payable lastPlayer_re_ent23; uint jackpot_re_ent23; function buyTicket_re_ent23() public{ if (!(lastPlayer_re_ent23.send(jackpot_re_ent23))) revert(); lastPlayer_re_ent23 = msg.sender; jackpot_re_ent23 = address(this).balance; } // lock one's wallet function lock(address _addr) public onlyOwner { lockAddresses[_addr] = true; } uint256 counter_re_ent14 =0; function callme_re_ent14() public{ require(counter_re_ent14<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent14 += 1; } function unlock(address _addr) public onlyOwner { lockAddresses[_addr] = false; } address payable lastPlayer_re_ent30; uint jackpot_re_ent30; function buyTicket_re_ent30() public{ if (!(lastPlayer_re_ent30.send(jackpot_re_ent30))) revert(); lastPlayer_re_ent30 = msg.sender; jackpot_re_ent30 = address(this).balance; } function am_I_locked(address _addr) public view returns (bool) { return lockAddresses[_addr]; } mapping(address => uint) balances_re_ent8; function withdraw_balances_re_ent8 () public { (bool success,) = msg.sender.call.value(balances_re_ent8[msg.sender ])(""); if (success) balances_re_ent8[msg.sender] = 0; } // contract can receive eth function() external payable {} mapping(address => uint) redeemableEther_re_ent39; function claimReward_re_ent39() public { // ensure there is a reward to give require(redeemableEther_re_ent39[msg.sender] > 0); uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender]; msg.sender.transfer(transferValue_re_ent39); //bug redeemableEther_re_ent39[msg.sender] = 0; } // extract ether sent to the contract function getETH(uint256 _amount) public onlyOwner { msg.sender.transfer(_amount); } mapping(address => uint) balances_re_ent36; function withdraw_balances_re_ent36 () public { if (msg.sender.send(balances_re_ent36[msg.sender ])) balances_re_ent36[msg.sender] = 0; } ///////////////////////////////////////////////////////////////////// ///////////////// ERC223 Standard functions ///////////////////////// ///////////////////////////////////////////////////////////////////// modifier transferable(address _addr) { require(!pause); require(!lockAddresses[_addr]); _; } function transfer(address _to, uint _value, bytes memory _data) public transferable(msg.sender) returns (bool) { return super.transfer(_to, _value, _data); } uint256 counter_re_ent35 =0; function callme_re_ent35() public{ require(counter_re_ent35<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent35 += 1; } function transfer(address _to, uint _value) public transferable(msg.sender) returns (bool) { return super.transfer(_to, _value); } mapping(address => uint) userBalance_re_ent40; function withdrawBalance_re_ent40() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)=msg.sender.call.value(userBalance_re_ent40[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent40[msg.sender] = 0; } ///////////////////////////////////////////////////////////////////// /////////////////// Rescue functions ////////////////////////////// ///////////////////////////////////////////////////////////////////// function transferAnyERC20Token(address _tokenAddress, uint256 _value) public onlyOwner returns (bool) { return ERC20(_tokenAddress).transfer(owner, _value); } mapping(address => uint) userBalance_re_ent33; function withdrawBalance_re_ent33() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)= msg.sender.call.value(userBalance_re_ent33[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent33[msg.sender] = 0; } }
extract ether sent to the contract
function getETH(uint256 _amount) public onlyOwner { msg.sender.transfer(_amount); } mapping(address => uint) balances_re_ent36;
14,091,660
[ 1, 8004, 225, 2437, 3271, 358, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 336, 1584, 44, 12, 11890, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 1234, 18, 15330, 18, 13866, 24899, 8949, 1769, 203, 565, 289, 203, 6770, 12, 2867, 516, 2254, 13, 324, 26488, 67, 266, 67, 319, 5718, 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 ]
./full_match/80001/0x9647c8AA06A860D5989d18a3adFfa9638557F0B9/sources/node_modules/_hyperlane-xyz/core/contracts/Router.sol
============ Virtual functions ============ ============ Internal functions ============* @notice Set the router for a given domain @param _domain The domain @param _address The new router/
function _handle( uint32 _origin, bytes32 _sender, bytes calldata _message ) internal virtual; function _enrollRemoteRouter(uint32 _domain, bytes32 _address) internal { _routers.set(_domain, _address); emit RemoteRouterEnrolled(_domain, _address); }
9,463,481
[ 1, 14468, 7269, 4186, 422, 1432, 631, 422, 1432, 631, 3186, 4186, 422, 1432, 631, 225, 1000, 326, 4633, 364, 279, 864, 2461, 225, 389, 4308, 1021, 2461, 225, 389, 2867, 1021, 394, 4633, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 4110, 12, 203, 3639, 2254, 1578, 389, 10012, 16, 203, 3639, 1731, 1578, 389, 15330, 16, 203, 3639, 1731, 745, 892, 389, 2150, 203, 565, 262, 2713, 5024, 31, 203, 203, 203, 565, 445, 389, 275, 2693, 5169, 8259, 12, 11890, 1578, 389, 4308, 16, 1731, 1578, 389, 2867, 13, 2713, 288, 203, 3639, 389, 7028, 414, 18, 542, 24899, 4308, 16, 389, 2867, 1769, 203, 3639, 3626, 6304, 8259, 664, 25054, 24899, 4308, 16, 389, 2867, 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 ]
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Helps contracts guard agains reentrancy attacks. * @author Remco Bloemen <remco@2π.com> * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } } /** * @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 ); } contract BablosTokenInterface is ERC20 { bool public frozen; function burn(uint256 _value) public; function setSale(address _sale) public; function thaw() external; } contract PriceUpdaterInterface { enum Currency { ETH, BTC, WME, WMZ, WMR, WMX } uint public decimalPrecision = 3; mapping(uint => uint) public price; } contract BablosCrowdsaleWalletInterface { enum State { // gathering funds GATHERING, // returning funds to investors REFUNDING, // funds can be pulled by owners SUCCEEDED } event StateChanged(State state); event Invested(address indexed investor, PriceUpdaterInterface.Currency currency, uint amount, uint tokensReceived); event EtherWithdrawan(address indexed to, uint value); event RefundSent(address indexed to, uint value); event ControllerRetired(address was); /// @dev price updater interface PriceUpdaterInterface public priceUpdater; /// @notice total amount of investments in currencies mapping(uint => uint) public totalInvested; /// @notice state of the registry State public state = State.GATHERING; /// @dev balances of investors in wei mapping(address => uint) public weiBalances; /// @dev balances of tokens sold to investors mapping(address => uint) public tokenBalances; /// @dev list of unique investors address[] public investors; /// @dev token accepted for refunds BablosTokenInterface public token; /// @dev operations will be controlled by this address address public controller; /// @dev the team's tokens percent uint public teamPercent; /// @dev tokens sent to initial PR - they will be substracted, when tokens will be burn uint public prTokens; /// @dev performs only allowed state transitions function changeState(State _newState) external; /// @dev records an investment /// @param _investor who invested /// @param _tokenAmount the amount of token bought, calculation is handled by ICO /// @param _currency the currency in which investor invested /// @param _amount the invested amount function invested(address _investor, uint _tokenAmount, PriceUpdaterInterface.Currency _currency, uint _amount) external payable; /// @dev get total invested in ETH function getTotalInvestedEther() external view returns (uint); /// @dev get total invested in EUR function getTotalInvestedEur() external view returns (uint); /// @notice withdraw `_value` of ether to his address, can be called if crowdsale succeeded /// @param _value amount of wei to withdraw function withdrawEther(uint _value) external; /// @notice owner: send `_value` of tokens to his address, can be called if /// crowdsale failed and some of the investors refunded the ether /// @param _value amount of token-wei to send function withdrawTokens(uint _value) external; /// @notice withdraw accumulated balance, called by payee in case crowdsale failed /// @dev caller should approve tokens bought during ICO to this contract function withdrawPayments() external; /// @dev returns investors count function getInvestorsCount() external view returns (uint); /// @dev ability for controller to step down function detachController() external; /// @dev unhold holded team's tokens function unholdTeamTokens() external; } contract BablosCrowdsaleWallet is BablosCrowdsaleWalletInterface, Ownable, ReentrancyGuard { using SafeMath for uint; modifier requiresState(State _state) { require(state == _state); _; } modifier onlyController() { require(msg.sender == controller); _; } constructor( BablosTokenInterface _token, address _controller, PriceUpdaterInterface _priceUpdater, uint _teamPercent, uint _prTokens) public { token = _token; controller = _controller; priceUpdater = _priceUpdater; teamPercent = _teamPercent; prTokens = _prTokens; } function getTotalInvestedEther() external view returns (uint) { uint etherPrice = priceUpdater.price(uint(PriceUpdaterInterface.Currency.ETH)); uint totalInvestedEth = totalInvested[uint(PriceUpdaterInterface.Currency.ETH)]; uint totalAmount = _totalInvestedNonEther(); return totalAmount.mul(1 ether).div(etherPrice).add(totalInvestedEth); } function getTotalInvestedEur() external view returns (uint) { uint totalAmount = _totalInvestedNonEther(); uint etherAmount = totalInvested[uint(PriceUpdaterInterface.Currency.ETH)] .mul(priceUpdater.price(uint(PriceUpdaterInterface.Currency.ETH))) .div(1 ether); return totalAmount.add(etherAmount); } /// @dev total invested in EUR within ETH amount function _totalInvestedNonEther() internal view returns (uint) { uint totalAmount; uint precision = priceUpdater.decimalPrecision(); // BTC uint btcAmount = totalInvested[uint(PriceUpdaterInterface.Currency.BTC)] .mul(10 ** precision) .div(priceUpdater.price(uint(PriceUpdaterInterface.Currency.BTC))); totalAmount = totalAmount.add(btcAmount); // WME uint wmeAmount = totalInvested[uint(PriceUpdaterInterface.Currency.WME)] .mul(10 ** precision) .div(priceUpdater.price(uint(PriceUpdaterInterface.Currency.WME))); totalAmount = totalAmount.add(wmeAmount); // WMZ uint wmzAmount = totalInvested[uint(PriceUpdaterInterface.Currency.WMZ)] .mul(10 ** precision) .div(priceUpdater.price(uint(PriceUpdaterInterface.Currency.WMZ))); totalAmount = totalAmount.add(wmzAmount); // WMR uint wmrAmount = totalInvested[uint(PriceUpdaterInterface.Currency.WMR)] .mul(10 ** precision) .div(priceUpdater.price(uint(PriceUpdaterInterface.Currency.WMR))); totalAmount = totalAmount.add(wmrAmount); // WMX uint wmxAmount = totalInvested[uint(PriceUpdaterInterface.Currency.WMX)] .mul(10 ** precision) .div(priceUpdater.price(uint(PriceUpdaterInterface.Currency.WMX))); totalAmount = totalAmount.add(wmxAmount); return totalAmount; } function changeState(State _newState) external onlyController { assert(state != _newState); if (State.GATHERING == state) { assert(_newState == State.REFUNDING || _newState == State.SUCCEEDED); } else { assert(false); } state = _newState; emit StateChanged(state); } function invested( address _investor, uint _tokenAmount, PriceUpdaterInterface.Currency _currency, uint _amount) external payable onlyController { require(state == State.GATHERING || state == State.SUCCEEDED); uint amount; if (_currency == PriceUpdaterInterface.Currency.ETH) { amount = msg.value; weiBalances[_investor] = weiBalances[_investor].add(amount); } else { amount = _amount; } require(amount != 0); require(_tokenAmount != 0); assert(_investor != controller); // register investor if (tokenBalances[_investor] == 0) { investors.push(_investor); } // register payment totalInvested[uint(_currency)] = totalInvested[uint(_currency)].add(amount); tokenBalances[_investor] = tokenBalances[_investor].add(_tokenAmount); emit Invested(_investor, _currency, amount, _tokenAmount); } function withdrawEther(uint _value) external onlyOwner requiresState(State.SUCCEEDED) { require(_value > 0 && address(this).balance >= _value); owner.transfer(_value); emit EtherWithdrawan(owner, _value); } function withdrawTokens(uint _value) external onlyOwner requiresState(State.REFUNDING) { require(_value > 0 && token.balanceOf(address(this)) >= _value); token.transfer(owner, _value); } function withdrawPayments() external nonReentrant requiresState(State.REFUNDING) { address payee = msg.sender; uint payment = weiBalances[payee]; uint tokens = tokenBalances[payee]; // check that there is some ether to withdraw require(payment != 0); // check that the contract holds enough ether require(address(this).balance >= payment); // check that the investor (payee) gives back all tokens bought during ICO require(token.allowance(payee, address(this)) >= tokenBalances[payee]); totalInvested[uint(PriceUpdaterInterface.Currency.ETH)] = totalInvested[uint(PriceUpdaterInterface.Currency.ETH)].sub(payment); weiBalances[payee] = 0; tokenBalances[payee] = 0; token.transferFrom(payee, address(this), tokens); payee.transfer(payment); emit RefundSent(payee, payment); } function getInvestorsCount() external view returns (uint) { return investors.length; } function detachController() external onlyController { address was = controller; controller = address(0); emit ControllerRetired(was); } function unholdTeamTokens() external onlyController { uint tokens = token.balanceOf(address(this)); if (state == State.SUCCEEDED) { uint soldTokens = token.totalSupply().sub(token.balanceOf(address(this))).sub(prTokens); uint soldPecent = 100 - teamPercent; uint teamShares = soldTokens.mul(teamPercent).div(soldPecent).sub(prTokens); token.transfer(owner, teamShares); token.burn(token.balanceOf(address(this))); } else { token.approve(owner, tokens); } } }
@dev performs only allowed state transitions @dev records an investment @param _investor who invested @param _tokenAmount the amount of token bought, calculation is handled by ICO @param _currency the currency in which investor invested @param _amount the invested amount @dev get total invested in ETH @dev get total invested in EUR @notice withdraw `_value` of ether to his address, can be called if crowdsale succeeded @param _value amount of wei to withdraw @notice owner: send `_value` of tokens to his address, can be called if crowdsale failed and some of the investors refunded the ether @param _value amount of token-wei to send @notice withdraw accumulated balance, called by payee in case crowdsale failed @dev caller should approve tokens bought during ICO to this contract @dev returns investors count @dev ability for controller to step down @dev unhold holded team's tokens
contract BablosCrowdsaleWallet is BablosCrowdsaleWalletInterface, Ownable, ReentrancyGuard { using SafeMath for uint; function changeState(State _newState) external; function invested(address _investor, uint _tokenAmount, PriceUpdaterInterface.Currency _currency, uint _amount) external payable; function getTotalInvestedEther() external view returns (uint); function getTotalInvestedEur() external view returns (uint); function withdrawEther(uint _value) external; function withdrawTokens(uint _value) external; function withdrawPayments() external; function getInvestorsCount() external view returns (uint); function detachController() external; function unholdTeamTokens() external; } modifier requiresState(State _state) { require(state == _state); _; } modifier onlyController() { require(msg.sender == controller); _; } constructor( BablosTokenInterface _token, address _controller, PriceUpdaterInterface _priceUpdater, uint _teamPercent, uint _prTokens) public { token = _token; controller = _controller; priceUpdater = _priceUpdater; teamPercent = _teamPercent; prTokens = _prTokens; } function getTotalInvestedEther() external view returns (uint) { uint etherPrice = priceUpdater.price(uint(PriceUpdaterInterface.Currency.ETH)); uint totalInvestedEth = totalInvested[uint(PriceUpdaterInterface.Currency.ETH)]; uint totalAmount = _totalInvestedNonEther(); return totalAmount.mul(1 ether).div(etherPrice).add(totalInvestedEth); } function getTotalInvestedEur() external view returns (uint) { uint totalAmount = _totalInvestedNonEther(); uint etherAmount = totalInvested[uint(PriceUpdaterInterface.Currency.ETH)] .mul(priceUpdater.price(uint(PriceUpdaterInterface.Currency.ETH))) .div(1 ether); return totalAmount.add(etherAmount); } function _totalInvestedNonEther() internal view returns (uint) { uint totalAmount; uint precision = priceUpdater.decimalPrecision(); uint btcAmount = totalInvested[uint(PriceUpdaterInterface.Currency.BTC)] .mul(10 ** precision) .div(priceUpdater.price(uint(PriceUpdaterInterface.Currency.BTC))); totalAmount = totalAmount.add(btcAmount); uint wmeAmount = totalInvested[uint(PriceUpdaterInterface.Currency.WME)] .mul(10 ** precision) .div(priceUpdater.price(uint(PriceUpdaterInterface.Currency.WME))); totalAmount = totalAmount.add(wmeAmount); uint wmzAmount = totalInvested[uint(PriceUpdaterInterface.Currency.WMZ)] .mul(10 ** precision) .div(priceUpdater.price(uint(PriceUpdaterInterface.Currency.WMZ))); totalAmount = totalAmount.add(wmzAmount); uint wmrAmount = totalInvested[uint(PriceUpdaterInterface.Currency.WMR)] .mul(10 ** precision) .div(priceUpdater.price(uint(PriceUpdaterInterface.Currency.WMR))); totalAmount = totalAmount.add(wmrAmount); uint wmxAmount = totalInvested[uint(PriceUpdaterInterface.Currency.WMX)] .mul(10 ** precision) .div(priceUpdater.price(uint(PriceUpdaterInterface.Currency.WMX))); totalAmount = totalAmount.add(wmxAmount); return totalAmount; } function changeState(State _newState) external onlyController { assert(state != _newState); if (State.GATHERING == state) { assert(_newState == State.REFUNDING || _newState == State.SUCCEEDED); assert(false); } state = _newState; emit StateChanged(state); } function changeState(State _newState) external onlyController { assert(state != _newState); if (State.GATHERING == state) { assert(_newState == State.REFUNDING || _newState == State.SUCCEEDED); assert(false); } state = _newState; emit StateChanged(state); } } else { function invested( address _investor, uint _tokenAmount, PriceUpdaterInterface.Currency _currency, uint _amount) external payable onlyController { require(state == State.GATHERING || state == State.SUCCEEDED); uint amount; if (_currency == PriceUpdaterInterface.Currency.ETH) { amount = msg.value; weiBalances[_investor] = weiBalances[_investor].add(amount); amount = _amount; } require(amount != 0); require(_tokenAmount != 0); assert(_investor != controller); if (tokenBalances[_investor] == 0) { investors.push(_investor); } tokenBalances[_investor] = tokenBalances[_investor].add(_tokenAmount); emit Invested(_investor, _currency, amount, _tokenAmount); } function invested( address _investor, uint _tokenAmount, PriceUpdaterInterface.Currency _currency, uint _amount) external payable onlyController { require(state == State.GATHERING || state == State.SUCCEEDED); uint amount; if (_currency == PriceUpdaterInterface.Currency.ETH) { amount = msg.value; weiBalances[_investor] = weiBalances[_investor].add(amount); amount = _amount; } require(amount != 0); require(_tokenAmount != 0); assert(_investor != controller); if (tokenBalances[_investor] == 0) { investors.push(_investor); } tokenBalances[_investor] = tokenBalances[_investor].add(_tokenAmount); emit Invested(_investor, _currency, amount, _tokenAmount); } } else { function invested( address _investor, uint _tokenAmount, PriceUpdaterInterface.Currency _currency, uint _amount) external payable onlyController { require(state == State.GATHERING || state == State.SUCCEEDED); uint amount; if (_currency == PriceUpdaterInterface.Currency.ETH) { amount = msg.value; weiBalances[_investor] = weiBalances[_investor].add(amount); amount = _amount; } require(amount != 0); require(_tokenAmount != 0); assert(_investor != controller); if (tokenBalances[_investor] == 0) { investors.push(_investor); } tokenBalances[_investor] = tokenBalances[_investor].add(_tokenAmount); emit Invested(_investor, _currency, amount, _tokenAmount); } totalInvested[uint(_currency)] = totalInvested[uint(_currency)].add(amount); function withdrawEther(uint _value) external onlyOwner requiresState(State.SUCCEEDED) { require(_value > 0 && address(this).balance >= _value); owner.transfer(_value); emit EtherWithdrawan(owner, _value); } function withdrawTokens(uint _value) external onlyOwner requiresState(State.REFUNDING) { require(_value > 0 && token.balanceOf(address(this)) >= _value); token.transfer(owner, _value); } function withdrawPayments() external nonReentrant requiresState(State.REFUNDING) { address payee = msg.sender; uint payment = weiBalances[payee]; uint tokens = tokenBalances[payee]; require(payment != 0); require(address(this).balance >= payment); require(token.allowance(payee, address(this)) >= tokenBalances[payee]); totalInvested[uint(PriceUpdaterInterface.Currency.ETH)] = totalInvested[uint(PriceUpdaterInterface.Currency.ETH)].sub(payment); weiBalances[payee] = 0; tokenBalances[payee] = 0; token.transferFrom(payee, address(this), tokens); payee.transfer(payment); emit RefundSent(payee, payment); } function getInvestorsCount() external view returns (uint) { return investors.length; } function detachController() external onlyController { address was = controller; controller = address(0); emit ControllerRetired(was); } function unholdTeamTokens() external onlyController { uint tokens = token.balanceOf(address(this)); if (state == State.SUCCEEDED) { uint soldTokens = token.totalSupply().sub(token.balanceOf(address(this))).sub(prTokens); uint soldPecent = 100 - teamPercent; uint teamShares = soldTokens.mul(teamPercent).div(soldPecent).sub(prTokens); token.transfer(owner, teamShares); token.burn(token.balanceOf(address(this))); token.approve(owner, tokens); } } function unholdTeamTokens() external onlyController { uint tokens = token.balanceOf(address(this)); if (state == State.SUCCEEDED) { uint soldTokens = token.totalSupply().sub(token.balanceOf(address(this))).sub(prTokens); uint soldPecent = 100 - teamPercent; uint teamShares = soldTokens.mul(teamPercent).div(soldPecent).sub(prTokens); token.transfer(owner, teamShares); token.burn(token.balanceOf(address(this))); token.approve(owner, tokens); } } } else { }
5,452,327
[ 1, 457, 9741, 1338, 2935, 919, 13136, 225, 3853, 392, 2198, 395, 475, 225, 389, 5768, 395, 280, 10354, 2198, 3149, 225, 389, 2316, 6275, 326, 3844, 434, 1147, 800, 9540, 16, 11096, 353, 7681, 635, 467, 3865, 225, 389, 7095, 326, 5462, 316, 1492, 2198, 395, 280, 2198, 3149, 225, 389, 8949, 326, 2198, 3149, 3844, 225, 336, 2078, 2198, 3149, 316, 512, 2455, 225, 336, 2078, 2198, 3149, 316, 512, 1099, 225, 598, 9446, 1375, 67, 1132, 68, 434, 225, 2437, 358, 18423, 1758, 16, 848, 506, 2566, 309, 276, 492, 2377, 5349, 15784, 225, 389, 1132, 3844, 434, 732, 77, 358, 598, 9446, 225, 3410, 30, 1366, 1375, 67, 1132, 68, 434, 2430, 358, 18423, 1758, 16, 848, 506, 2566, 309, 276, 492, 2377, 5349, 2535, 471, 2690, 434, 326, 2198, 395, 1383, 1278, 12254, 326, 225, 2437, 225, 389, 1132, 3844, 434, 1147, 17, 1814, 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, 605, 378, 383, 87, 39, 492, 2377, 5349, 16936, 353, 605, 378, 383, 87, 39, 492, 2377, 5349, 16936, 1358, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 225, 445, 2549, 1119, 12, 1119, 389, 2704, 1119, 13, 3903, 31, 203, 203, 225, 445, 2198, 3149, 12, 2867, 389, 5768, 395, 280, 16, 2254, 389, 2316, 6275, 16, 20137, 15305, 1358, 18, 7623, 389, 7095, 16, 2254, 389, 8949, 13, 3903, 8843, 429, 31, 203, 203, 225, 445, 12831, 3605, 3149, 41, 1136, 1435, 3903, 1476, 1135, 261, 11890, 1769, 203, 203, 225, 445, 12831, 3605, 3149, 41, 295, 1435, 3903, 1476, 1135, 261, 11890, 1769, 203, 203, 225, 445, 598, 9446, 41, 1136, 12, 11890, 389, 1132, 13, 3903, 31, 203, 203, 225, 445, 598, 9446, 5157, 12, 11890, 389, 1132, 13, 3903, 31, 203, 203, 225, 445, 598, 9446, 23725, 1435, 3903, 31, 203, 203, 225, 445, 336, 3605, 395, 1383, 1380, 1435, 3903, 1476, 1135, 261, 11890, 1769, 203, 203, 225, 445, 10199, 2933, 1435, 3903, 31, 203, 203, 225, 445, 640, 21056, 8689, 5157, 1435, 3903, 31, 203, 97, 203, 203, 225, 9606, 4991, 1119, 12, 1119, 389, 2019, 13, 288, 203, 565, 2583, 12, 2019, 422, 389, 2019, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 9606, 1338, 2933, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 2596, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 21281, 225, 3885, 12, 203, 2 ]
./full_match/1/0x17B00548003683C423eecce4371b4bA56eEd962b/sources/contracts/access/DramAccessControl.sol
* @inheritdoc IDramAccessControl/
function revokeRole( bytes32 role, address account ) external virtual override onlyRoleOrAdmin(ROLE_MANAGER_ROLE) { if (role == ADMIN_ROLE) revert DirectAdminUpdateError(); _revokeRole(role, account); }
3,169,601
[ 1, 36, 10093, 1599, 1940, 16541, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18007, 2996, 12, 203, 3639, 1731, 1578, 2478, 16, 203, 3639, 1758, 2236, 203, 565, 262, 3903, 5024, 3849, 1338, 2996, 1162, 4446, 12, 16256, 67, 19402, 67, 16256, 13, 288, 203, 3639, 309, 261, 4615, 422, 25969, 67, 16256, 13, 15226, 9908, 4446, 1891, 668, 5621, 203, 3639, 389, 9083, 3056, 2996, 12, 4615, 16, 2236, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xD7cF61161F8f90068944395AaDe32D61BB1ef2AF/sources/MILF.sol
generate the joe pair path of token -> weth make the swap
function swapTokensForAvax(uint256 tokenAmount) private lockTheSwap{ address[] memory path = new address[](2); path[0] = address(this); path[1] = joeV2Router.WAVAX(); _approve(address(this), address(joeV2Router), tokenAmount); joeV2Router.swapExactTokensForAVAXSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); }
4,553,712
[ 1, 7163, 326, 525, 15548, 3082, 589, 434, 1147, 317, 341, 546, 1221, 326, 7720, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 5157, 1290, 3769, 651, 12, 11890, 5034, 1147, 6275, 13, 3238, 2176, 1986, 12521, 95, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 589, 63, 20, 65, 273, 1758, 12, 2211, 1769, 203, 3639, 589, 63, 21, 65, 273, 525, 15548, 58, 22, 8259, 18, 59, 5856, 2501, 5621, 203, 203, 3639, 389, 12908, 537, 12, 2867, 12, 2211, 3631, 1758, 12, 78, 15548, 58, 22, 8259, 3631, 1147, 6275, 1769, 203, 203, 3639, 525, 15548, 58, 22, 8259, 18, 22270, 14332, 5157, 1290, 5856, 2501, 6289, 310, 14667, 1398, 5912, 5157, 12, 203, 5411, 1147, 6275, 16, 203, 5411, 589, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1203, 18, 5508, 203, 3639, 11272, 203, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; contract Voting { // Structures struct Voter { bool isRegistered; bool hasVoted; uint votedProposalId; } struct Proposal { string description; uint voteCount; } // vote mapping struct Vote{ // Subject of the vote string tips; // Owner address address owner; // Winner ID uint winningProposalId; // Status ID WorkflowStatus statusId; //Voter mapping mapping (address => Voter) voters; uint votersCount; // Proposal listing Proposal[] proposals; uint maxVoteCount; } // Enumeration enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } mapping (uint => Vote) votes;// Maps use less gas than arrays uint private votesCount;// So a counter is associated to retrive votes // Events event VoteCreated(uint voteIndex); event VoterRegistered(uint voteIndex, address voterAddress); event ProposalsRegistrationStarted(uint voteIndex); event ProposalsRegistrationEnded(uint voteIndex); event ProposalRegistered(uint voteIndex, uint proposalId); event VotingSessionStarted(uint voteIndex); event VotingSessionEnded(uint voteIndex); event Voted (uint voteIndex, address voter, uint proposalId); event VotesTallied(uint voteIndex); event WorkflowStatusChange(uint voteIndex, WorkflowStatus previousStatus, WorkflowStatus newStatus); modifier onlyOwner(uint index){ require(_isOwner(index, msg.sender), '0');//Ownable: caller can be only the owner of the vote _; } modifier onlyRegistered(uint index){ require(votes[index].voters[msg.sender].isRegistered, '1');//Listed: caller has not been registered by the owner _; } // For internal calls, the sender address should be retrived from the top call function _isOwner(uint index, address _address) private view returns (bool) { return votes[index].owner==_address; } modifier onlyRegisteredOrOwner(uint index){ require(votes[index].owner==msg.sender || votes[index].voters[msg.sender].isRegistered, '2');//Ownable or listed only _; } // Setter and interaction functions // // Add a new vote to the list function newVote(string memory tips) external {// Everyone can add a new vote require(bytes(tips).length>0, '3');//Tips should not be empty //didn't accept empty tips votes[votesCount].tips = tips; votes[votesCount].owner = msg.sender; emit VoteCreated(votesCount); votesCount+=1; } // I decided to use only one function insteed of specific status setter like "setProposalsRegistrationStartedStatus" function setNextWorkflowStatus(uint index) external onlyOwner(index){ require(votes[index].statusId != WorkflowStatus.VotesTallied, '4');//The vote is already done // keep the old status for the "WorkflowStatusChange" event. WorkflowStatus oldStatus = votes[index].statusId; // State machine for the status workflow // 0_ Voters registration by the owner. // 0 => 1_ I defined a minimum of two voters, otherwise the vote would not be necessary. // Proposals registration for they registered address. if (votes[index].statusId==WorkflowStatus.RegisteringVoters){ require(votes[index].votersCount>=2, '5');//We should have at least two voters to continue the workflow votes[index].statusId = WorkflowStatus.ProposalsRegistrationStarted; emit ProposalsRegistrationStarted(index); } // 1 => 2_ I defined a minimum of one proposal because it's the minimum to have an outcome. // Close the registration period. else if (votes[index].statusId==WorkflowStatus.ProposalsRegistrationStarted){ require(votes[index].proposals.length>=1, '6');//We should have at least one Proposal to continue the workflow votes[index].statusId = WorkflowStatus.ProposalsRegistrationEnded; emit ProposalsRegistrationEnded(index); } // 2 => 3_ I did not launch the voting session right afterwards to let the voters see the proposals // Open the votes[index]. else if (votes[index].statusId==WorkflowStatus.ProposalsRegistrationEnded){ votes[index].statusId = WorkflowStatus.VotingSessionStarted; emit VotingSessionStarted(index); } // 3 => 4_ Close the vote else if (votes[index].statusId==WorkflowStatus.VotingSessionStarted){ votes[index].statusId = WorkflowStatus.VotingSessionEnded; emit VotingSessionEnded(index); } // 4 => 5_ I did not launch the votes counting right after the VotingSessionEnded because there is two separated points in the exercice. // But all results are publique so the suspense would not be there anyway. else if (votes[index].statusId==WorkflowStatus.VotingSessionEnded){ votes[index].statusId = WorkflowStatus.VotesTallied; emit VotesTallied(index); } emit WorkflowStatusChange(index, oldStatus, votes[index].statusId); } // Let a vote owner to register any etherum address to take part in the votes. function authorize( uint index, address _address) external onlyOwner(index){ require(votes[index].statusId==WorkflowStatus.RegisteringVoters, '7');//Unable to register anyone after the RegisteringVoters workflow status require(votes[index].voters[_address].isRegistered==false, '8');//Address already registered votes[index].voters[_address] = Voter({isRegistered: true, hasVoted: false, votedProposalId: 0}); // The voter counter exists to ensure that there is a minimum of two. votes[index].votersCount++; emit VoterRegistered(index, _address); } // Registered address can add any proposition description at multiple times function newProposal(uint index, string memory description) external onlyRegistered(index){ require(votes[index].statusId==WorkflowStatus.ProposalsRegistrationStarted, '9');//Unable to register any proposals. Proposals Registration not started or already ended votes[index].proposals.push(Proposal({description: description, voteCount:0})); emit ProposalRegistered(index, votes[index].proposals.length-1); } // Registered address can vote once for a registered proposals function doVote(uint index, uint votedProposalId) external onlyRegistered(index){ require(votes[index].statusId==WorkflowStatus.VotingSessionStarted, '10');//Unable to vote while the current workflow status is not VotingSessionStarted require(votes[index].voters[msg.sender].hasVoted==false, '11');//You can t vote twice require(votes[index].proposals.length>votedProposalId, '12');//votedProposalId doesn t exist votes[index].proposals[votedProposalId].voteCount++; votes[index].voters[msg.sender].hasVoted = true; votes[index].voters[msg.sender].votedProposalId = votedProposalId; votes[index].proposals[votedProposalId].voteCount += 1; // Check the winning proposal if (votes[index].maxVoteCount<votes[index].proposals[votedProposalId].voteCount){ votes[index].winningProposalId = votedProposalId; votes[index].maxVoteCount = votes[index].proposals[votedProposalId].voteCount; } emit Voted(index, msg.sender, votedProposalId); } // Some usefull getter function getVoteCount() external view returns (uint){ return votesCount; } // get the vote purpos at the given index function getVoteTips(uint index) external view returns(string memory){ require(votesCount>index, "13");//Given vote index doesn't exist return votes[index].tips; } // Ask if the sender is the vote owner function isOwner(uint index) external view returns(bool){ require(votesCount>index, "13"); return votes[index].owner==msg.sender; } // Ask if the sender has been registered in the vote by the owner function isRegistered(uint index) external view returns(bool){ require(votesCount>index, "13"); return votes[index].voters[msg.sender].isRegistered; } // Get the current status of the vote as an ID (not very human readeable) function getWorkflowStatus(uint index) external view returns (WorkflowStatus) { require(votesCount>index, "13"); return votes[index].statusId; } function getProposalCount(uint index) external view returns(uint){ require(votesCount>index, "13"); return votes[index].proposals.length; } function getProposalDescriptionById(uint index, uint ProposalId) public view returns (string memory){ require(votesCount>index, "13"); require(votes[index].proposals.length>ProposalId, '12'); return votes[index].proposals[ProposalId].description; } // As explaned in the exercise, everyone can check the final details of the winning proposal so i did'n put the onlyRegistered modifier. function getWinningProposalDescription(uint index) external view returns (string memory){ require(votesCount>index, "13"); require(votes[index].statusId==WorkflowStatus.VotesTallied, '15');//Vote not tallied yet return getProposalDescriptionById(index, votes[index].winningProposalId); } function getProposalVoteCountById(uint index, uint ProposalId) external view onlyRegisteredOrOwner(index) returns (uint){ require(votesCount>index, "13"); require(votes[index].proposals.length>ProposalId, '12'); return votes[index].proposals[ProposalId].voteCount; } function getVotedProposalIdByAddress(uint index, address _address) external view returns (int){ require(votesCount>index, "13"); require(votes[index].statusId==WorkflowStatus.VotesTallied || votes[index].statusId==WorkflowStatus.VotingSessionStarted || votes[index].statusId==WorkflowStatus.VotingSessionEnded, 'Vote not started yet'); require(votes[index].voters[_address].hasVoted, '14');//This address has not voted return int(votes[index].voters[_address].votedProposalId); } function hasVoted(uint index, address _address) external view returns (bool){ require(votesCount>index, "13"); return votes[index].voters[_address].hasVoted; } // get front vote informations function getFullPersonalVoteInfo(uint index) external view returns(string memory, uint, bool, int, bool, uint){ require(votesCount>index, "13"); string memory tips = votes[index].tips; uint state = uint(this.getWorkflowStatus(index)); bool registered = votes[index].voters[msg.sender].isRegistered; int votedIndex = -1; uint winningProposalId = 0; if (registered && this.hasVoted(index, msg.sender)){ votedIndex = this.getVotedProposalIdByAddress(index, msg.sender); winningProposalId = votes[index].winningProposalId; } bool owner = _isOwner(index, msg.sender); return (tips, state, registered, votedIndex, owner, winningProposalId); } }
We should have at least one Proposal to continue the workflow
require(votes[index].proposals.length>=1, '6');
12,942,822
[ 1, 3218, 1410, 1240, 622, 4520, 1245, 19945, 358, 1324, 326, 6095, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 2583, 12, 27800, 63, 1615, 8009, 685, 22536, 18, 2469, 34, 33, 21, 16, 296, 26, 8284, 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 ]
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface TradeBotCommanderV2Interface { // events event ADDEDACCOUNT705(address account); //inject NONSTANDARD NAMING event REMOVEDACCOUNT677(address account); //inject NONSTANDARD NAMING event CALL773(address target, uint256 amount, bytes data, bool ok, bytes returnData); //inject NONSTANDARD NAMING // callable by accounts function PROCESSLIMITORDER517( //inject NONSTANDARD NAMING DharmaTradeBotV1Interface.LimitOrderArguments calldata args, DharmaTradeBotV1Interface.LimitOrderExecutionArguments calldata executionArgs ) external returns (bool ok, uint256 amountReceived); function DEPLOYANDPROCESSLIMITORDER155( //inject NONSTANDARD NAMING address initialSigningKey, // the initial key on the keyring address keyRing, DharmaTradeBotV1Interface.LimitOrderArguments calldata args, DharmaTradeBotV1Interface.LimitOrderExecutionArguments calldata executionArgs ) external returns (bool ok, bytes memory returnData); // only callable by owner function ADDACCOUNT504(address account) external; //inject NONSTANDARD NAMING function REMOVEACCOUNT427(address account) external; //inject NONSTANDARD NAMING function CALLANY167( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external returns (bool ok, bytes memory returnData); // view functions function GETACCOUNTS195() external view returns (address[] memory); //inject NONSTANDARD NAMING function GETTRADEBOT843() external view returns (address tradeBot); //inject NONSTANDARD NAMING } interface DharmaTradeBotV1Interface { struct LimitOrderArguments { address account; address assetToSupply; // Ether = address(0) address assetToReceive; // Ether = address(0) uint256 maximumAmountToSupply; uint256 maximumPriceToAccept; // represented as a mantissa (n * 10^18) uint256 expiration; bytes32 salt; } struct LimitOrderExecutionArguments { uint256 amountToSupply; // will be lower than maximum for partial fills bytes signatures; address tradeTarget; bytes tradeData; } function PROCESSLIMITORDER517( //inject NONSTANDARD NAMING LimitOrderArguments calldata args, LimitOrderExecutionArguments calldata executionArgs ) external returns (uint256 amountReceived); } interface DharmaSmartWalletFactoryV1Interface { function NEWSMARTWALLET679( //inject NONSTANDARD NAMING address userSigningKey ) external returns (address wallet); function GETNEXTSMARTWALLET653( //inject NONSTANDARD NAMING address userSigningKey ) external view returns (address wallet); } interface DharmaKeyRingFactoryV2Interface { function NEWKEYRING243( //inject NONSTANDARD NAMING address userSigningKey, address targetKeyRing ) external returns (address keyRing); function GETNEXTKEYRING535( //inject NONSTANDARD NAMING address userSigningKey ) external view returns (address targetKeyRing); } contract TwoStepOwnable { address private _owner; address private _newPotentialOwner; event OWNERSHIPTRANSFERRED599( //inject NONSTANDARD NAMING address indexed previousOwner, address indexed newOwner ); constructor() internal { _owner = tx.origin; emit OWNERSHIPTRANSFERRED599(address(0), _owner); } function OWNER209() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER726() { //inject NONSTANDARD NAMING require(ISOWNER585(), "TwoStepOwnable: caller is not the owner."); _; } function ISOWNER585() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function TRANSFEROWNERSHIP473(address newOwner) public ONLYOWNER726 { //inject NONSTANDARD NAMING require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } function CANCELOWNERSHIPTRANSFER552() public ONLYOWNER726 { //inject NONSTANDARD NAMING delete _newPotentialOwner; } function ACCEPTOWNERSHIP824() public { //inject NONSTANDARD NAMING require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OWNERSHIPTRANSFERRED599(_owner, msg.sender); _owner = msg.sender; } } contract TradeBotCommanderV2 is TradeBotCommanderV2Interface, TwoStepOwnable { // Track all authorized accounts. address[] private _accounts; // Indexes start at 1, as 0 signifies non-inclusion mapping (address => uint256) private _accountIndexes; DharmaTradeBotV1Interface private immutable _TRADE_BOT; DharmaSmartWalletFactoryV1Interface private immutable _WALLET_FACTORY; DharmaKeyRingFactoryV2Interface private immutable _KEYRING_FACTORY; constructor(address walletFactory, address keyRingFactory, address tradeBot, address[] memory initialAccounts) public { require( walletFactory != address(0) && keyRingFactory != address(0) && tradeBot != address(0), "Missing required constructor arguments." ); _WALLET_FACTORY = DharmaSmartWalletFactoryV1Interface(walletFactory); _KEYRING_FACTORY = DharmaKeyRingFactoryV2Interface(keyRingFactory); _TRADE_BOT = DharmaTradeBotV1Interface(tradeBot); for (uint256 i; i < initialAccounts.length; i++) { address account = initialAccounts[i]; _ADDACCOUNT722(account); } } function PROCESSLIMITORDER517( //inject NONSTANDARD NAMING DharmaTradeBotV1Interface.LimitOrderArguments calldata args, DharmaTradeBotV1Interface.LimitOrderExecutionArguments calldata executionArgs ) external override returns (bool ok, uint256 amountReceived) { require( _accountIndexes[msg.sender] != 0, "Only authorized accounts may trigger limit orders." ); amountReceived = _TRADE_BOT.PROCESSLIMITORDER517( args, executionArgs ); ok = true; } // Deploy a key ring and a smart wallet, then process the limit order. function DEPLOYANDPROCESSLIMITORDER155( //inject NONSTANDARD NAMING address initialSigningKey, // the initial key on the keyring address keyRing, DharmaTradeBotV1Interface.LimitOrderArguments calldata args, DharmaTradeBotV1Interface.LimitOrderExecutionArguments calldata executionArgs ) external override returns (bool ok, bytes memory returnData) { require( _accountIndexes[msg.sender] != 0, "Only authorized accounts may trigger limit orders." ); _DEPLOYNEWKEYRINGIFNEEDED997(initialSigningKey, keyRing); _DEPLOYNEWSMARTWALLETIFNEEDED48(keyRing, args.account); try _TRADE_BOT.PROCESSLIMITORDER517(args, executionArgs) returns (uint256 amountReceived) { return (true, abi.encode(amountReceived)); } catch (bytes memory revertData) { return (false, revertData); } } function ADDACCOUNT504(address account) external override ONLYOWNER726 { //inject NONSTANDARD NAMING _ADDACCOUNT722(account); } function REMOVEACCOUNT427(address account) external override ONLYOWNER726 { //inject NONSTANDARD NAMING _REMOVEACCOUNT899(account); } function CALLANY167( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external override ONLYOWNER726 returns (bool ok, bytes memory returnData) { // Call the specified target and supply the specified amount and data. (ok, returnData) = target.call{value: amount}(data); emit CALL773(target, amount, data, ok, returnData); } function GETACCOUNTS195() external view override returns (address[] memory) { //inject NONSTANDARD NAMING return _accounts; } function GETTRADEBOT843() external view override returns (address tradeBot) { //inject NONSTANDARD NAMING return address(_TRADE_BOT); } function _DEPLOYNEWKEYRINGIFNEEDED997( //inject NONSTANDARD NAMING address initialSigningKey, address expectedKeyRing ) internal returns (address keyRing) { // Only deploy if a contract doesn't already exist at expected address. bytes32 size; assembly { size := extcodesize(expectedKeyRing) } if (size == 0) { require( _KEYRING_FACTORY.GETNEXTKEYRING535(initialSigningKey) == expectedKeyRing, "Key ring to be deployed does not match expected key ring." ); keyRing = _KEYRING_FACTORY.NEWKEYRING243(initialSigningKey, expectedKeyRing); } else { // Note: the key ring at the expected address may have been modified so that // the supplied user signing key is no longer a valid key - therefore, treat // this helper as a way to protect against race conditions, not as a primary // mechanism for interacting with key ring contracts. keyRing = expectedKeyRing; } } function _DEPLOYNEWSMARTWALLETIFNEEDED48( //inject NONSTANDARD NAMING address userSigningKey, // the key ring address expectedSmartWallet ) internal returns (address smartWallet) { // Only deploy if a contract doesn't already exist at expected address. bytes32 size; assembly { size := extcodesize(expectedSmartWallet) } if (size == 0) { require( _WALLET_FACTORY.GETNEXTSMARTWALLET653(userSigningKey) == expectedSmartWallet, "Smart wallet to be deployed does not match expected smart wallet." ); smartWallet = _WALLET_FACTORY.NEWSMARTWALLET679(userSigningKey); } else { // Note: the smart wallet at the expected address may have been modified // so that the supplied user signing key is no longer a valid key. // Therefore, treat this helper as a way to protect against race // conditions, not as a primary mechanism for interacting with smart // wallet contracts. smartWallet = expectedSmartWallet; } } function _ADDACCOUNT722(address account) internal { //inject NONSTANDARD NAMING require( _accountIndexes[account] == 0, "Account matching the provided account already exists." ); _accounts.push(account); _accountIndexes[account] = _accounts.length; emit ADDEDACCOUNT705(account); } function _REMOVEACCOUNT899(address account) internal { //inject NONSTANDARD NAMING uint256 removedAccountIndex = _accountIndexes[account]; require( removedAccountIndex != 0, "No account found matching the provided account." ); // swap account to remove with the last one then pop from the array. address lastAccount = _accounts[_accounts.length - 1]; _accounts[removedAccountIndex - 1] = lastAccount; _accountIndexes[lastAccount] = removedAccountIndex; _accounts.pop(); delete _accountIndexes[account]; emit REMOVEDACCOUNT677(account); } }
Note: the smart wallet at the expected address may have been modified so that the supplied user signing key is no longer a valid key. Therefore, treat this helper as a way to protect against race conditions, not as a primary mechanism for interacting with smart wallet contracts.
if (size == 0) { require( _WALLET_FACTORY.GETNEXTSMARTWALLET653(userSigningKey) == expectedSmartWallet, "Smart wallet to be deployed does not match expected smart wallet." ); smartWallet = _WALLET_FACTORY.NEWSMARTWALLET679(userSigningKey); smartWallet = expectedSmartWallet; }
12,831,829
[ 1, 8067, 30, 326, 13706, 9230, 622, 326, 2665, 1758, 2026, 1240, 2118, 4358, 1427, 716, 326, 4580, 729, 10611, 498, 353, 1158, 7144, 279, 923, 498, 18, 17189, 16, 10116, 333, 4222, 487, 279, 4031, 358, 17151, 5314, 17996, 4636, 16, 486, 487, 279, 3354, 12860, 364, 16592, 310, 598, 13706, 9230, 20092, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 309, 261, 1467, 422, 374, 13, 288, 203, 1377, 2583, 12, 203, 3639, 389, 59, 1013, 15146, 67, 16193, 18, 3264, 25539, 7303, 4928, 59, 1013, 15146, 26, 8643, 12, 1355, 12322, 653, 13, 422, 2665, 23824, 16936, 16, 203, 3639, 315, 23824, 9230, 358, 506, 19357, 1552, 486, 845, 2665, 13706, 9230, 1199, 203, 1377, 11272, 203, 1377, 13706, 16936, 273, 389, 59, 1013, 15146, 67, 16193, 18, 5407, 2651, 49, 4928, 59, 1013, 15146, 26, 7235, 12, 1355, 12322, 653, 1769, 203, 1377, 13706, 16936, 273, 2665, 23824, 16936, 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 ]
./full_match/1/0x84b68BD08155D5BB4FB8c40882838684AB20F4f6/sources/Users/225153/Projects/zzz-contracts/contracts/LPTokenWrapper.sol
Align balances for the user
function withdraw(uint256 amount) public virtual { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); }
3,068,145
[ 1, 10044, 324, 26488, 364, 326, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 9446, 12, 11890, 5034, 3844, 13, 1071, 5024, 288, 203, 3639, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1717, 12, 8949, 1769, 203, 3639, 389, 70, 26488, 63, 3576, 18, 15330, 65, 273, 389, 70, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 8949, 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 ]
./partial_match/42/0xF9712B026A1dEFF115BB5ee5172c76A80D2f6672/sources/XplosiveBNB.sol
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks. Arithmetic operations in Solidity wrap on overflow. This can easily result in bugs, because programmers usually assume that an overflow raises an error, which is the standard behavior in high level programming languages. `SafeMath` restores this intuition by reverting the transaction when an operation overflows. Using this library instead of the unchecked operations eliminates an entire class of bugs, so it's recommended to use it always./
library XSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a,m); uint256 d = sub(c,1); return mul(div(d,m),m); } function divRound(uint256 x, uint256 y) internal pure returns (uint256) { require(y != 0, "Div by zero"); uint256 r = x / y; if (x % y != 0) { r = r + 1; } return r; } function divRound(uint256 x, uint256 y) internal pure returns (uint256) { require(y != 0, "Div by zero"); uint256 r = x / y; if (x % y != 0) { r = r + 1; } return r; } }
9,069,106
[ 1, 24114, 1879, 348, 7953, 560, 1807, 30828, 5295, 598, 3096, 9391, 4271, 18, 27443, 5295, 316, 348, 7953, 560, 2193, 603, 9391, 18, 1220, 848, 17997, 563, 316, 22398, 16, 2724, 5402, 81, 414, 11234, 6750, 716, 392, 9391, 14183, 392, 555, 16, 1492, 353, 326, 4529, 6885, 316, 3551, 1801, 5402, 11987, 8191, 18, 1375, 9890, 10477, 68, 3127, 3485, 333, 509, 89, 608, 635, 15226, 310, 326, 2492, 1347, 392, 1674, 9391, 87, 18, 11637, 333, 5313, 3560, 434, 326, 22893, 5295, 19229, 4174, 392, 7278, 667, 434, 22398, 16, 1427, 518, 1807, 14553, 358, 999, 518, 3712, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 12083, 1139, 9890, 10477, 288, 203, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 2583, 12, 71, 1545, 279, 16, 315, 9890, 10477, 30, 2719, 9391, 8863, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 720, 12, 69, 16, 324, 16, 315, 9890, 10477, 30, 720, 25693, 9391, 8863, 203, 565, 289, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 16, 533, 3778, 9324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 70, 1648, 279, 16, 9324, 1769, 203, 3639, 2254, 5034, 276, 273, 279, 300, 324, 31, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 16, 315, 9890, 10477, 30, 23066, 9391, 8863, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 2 ]